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.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(mcp): read the Content plan and where drafts went, and mark a draft published (#1715)
Cihan72f602f0e7c2
diff --git a/docs/guides/mcp-server.mdx b/docs/guides/mcp-server.mdxindex e771580db..c9739f52a 100644--- a/docs/guides/mcp-server.mdx+++ b/docs/guides/mcp-server.mdx@@ -220,7 +220,7 @@ instead.## Available tools-The MCP server exposes **53 tools**. Descriptions below match+The MCP server exposes **55 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 userintent, not during exploratory queries.@@ -299,23 +299,29 @@ curl "https://app.ansvisor.com/api/mcp/mentions/summary?brand_id=<brand_id>&plat| Tool | What it does | Writes || --- | --- | --- || `list_content_opportunities` | Content gaps ranked by opportunity score — where the brand is losing visibility. | |+| `get_content_plan` | The Content plan, as **Content → Plan** ranks it by the Priority Score: what to create, optimize or protect next, why, the score's parts, the draft already being written and the rows marked a priority. Over 7, 30 or 90 days; optional `card`. | || `get_content_opportunity` | Full details for one opportunity, including metrics, intent, competitors, and any existing brief. | || `generate_content_brief` | Generate or overwrite an AI content brief for an opportunity (LLM cost/latency). | **yes** || `update_opportunity_status` | Move an opportunity through workflow states (`new`, `reviewed`, `sent`, `in_progress`, `done`, `dismissed`). | **yes** |+The plan is also available over REST with the same `ans_` key: `GET /api/mcp/content-plan?brand_id=<brand_id>&days=30`, with `card` as an optional query parameter.+### Content Editor-Drafts are read and written as a person would in the editor. Ansvisor never publishes, 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.+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": "…" }`.| Tool | What it does | Writes || --- | --- | --- |-| `list_content_drafts` | The brand's drafts, latest changed first (up to 100), with status, method (`create` or `optimize`), author, open suggestions and the editor path; filter by `status`. | |-| `get_content_draft` | One draft: its HTML, its numbered passages (`locked` ones AI answers quote today), where and since when the page is live, its Action Center action, the open suggestions and the only pages a suggestion may link to. | |+| `list_content_drafts` | The brand's drafts, latest changed first (up to 100), with status, method (`create` or `optimize`), author, open suggestions and the editor path; filter by `status`. Each says where it was last sent (`last_send`: status, target, when, the error, where it went live) and whether its shopping links still sell (`shopping_links`). | |+| `get_content_draft` | One draft: its HTML, its numbered passages (`locked` ones AI answers quote today), where and since when the page is live, its Action Center action, the open suggestions and the only pages a suggestion may link to; with `last_send`, `shopping_links` and, on an online shop's page, its `shopping_path` (the category pages and products it should link). | || `get_content_sources` | What the draft draws on over 30 days, as the Sources tab shows it: prompts, AI searches (fan-outs), cited pages, Search Console queries and the person's choices. | || `get_content_impact` | What the draft's live page earns (citations, AI visits, Google clicks, the prompts citing it) against the period before, as the Live page tab reads it. Only for a draft of a live page. | || `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** |+| `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** |### Site auditdiff --git a/server/src/lib/content-published.js b/server/src/lib/content-published.jsindex c20648b43..95d6bb4f5 100644--- a/server/src/lib/content-published.js+++ b/server/src/lib/content-published.js@@ -327,3 +327,40 @@ export async function publishDraft(draft, url, actorId) {const { taskCompleted } = await markDraftPublished(draft.id, url, { at, actorId, onDomain });return { publishedUrl: url, publishedAt: at, taskCompleted, onBrandDomain: onDomain };}++/**+ * The same mark for an MCP API key (`mark_content_draft_published`): the key+ * carries no session, so the web MCP layer passes the key's organization and+ * user. As the route, the draft must be the organization's and not archived;+ * null when it isn't (another's reads as not there). A page already+ * published at `url` is left as it is, its live-since time kept, so a call+ * made again changes nothing (the tool says it is idempotent).+ *+ * @param {{ draftId: string, url: string, userId: string, orgId: string }} input+ * @returns {Promise<{ publishedUrl: string, publishedAt: string, taskCompleted: boolean, onBrandDomain: boolean } | null>}+ */+export async function publishDraftForKeyUser({ draftId, url, userId, orgId }) {+ const { data: draft, error } = await supabaseAdmin+ .from('content_drafts')+ .select(+ 'id, brand_id, action_id, archived_at, status, published_url, published_at, brands!inner(organization_id)',+ )+ .eq('id', draftId)+ .eq('brands.organization_id', orgId)+ .maybeSingle();+ if (error) throw new Error(error.message);+ if (!draft || draft.archived_at) return null;+ if (draft.status === 'published' && draft.published_url === url) {+ return {+ publishedUrl: url,+ publishedAt: draft.published_at,+ taskCompleted: false,+ onBrandDomain: await onBrandDomains(draft.brand_id, url),+ };+ }+ return publishDraft(+ { id: draft.id, brand_id: draft.brand_id, action_id: draft.action_id },+ url,+ userId,+ );+}diff --git a/server/src/lib/content-published.test.js b/server/src/lib/content-published.test.jsindex 3bde29de4..ce387f87c 100644--- a/server/src/lib/content-published.test.js+++ b/server/src/lib/content-published.test.js@@ -61,7 +61,8 @@ vi.mock('./logger.js', () => ({logger: { warn: (...args) => events.push(args), error: () => {} },}));-const { liveAddress, markDeliveryPublished, publishDraft } = await import('./content-published.js');+const { liveAddress, markDeliveryPublished, publishDraft, publishDraftForKeyUser } =+ await import('./content-published.js');const LIVE = 'https://www.acme.example/blog/cold-brew';@@ -282,6 +283,64 @@ describe('publishDraft', () => {});});+describe('publishDraftForKeyUser', () => {+ // The fake database reads the embedded organization as a column of its own.+ const ofOrg = (org) => Object.assign(tables.content_drafts[0], { 'brands.organization_id': org });++ it('publishes the organization’s draft as the key’s user, as the route does', async () => {+ ofOrg('org1');+ expect(+ await publishDraftForKeyUser({ draftId: 'dr1', url: LIVE, userId: 'u1', orgId: 'org1' }),+ ).toMatchObject({ publishedUrl: LIVE, taskCompleted: false, onBrandDomain: true });+ expect(tables.content_drafts[0]).toMatchObject({ status: 'published', published_url: LIVE });+ });++ it('leaves another organization’s draft, and an archived one, alone', async () => {+ ofOrg('org2');+ expect(+ await publishDraftForKeyUser({ draftId: 'dr1', url: LIVE, userId: 'u1', orgId: 'org1' }),+ ).toBeNull();+ ofOrg('org1');+ tables.content_drafts[0].archived_at = '2026-10-20T10:00:00Z';+ expect(+ await publishDraftForKeyUser({ draftId: 'dr1', url: LIVE, userId: 'u1', orgId: 'org1' }),+ ).toBeNull();+ expect(tables.content_drafts[0].published_url ?? null).toBeNull();+ });++ it('changes nothing for a page already published at the address, its live-since kept', async () => {+ ofOrg('org1');+ const since = '2026-10-21T08:00:00Z';+ Object.assign(tables.content_drafts[0], {+ status: 'published',+ published_url: LIVE,+ published_at: since,+ action_id: 'a1',+ });+ tables.action_tasks = [task('t1', 'publish_content')];+ const before = clone(tables);++ expect(+ await publishDraftForKeyUser({ draftId: 'dr1', url: LIVE, userId: 'u1', orgId: 'org1' }),+ ).toEqual({+ publishedUrl: LIVE,+ publishedAt: since,+ taskCompleted: false,+ onBrandDomain: true,+ });+ expect(tables).toEqual(before);+ expect(rpcs).toEqual([]);++ // At another address, it moves, as the editor's Mark published moves it.+ const moved = 'https://www.acme.example/blog/cold-brew-at-home';+ expect(+ await publishDraftForKeyUser({ draftId: 'dr1', url: moved, userId: 'u1', orgId: 'org1' }),+ ).toMatchObject({ publishedUrl: moved });+ expect(tables.content_drafts[0].published_url).toBe(moved);+ expect(tables.content_drafts[0].published_at).not.toBe(since);+ });+});+describe('markDeliveryPublished', () => {it('tells the action of a page its CMS published, as a person’s publish does', async () => {tables.content_drafts[0].action_id = 'a1';diff --git a/server/src/server.js b/server/src/server.jsindex 9fc21092e..6d0449b66 100644--- a/server/src/server.js+++ b/server/src/server.js@@ -41,6 +41,7 @@ import { generateBriefForOpportunity } from './routes/content.js';import webhookContentCallbackRoutes from './routes/webhook-content-callback.js';import webhookContentDraftCallbackRoutes from './routes/webhook-content-draft-callback.js';import { sendImproveActionForKeyUser } from './routes/prompts.js';+import { liveAddress, publishDraftForKeyUser } from './lib/content-published.js';import { readOpportunityInbox, startAutoAudits, startSiteAuditForBrand } from './routes/audits.js';import { sweepAutoAudits } from './lib/audit/auto-audit-sweep.js';import { PlanLimitError, getAiUsage, getSiteAuditQuotaStatus } from './lib/plan-guard.js';@@ -604,6 +605,57 @@ app.post('/api/internal/prompts/:promptId/improve/action', async (req, res) => {}});+// --- Internal publish endpoint (CRON_SECRET auth, called by web MCP layer) ---+// A page marked Published at its live address for an MCP API key+// (`mark_content_draft_published`), as the editor's Mark published does+// (POST /api/content-drafts/:draftId/publish). The web MCP layer passes the+// key's organization and user; the draft must be that organization's.+const internalPublishBody = z.object({+ url: z.string().max(8192),+ userId: z.guid(),+ orgId: z.guid(),+});++app.post('/api/internal/content-drafts/:draftId/publish', async (req, res) => {+ const secret = req.headers.authorization?.replace('Bearer ', '');+ if (!process.env.CRON_SECRET || secret !== process.env.CRON_SECRET) {+ return res.status(401).json({ success: false, message: 'Unauthorized' });+ }++ const draftId = z.guid().safeParse(req.params.draftId);+ const body = internalPublishBody.safeParse(req.body ?? {});+ if (!draftId.success || !body.success) {+ return res.status(400).json({ success: false, code: 'invalid', message: 'Invalid request' });+ }+ const url = liveAddress(body.data.url);+ if (!url) {+ return res.status(400).json({+ success: false,+ code: 'invalid_url',+ message: 'Give the http(s) address the page is live at, with no sign-in details.',+ });+ }+ try {+ const result = await publishDraftForKeyUser({+ draftId: draftId.data,+ url,+ userId: body.data.userId,+ orgId: body.data.orgId,+ });+ if (!result) {+ return res+ .status(404)+ .json({ success: false, code: 'not_found', message: 'Draft not found' });+ }+ return res.json({ success: true, ...result });+ } catch (err) {+ req.log.error({ err: { name: err?.name } }, 'internal content draft publish error');+ return res+ .status(500)+ .json({ success: false, message: 'The page could not be marked published' });+ }+});+// --- Internal citation-recount endpoint (CRON_SECRET auth, called by the web// layer whenever a brand's domain list changes) ---// Recomputes prompt_results.citation_count for the brand against its currentdiff --git a/web/src/app/api/mcp/content-drafts/[id]/published/route.test.ts b/web/src/app/api/mcp/content-drafts/[id]/published/route.test.tsnew file mode 100644index 000000000..3196c862a--- /dev/null+++ b/web/src/app/api/mcp/content-drafts/[id]/published/route.test.ts@@ -0,0 +1,64 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++/** POST /api/mcp/content-drafts/[id]/published: the REST mirror of mark_content_draft_published. */++const { markContentDraftPublishedFor } = vi.hoisted(() => ({+ markContentDraftPublishedFor: 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/supabase/admin', () => ({ supabaseAdmin: {} }));+vi.mock('@/lib/mcp/content-delivery', () => ({ markContentDraftPublishedFor }));++const { POST } = await import('./route');+const { SubscriptionInactiveError } = await import('@/lib/mcp/subscription-gate');++const DRAFT = '11111111-2222-3333-4444-555555555555';+const post = (body: unknown, id = DRAFT) =>+ POST(+ new Request(`http://localhost/api/mcp/content-drafts/${id}/published`, {+ method: 'POST',+ body: JSON.stringify(body),+ }),+ { params: Promise.resolve({ id }) },+ );++beforeEach(() => {+ markContentDraftPublishedFor.mockReset();+});++describe('POST /api/mcp/content-drafts/[id]/published', () => {+ it('marks the page live at the address given', async () => {+ markContentDraftPublishedFor.mockResolvedValue({ published_url: 'https://acme.example/x' });+ const res = await post({ url: 'https://acme.example/x' });+ expect(res.status).toBe(200);+ expect(markContentDraftPublishedFor).toHaveBeenCalledWith(+ expect.anything(),+ DRAFT,+ 'https://acme.example/x',+ );+ });++ it('answers 400 for a request it cannot read, an address it refuses, and 404 for a draft not there', async () => {+ expect((await post({ url: 'https://acme.example/x' }, 'not-a-draft')).status).toBe(400);+ expect((await post({})).status).toBe(400);+ markContentDraftPublishedFor.mockResolvedValueOnce({ error: 'invalid_url', message: 'No' });+ expect((await post({ url: 'ftp://x' })).status).toBe(400);+ markContentDraftPublishedFor.mockResolvedValueOnce({ error: 'not_found', message: 'No' });+ expect((await post({ url: 'https://acme.example/x' })).status).toBe(404);+ });++ it('answers 402 for a read-only workspace', async () => {+ markContentDraftPublishedFor.mockRejectedValueOnce(new SubscriptionInactiveError());+ const res = await post({ url: 'https://acme.example/x' });+ expect(res.status).toBe(402);+ expect(await res.json()).toMatchObject({ code: 'subscription_inactive' });+ });+});diff --git a/web/src/app/api/mcp/content-drafts/[id]/published/route.ts b/web/src/app/api/mcp/content-drafts/[id]/published/route.tsnew file mode 100644index 000000000..dba64d349--- /dev/null+++ b/web/src/app/api/mcp/content-drafts/[id]/published/route.ts@@ -0,0 +1,34 @@+import { NextResponse } from 'next/server';+import { z } from 'zod';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { markContentDraftPublishedFor } from '@/lib/mcp/content-delivery';+import { failedCallResponse } from '@/lib/mcp/subscription-gate';+import { contentUuid } from '@/lib/mcp/content-schemas';++const body = z.object({ url: z.string().max(2048) });++/**+ * POST /api/mcp/content-drafts/[id]/published — REST mirror of+ * `mark_content_draft_published`. Body: { url }.+ */+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 = body.safeParse(await req.json().catch(() => ({})));+ if (!contentUuid.safeParse(id).success || !parsed.success) {+ return NextResponse.json({ error: 'Invalid request' }, { status: 400 });+ }+ try {+ const result = await markContentDraftPublishedFor(auth, id, parsed.data.url);+ if ('error' in result) {+ return NextResponse.json(+ { error: result.message, code: result.error },+ { status: result.error === 'not_found' ? 404 : 400 },+ );+ }+ return NextResponse.json(result);+ } catch (err) {+ return failedCallResponse(err);+ }+}diff --git a/web/src/app/api/mcp/content-plan/route.test.ts b/web/src/app/api/mcp/content-plan/route.test.tsnew file mode 100644index 000000000..15c1364df--- /dev/null+++ b/web/src/app/api/mcp/content-plan/route.test.ts@@ -0,0 +1,58 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++/** GET /api/mcp/content-plan: the REST mirror of get_content_plan. */++const { getContentPlanFor } = vi.hoisted(() => ({ getContentPlanFor: 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-plan', () => ({ getContentPlanFor }));++const { GET } = await import('./route');++const BRAND = '11111111-2222-3333-4444-555555555555';+const OTHER = '66666666-7777-8888-9999-000000000000';+const get = (query: string) => GET(new Request(`http://localhost/api/mcp/content-plan${query}`));++beforeEach(() => {+ getContentPlanFor.mockReset();+});++describe('GET /api/mcp/content-plan', () => {+ it("answers the brand's plan over the days and card asked", async () => {+ getContentPlanFor.mockResolvedValue({ days: 7, rows: [] });+ const res = await get(`?brand_id=${BRAND}&days=7&card=protect`);+ expect(await res.json()).toEqual({ plan: { days: 7, rows: [] } });+ expect(getContentPlanFor).toHaveBeenCalledWith(expect.anything(), {+ brandId: BRAND,+ days: 7,+ card: 'protect',+ });+ });++ it('reads 30 days without a period, and refuses one it does not offer', async () => {+ getContentPlanFor.mockResolvedValue({ days: 30, rows: [] });+ await get(`?brand_id=${BRAND}`);+ expect(getContentPlanFor.mock.calls[0][1]).toMatchObject({ days: 30 });+ expect((await get(`?brand_id=${BRAND}&days=14`)).status).toBe(400);+ expect((await get(`?brand_id=${BRAND}&card=later`)).status).toBe(400);+ expect((await get('')).status).toBe(400);+ });++ it('refuses a brand_id that is not a UUID, before reading anything', async () => {+ const res = await get('?brand_id=brand-1');+ expect(res.status).toBe(400);+ expect(getContentPlanFor).not.toHaveBeenCalled();+ });++ it("answers 404 for another organization's brand", async () => {+ getContentPlanFor.mockResolvedValue(null);+ expect((await get(`?brand_id=${OTHER}`)).status).toBe(404);+ });+});diff --git a/web/src/app/api/mcp/content-plan/route.ts b/web/src/app/api/mcp/content-plan/route.tsnew file mode 100644index 000000000..11b9267e0--- /dev/null+++ b/web/src/app/api/mcp/content-plan/route.ts@@ -0,0 +1,43 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { getContentPlanFor } from '@/lib/mcp/content-plan';+import { contentUuid } from '@/lib/mcp/content-schemas';+import { PLAN_CARDS, PLAN_PERIODS, type PlanCard, type PlanPeriod } from '@/lib/content/plan';++/** GET /api/mcp/content-plan — REST mirror of the `get_content_plan` 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 brandId = contentUuid.safeParse(url.searchParams.get('brand_id'));+ if (!brandId.success) {+ return NextResponse.json({ error: 'brand_id must be a brand UUID' }, { status: 400 });+ }+ const days = Number(url.searchParams.get('days') ?? 30);+ if (!(PLAN_PERIODS as readonly number[]).includes(days)) {+ return NextResponse.json({ error: 'days must be 7, 30 or 90' }, { status: 400 });+ }+ const card = url.searchParams.get('card');+ if (card && !(PLAN_CARDS as readonly string[]).includes(card)) {+ return NextResponse.json(+ { error: 'card must be create, optimize, protect or priority' },+ { status: 400 },+ );+ }++ try {+ const plan = await getContentPlanFor(auth, {+ brandId: brandId.data,+ days: days as PlanPeriod,+ card: (card as PlanCard | null) ?? undefined,+ });+ if (plan === null) {+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });+ }+ return NextResponse.json({ plan });+ } catch (err) {+ const message = err instanceof Error ? err.message : 'Failed';+ return NextResponse.json({ error: message }, { status: 500 });+ }+}diff --git a/web/src/lib/actions/content-plan.ts b/web/src/lib/actions/content-plan.tsindex 489e2ff60..bb1b4783c 100644--- a/web/src/lib/actions/content-plan.ts+++ b/web/src/lib/actions/content-plan.ts@@ -4,38 +4,19 @@ import { z } from 'zod';import { createClient } from '@/lib/supabase/server';import { getSuggestionSourceStates } from '@/lib/actions/integrations';import { updateOpportunityStatus } from '@/lib/actions/content';-import { readAssignees } from '@/lib/action-center/assignees';-import { memberLabel } from '@/lib/action-center/display';-import type { DraftMethod } from '@/lib/content/drafts';import type { PlanConversions } from '@/lib/content/conversions';import type { CitedAddress, PlanResults } from '@/lib/content/plan-mix';+import { PLAN_PERIODS, type PlanPeriod } from '@/lib/content/plan';import {- PLAN_PERIODS,- type PlanAnswers,- type PlanDraft,- type PlanMark,- type PlanOpportunity,- type PlanPage,- type PlanPeriod,- type PlanTracking,-} from '@/lib/content/plan';+ OPEN_OPPORTUNITY_STATUSES,+ OPPORTUNITY_KEY,+ opportunityIdOf,+ readContentPlan,+ type ContentPlanRead,+} from '@/lib/content/plan-read';import { googleSourceStatus } from '@/lib/traffic-sources';import { assertWritable } from '@/lib/subscription-guard';-/**- * What the Content plan (CE-014) is built from, read through the signed-in- * member's session: the brand's pages as AI cites them (content_plan_pages,- * 00220), its open opportunities for its own pages, the drafts still being- * written (with who their Action Center task is assigned to), and the rows- * marked as a priority or hidden (content_plan_marks, 00229).- * lib/content/plan.ts ranks them.- */--/** Open opportunities, as New content offers them. */-const OPEN_OPPORTUNITY_STATUSES = ['new', 'reviewed', 'sent', 'in_progress'];-const OPPORTUNITY_LIMIT = 200;-const DRAFT_LIMIT = 500;-const planInput = z.object({brandId: z.guid(),days: z.union([@@ -45,176 +26,22 @@ const planInput = z.object({]),});-const text = (value: unknown) => (typeof value === 'string' ? value.trim() : '');--const OPPORTUNITY_COLUMNS = 'id, title, decision, opportunity_score, brief, source_data';-const OPPORTUNITY_KEY = 'opportunity:';/**- * The opportunity a row's key names (`opportunity:<id>`), or null for a- * page's row. The server reads it from the key the mark is written under,- * so a row's status change can't land on another opportunity.+ * What the Content plan (CE-014) is built from (readContentPlan), read+ * through the signed-in member's session.*/-function opportunityIdOf(rowKey: string): string | null {- return rowKey.startsWith(OPPORTUNITY_KEY) ? rowKey.slice(OPPORTUNITY_KEY.length) : null;-}-export async function getContentPlan(brandId: string,days: PlanPeriod,-): Promise<{- pages: PlanPage[];- answers: PlanAnswers;- tracking: PlanTracking;- opportunities: PlanOpportunity[];- drafts: PlanDraft[];- marks: PlanMark[];-} | null> {+): Promise<ContentPlanRead | null> {if (!planInput.safeParse({ brandId, days }).success) throw new Error('invalid');const supabase = await createClient();- const [userRes, pagesRes, opportunitiesRes, draftsRes, marksRes] = await Promise.all([- supabase.auth.getUser(),- supabase.rpc('content_plan_pages', { p_brand_id: brandId, p_days: days }),- supabase- .from('content_opportunities')- .select(OPPORTUNITY_COLUMNS)- .eq('brand_id', brandId)- .eq('type', 'owned')- .in('status', OPEN_OPPORTUNITY_STATUSES)- .order('opportunity_score', { ascending: false })- .limit(OPPORTUNITY_LIMIT),- supabase- .from('content_drafts')- .select('id, author, created_by, method, opportunity_id, source_url, action_id')- .eq('brand_id', brandId)- .in('status', ['draft', 'in_review', 'ready'])- // An archived draft (00233) is set aside: the row starts afresh.- .is('archived_at', null)- .order('updated_at', { ascending: false })- .limit(DRAFT_LIMIT),- supabase- .from('content_plan_marks')- .select('row_key, priority, hidden_at')- .eq('brand_id', brandId),- ]);- if (pagesRes.error) throw new Error(pagesRes.error.message);- if (opportunitiesRes.error) throw new Error(opportunitiesRes.error.message);- if (draftsRes.error) throw new Error(draftsRes.error.message);- if (marksRes.error) throw new Error(marksRes.error.message);- // Null: not the member's brand.- if (!pagesRes.data) return null;- const me = userRes.data.user?.id ?? null;-- const read = pagesRes.data as unknown as {- pages?: PlanPage[];- answers?: Partial<PlanAnswers>;- prevFrom?: string;- trackedSince?: string | null;- };- const answers = {- cur: Number(read.answers?.cur ?? 0),- prev: Number(read.answers?.prev ?? 0),- };- const tracking = {- prevFrom: read.prevFrom ?? null,- trackedSince: read.trackedSince ?? null,- };- const pages = (read.pages ?? []).map((p) => ({- page: p.page,- title: p.title ?? null,- citations: { cur: Number(p.citations?.cur ?? 0), prev: Number(p.citations?.prev ?? 0) },- platformsDown: Array.isArray(p.platformsDown) ? p.platformsDown : [],- aiVisits: Number(p.aiVisits ?? 0),- // Null with conversions off (00291), or from a database before it.- conversions:- p.conversions === null || p.conversions === undefined ? null : Number(p.conversions),- }));-- const marks = (marksRes.data ?? []).map(- (m): PlanMark => ({ rowKey: m.row_key, priority: m.priority, hidden: m.hidden_at !== null }),- );- // A hidden opportunity's row was dismissed with it: read it too, to show- // again, while it is still dismissed (not completed or reopened since).- const openIds = new Set((opportunitiesRes.data ?? []).map((o) => o.id));- const hiddenIds = marks- .filter((m) => m.hidden)- .map((m) => opportunityIdOf(m.rowKey))- .filter((id): id is string => id !== null && z.guid().safeParse(id).success)- .filter((id) => !openIds.has(id));- const hiddenRes = hiddenIds.length- ? await supabase- .from('content_opportunities')- .select(OPPORTUNITY_COLUMNS)- .eq('brand_id', brandId)- .eq('status', 'dismissed')- .in('id', hiddenIds)- : { data: [], error: null };- if (hiddenRes.error) throw new Error(hiddenRes.error.message);-- const opportunities = [...(opportunitiesRes.data ?? []), ...(hiddenRes.data ?? [])].map(- (o): PlanOpportunity => {- const sd = (o.source_data ?? {}) as Record<string, unknown>;- const brief = (o.brief ?? null) as { suggestedTitle?: unknown } | null;- const target = Array.isArray(sd.targetPages)- ? (sd.targetPages as { url?: unknown; title?: unknown }[]).find((p) => text(p?.url))- : undefined;- return {- id: o.id,- title: o.title,- pageTitle: text(brief?.suggestedTitle) || null,- decision: o.decision,- score: Number(o.opportunity_score ?? 0),- targetPage: target ? text(target.url) : null,- targetTitle: text(target?.title) || null,- competitorsCited: Array.isArray(sd.competitorsCited)- ? sd.competitorsCited.map(text).filter(Boolean).slice(0, 2)- : [],- visibility: typeof sd.visibilityScore === 'number' ? sd.visibilityScore : null,- prompts: Array.isArray(sd.prompts) ? sd.prompts.length : 0,- assetType: Array.isArray(sd.assets)- ? text((sd.assets as { type?: unknown }[])[0]?.type) || null- : null,- };- },- );-- // Who each draft's Action Center task is assigned to.- const actionIds = [- ...new Set((draftsRes.data ?? []).map((d) => d.action_id).filter(Boolean)),- ] as string[];- const actionsRes = actionIds.length- ? await supabase.from('actions').select('id, assignee_id').in('id', actionIds)- : { data: [], error: null };- if (actionsRes.error) throw new Error(actionsRes.error.message);- const assigneeOf = new Map(- (actionsRes.data ?? []).map((a) => [a.id as string, a.assignee_id as string | null]),- );- const people = await readAssignees(+ return readContentPlan(supabase,brandId,- [...assigneeOf.values()].filter(Boolean) as string[],+ days,+ supabase.auth.getUser().then(({ data }) => data.user?.id ?? null),);-- const drafts = (draftsRes.data ?? []).map((d): PlanDraft => {- const assigneeId = d.action_id ? (assigneeOf.get(d.action_id) ?? null) : null;- const person = assigneeId ? people.get(assigneeId) : undefined;- return {- id: d.id,- author: d.author === 'agent' ? 'agent' : 'user',- isMine: me !== null && d.created_by === me,- method: d.method as DraftMethod,- opportunityId: d.opportunity_id,- sourceUrl: d.source_url,- actionId: d.action_id ?? null,- assignee: person- ? {- id: person.id,- name: memberLabel({ fullName: person.fullName, email: person.email ?? '' }),- }- : null,- };- });-- return { pages, answers, tracking, opportunities, drafts, marks };}const markInput = z.object({diff --git a/web/src/lib/content/cms-send-client.ts b/web/src/lib/content/cms-send-client.tsindex b31252ac8..160e1c754 100644--- a/web/src/lib/content/cms-send-client.ts+++ b/web/src/lib/content/cms-send-client.ts@@ -2,6 +2,7 @@ import { BROWSER_API_BASE_URL } from '@/config/api';import { apiFailure } from '@/lib/api-failure';import { createClient } from '@/lib/supabase/client';import type { CmsFields, CmsPage } from '@/lib/content/cms-send';+import { lastSend } from '@/lib/content/cms-status';/*** Send to CMS from the browser (#1331), through the API's same-origin proxy:@@ -213,36 +214,6 @@ export interface CmsStatus {/** Ids a read takes: content_draft_last_deliveries (00262) reads up to 500. */const STATUS_IDS_PER_READ = 500;-/**- * A send still queued after this was left by a server that stopped mid-batch- * (00262 closes it at the workspace's next send): it reads as interrupted,- * so neither the Library nor the editor waits on it or says it is still- * going. Read by the browser's clock: one 30 minutes fast would read a send- * under way as interrupted, until its next read.- */-const INTERRUPTED_AFTER_MS = 30 * 60_000;--/** A send as the Library and the editor read it: one left queued, as interrupted. */-function lastSend(row: {- status: string;- created_at: string;- sent_at: string | null;- published_at: string | null;- error: string | null;- target?: string | null;-}): { status: CmsDelivery['status']; target: CmsTarget; at: string; error: string | null } {- const interrupted =- row.status === 'queued' && Date.parse(row.created_at) < Date.now() - INTERRUPTED_AFTER_MS;- return {- status: interrupted ? 'failed' : (row.status as CmsDelivery['status']),- target:- row.target === 'webflow' || row.target === 'wordpress' || row.target === 'framer'- ? row.target- : 'webhook',- at: row.published_at ?? row.sent_at ?? row.created_at,- error: interrupted ? 'Not sent: interrupted' : row.error,- };-}/*** Each draft's last send, for the Library's rows: one row a draft, howeverdiff --git a/web/src/lib/content/cms-status.ts b/web/src/lib/content/cms-status.tsnew file mode 100644index 000000000..6f57136da--- /dev/null+++ b/web/src/lib/content/cms-status.ts@@ -0,0 +1,38 @@+import type { CmsDelivery, CmsTarget } from '@/lib/content/cms-send-client';++/**+ * A page's last Send to CMS (#1331, 00262) as the Library, the editor and the+ * MCP read it, from its content_draft_deliveries row.+ */++/**+ * A send still queued after this was left by a server that stopped mid-batch+ * (00262 closes it at the workspace's next send): it reads as interrupted,+ * so neither the Library nor the editor waits on it or says it is still+ * going. Read by the reader's clock (the browser's; the server's for the+ * MCP): one 30 minutes fast would read a send under way as interrupted,+ * until its next read.+ */+const INTERRUPTED_AFTER_MS = 30 * 60_000;++/** A send as the Library, the editor and the MCP read it: one left queued, as interrupted. */+export function lastSend(row: {+ status: string;+ created_at: string;+ sent_at: string | null;+ published_at: string | null;+ error: string | null;+ target?: string | null;+}): { status: CmsDelivery['status']; target: CmsTarget; at: string; error: string | null } {+ const interrupted =+ row.status === 'queued' && Date.parse(row.created_at) < Date.now() - INTERRUPTED_AFTER_MS;+ return {+ status: interrupted ? 'failed' : (row.status as CmsDelivery['status']),+ target:+ row.target === 'webflow' || row.target === 'wordpress' || row.target === 'framer'+ ? row.target+ : 'webhook',+ at: row.published_at ?? row.sent_at ?? row.created_at,+ error: interrupted ? 'Not sent: interrupted' : row.error,+ };+}diff --git a/web/src/lib/content/plan-read.ts b/web/src/lib/content/plan-read.tsnew file mode 100644index 000000000..479f242c2--- /dev/null+++ b/web/src/lib/content/plan-read.ts@@ -0,0 +1,208 @@+import { z } from 'zod';+import type { SupabaseClient } from '@supabase/supabase-js';+import { readAssignees } from '@/lib/action-center/assignees';+import { memberLabel } from '@/lib/action-center/display';+import type { DraftMethod } from '@/lib/content/drafts';+import type {+ PlanAnswers,+ PlanDraft,+ PlanMark,+ PlanOpportunity,+ PlanPage,+ PlanPeriod,+ PlanTracking,+} from '@/lib/content/plan';++/**+ * What the Content plan (CE-014) is built from: the brand's pages as AI cites+ * them (content_plan_pages, 00220), its open opportunities for its own pages,+ * the drafts still being written (with who their Action Center task is+ * assigned to), and the rows marked as a priority or hidden+ * (content_plan_marks, 00229). lib/content/plan.ts ranks them.+ *+ * Read through the client given: the signed-in member's session on the+ * Content plan page (getContentPlan), the service role for the MCP tool+ * get_content_plan, after its own check that the brand is the key's.+ */++/** Open opportunities, as New content offers them. */+export const OPEN_OPPORTUNITY_STATUSES = ['new', 'reviewed', 'sent', 'in_progress'];+const OPPORTUNITY_LIMIT = 200;+const DRAFT_LIMIT = 500;++const text = (value: unknown) => (typeof value === 'string' ? value.trim() : '');++const OPPORTUNITY_COLUMNS = 'id, title, decision, opportunity_score, brief, source_data';+export const OPPORTUNITY_KEY = 'opportunity:';+/**+ * The opportunity a row's key names (`opportunity:<id>`), or null for a+ * page's row. The server reads it from the key the mark is written under,+ * so a row's status change can't land on another opportunity.+ */+export function opportunityIdOf(rowKey: string): string | null {+ return rowKey.startsWith(OPPORTUNITY_KEY) ? rowKey.slice(OPPORTUNITY_KEY.length) : null;+}++export interface ContentPlanRead {+ pages: PlanPage[];+ answers: PlanAnswers;+ tracking: PlanTracking;+ opportunities: PlanOpportunity[];+ drafts: PlanDraft[];+ marks: PlanMark[];+}++/**+ * The plan's reads for a brand over `days`; null when the brand isn't the+ * reader's. `me` is who reads it, so their own drafts are marked as theirs.+ */+export async function readContentPlan(+ supabase: SupabaseClient,+ brandId: string,+ days: PlanPeriod,+ me: Promise<string | null>,+): Promise<ContentPlanRead | null> {+ const [userId, pagesRes, opportunitiesRes, draftsRes, marksRes] = await Promise.all([+ me,+ supabase.rpc('content_plan_pages', { p_brand_id: brandId, p_days: days }),+ supabase+ .from('content_opportunities')+ .select(OPPORTUNITY_COLUMNS)+ .eq('brand_id', brandId)+ .eq('type', 'owned')+ .in('status', OPEN_OPPORTUNITY_STATUSES)+ .order('opportunity_score', { ascending: false })+ .limit(OPPORTUNITY_LIMIT),+ supabase+ .from('content_drafts')+ .select('id, author, created_by, method, opportunity_id, source_url, action_id')+ .eq('brand_id', brandId)+ .in('status', ['draft', 'in_review', 'ready'])+ // An archived draft (00233) is set aside: the row starts afresh.+ .is('archived_at', null)+ .order('updated_at', { ascending: false })+ .limit(DRAFT_LIMIT),+ supabase+ .from('content_plan_marks')+ .select('row_key, priority, hidden_at')+ .eq('brand_id', brandId),+ ]);+ if (pagesRes.error) throw new Error(pagesRes.error.message);+ if (opportunitiesRes.error) throw new Error(opportunitiesRes.error.message);+ if (draftsRes.error) throw new Error(draftsRes.error.message);+ if (marksRes.error) throw new Error(marksRes.error.message);+ // Null: not the member's brand.+ if (!pagesRes.data) return null;++ const read = pagesRes.data as unknown as {+ pages?: PlanPage[];+ answers?: Partial<PlanAnswers>;+ prevFrom?: string;+ trackedSince?: string | null;+ };+ const answers = {+ cur: Number(read.answers?.cur ?? 0),+ prev: Number(read.answers?.prev ?? 0),+ };+ const tracking = {+ prevFrom: read.prevFrom ?? null,+ trackedSince: read.trackedSince ?? null,+ };+ const pages = (read.pages ?? []).map((p) => ({+ page: p.page,+ title: p.title ?? null,+ citations: { cur: Number(p.citations?.cur ?? 0), prev: Number(p.citations?.prev ?? 0) },+ platformsDown: Array.isArray(p.platformsDown) ? p.platformsDown : [],+ aiVisits: Number(p.aiVisits ?? 0),+ // Null with conversions off (00291), or from a database before it.+ conversions:+ p.conversions === null || p.conversions === undefined ? null : Number(p.conversions),+ }));++ const marks = (marksRes.data ?? []).map(+ (m): PlanMark => ({ rowKey: m.row_key, priority: m.priority, hidden: m.hidden_at !== null }),+ );+ // A hidden opportunity's row was dismissed with it: read it too, to show+ // again, while it is still dismissed (not completed or reopened since).+ const openIds = new Set((opportunitiesRes.data ?? []).map((o) => o.id));+ const hiddenIds = marks+ .filter((m) => m.hidden)+ .map((m) => opportunityIdOf(m.rowKey))+ .filter((id): id is string => id !== null && z.guid().safeParse(id).success)+ .filter((id) => !openIds.has(id));+ const hiddenRes = hiddenIds.length+ ? await supabase+ .from('content_opportunities')+ .select(OPPORTUNITY_COLUMNS)+ .eq('brand_id', brandId)+ .eq('status', 'dismissed')+ .in('id', hiddenIds)+ : { data: [], error: null };+ if (hiddenRes.error) throw new Error(hiddenRes.error.message);++ const opportunities = [...(opportunitiesRes.data ?? []), ...(hiddenRes.data ?? [])].map(+ (o): PlanOpportunity => {+ const sd = (o.source_data ?? {}) as Record<string, unknown>;+ const brief = (o.brief ?? null) as { suggestedTitle?: unknown } | null;+ const target = Array.isArray(sd.targetPages)+ ? (sd.targetPages as { url?: unknown; title?: unknown }[]).find((p) => text(p?.url))+ : undefined;+ return {+ id: o.id,+ title: o.title,+ pageTitle: text(brief?.suggestedTitle) || null,+ decision: o.decision,+ score: Number(o.opportunity_score ?? 0),+ targetPage: target ? text(target.url) : null,+ targetTitle: text(target?.title) || null,+ competitorsCited: Array.isArray(sd.competitorsCited)+ ? sd.competitorsCited.map(text).filter(Boolean).slice(0, 2)+ : [],+ visibility: typeof sd.visibilityScore === 'number' ? sd.visibilityScore : null,+ prompts: Array.isArray(sd.prompts) ? sd.prompts.length : 0,+ assetType: Array.isArray(sd.assets)+ ? text((sd.assets as { type?: unknown }[])[0]?.type) || null+ : null,+ };+ },+ );++ // Who each draft's Action Center task is assigned to.+ const actionIds = [+ ...new Set((draftsRes.data ?? []).map((d) => d.action_id).filter(Boolean)),+ ] as string[];+ const actionsRes = actionIds.length+ ? await supabase.from('actions').select('id, assignee_id').in('id', actionIds)+ : { data: [], error: null };+ if (actionsRes.error) throw new Error(actionsRes.error.message);+ const assigneeOf = new Map(+ (actionsRes.data ?? []).map((a) => [a.id as string, a.assignee_id as string | null]),+ );+ const people = await readAssignees(+ supabase,+ brandId,+ [...assigneeOf.values()].filter(Boolean) as string[],+ );++ const drafts = (draftsRes.data ?? []).map((d): PlanDraft => {+ const assigneeId = d.action_id ? (assigneeOf.get(d.action_id) ?? null) : null;+ const person = assigneeId ? people.get(assigneeId) : undefined;+ return {+ id: d.id,+ author: d.author === 'agent' ? 'agent' : 'user',+ isMine: userId !== null && d.created_by === userId,+ method: d.method as DraftMethod,+ opportunityId: d.opportunity_id,+ sourceUrl: d.source_url,+ actionId: d.action_id ?? null,+ assignee: person+ ? {+ id: person.id,+ name: memberLabel({ fullName: person.fullName, email: person.email ?? '' }),+ }+ : null,+ };+ });++ return { pages, answers, tracking, opportunities, drafts, marks };+}diff --git a/web/src/lib/mcp/content-delivery.test.ts b/web/src/lib/mcp/content-delivery.test.tsnew file mode 100644index 000000000..91a60af92--- /dev/null+++ b/web/src/lib/mcp/content-delivery.test.ts@@ -0,0 +1,133 @@+// @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';++/**+ * mark_content_draft_published (B5): a page the user's own AI tool put on a+ * CMS, marked live as the editor's Mark published does, through the API's+ * publishDraft for the key's user and organization.+ */++let subscriptionStatus: string;+vi.mock('@/lib/supabase/admin', () => ({+ supabaseAdmin: {+ from: () => {+ const chain = {+ select: () => chain,+ eq: () => chain,+ maybeSingle: async () => ({+ data: { subscription_status: subscriptionStatus },+ error: null,+ }),+ };+ return chain;+ },+ },+}));++const { markContentDraftPublishedFor } = await import('./content-delivery');+const { createMcpServer } = await import('./server');++const auth: McpAuthContext = {+ userId: 'user-1',+ email: null,+ organizationId: 'org-1',+ apiKeyId: 'key-1',+};+const LIVE = 'https://acme.example/blog/cold-brew';+const fetchMock = vi.fn();++beforeEach(() => {+ subscriptionStatus = 'active';+ fetchMock.mockReset();+ vi.stubGlobal('fetch', fetchMock);+ vi.stubEnv('CRON_SECRET', 'secret');+});++afterEach(() => {+ vi.unstubAllGlobals();+ vi.unstubAllEnvs();+});++describe('markContentDraftPublishedFor', () => {+ it("marks the page live through the API, as the key's user of the key's organization", async () => {+ fetchMock.mockResolvedValue(+ Response.json({+ success: true,+ publishedUrl: LIVE,+ publishedAt: '2026-10-28T18:00:00Z',+ taskCompleted: true,+ onBrandDomain: true,+ }),+ );+ expect(await markContentDraftPublishedFor(auth, 'draft-1', LIVE)).toEqual({+ published_url: LIVE,+ published_at: '2026-10-28T18:00:00Z',+ task_completed: true,+ on_brand_domain: true,+ });+ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toMatch(/\/api\/internal\/content-drafts\/draft-1\/publish$/);+ expect(init).toMatchObject({ method: 'POST', headers: { Authorization: 'Bearer secret' } });+ expect(JSON.parse(init.body)).toEqual({ url: LIVE, userId: 'user-1', orgId: 'org-1' });+ });++ it('says what is wrong with an address, and that a draft is not there', async () => {+ fetchMock.mockResolvedValueOnce(Response.json({ code: 'invalid_url' }, { status: 400 }));+ expect(await markContentDraftPublishedFor(auth, 'draft-1', 'ftp://x')).toMatchObject({+ error: 'invalid_url',+ });+ fetchMock.mockResolvedValueOnce(Response.json({ code: 'not_found' }, { status: 404 }));+ expect(await markContentDraftPublishedFor(auth, 'draft-2', LIVE)).toMatchObject({+ error: 'not_found',+ });+ // A request the API can't read isn't the address's fault.+ fetchMock.mockResolvedValueOnce(+ Response.json({ code: 'invalid', message: 'Invalid request' }, { status: 400 }),+ );+ await expect(markContentDraftPublishedFor(auth, 'draft-3', LIVE)).rejects.toThrow(+ 'Invalid request',+ );+ });++ it('refuses a read-only workspace before asking the API', async () => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ subscriptionStatus = 'canceled';+ await expect(markContentDraftPublishedFor(auth, 'draft-1', LIVE)).rejects.toMatchObject({+ code: 'subscription_inactive',+ });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("passes on the API's failure, and asks nothing without an organization", async () => {+ fetchMock.mockResolvedValueOnce(Response.json({ message: 'boom' }, { status: 500 }));+ await expect(markContentDraftPublishedFor(auth, 'draft-1', LIVE)).rejects.toThrow('boom');+ fetchMock.mockReset();+ expect(+ await markContentDraftPublishedFor({ ...auth, organizationId: null }, 'draft-1', LIVE),+ ).toMatchObject({ error: 'not_found' });+ expect(fetchMock).not.toHaveBeenCalled();+ });+});++describe('the B5 tools', () => {+ it('list with a title, the plan as a read and the mark as a write', 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 { tools } = await client.listTools();+ const tool = (name: string) => tools.find((t) => t.name === name);+ expect(tool('get_content_plan')).toMatchObject({+ title: 'Content plan',+ annotations: { readOnlyHint: true, openWorldHint: false },+ });+ expect(tool('mark_content_draft_published')).toMatchObject({+ title: 'Mark a draft published',+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },+ });+ });+});diff --git a/web/src/lib/mcp/content-delivery.ts b/web/src/lib/mcp/content-delivery.tsnew file mode 100644index 000000000..05623000d--- /dev/null+++ b/web/src/lib/mcp/content-delivery.ts@@ -0,0 +1,209 @@+import { supabaseAdmin } from '@/lib/supabase/admin';+import type { McpAuthContext } from '@/lib/mcp-auth';+import { API_BASE_URL } from '@/config/api';+import { lastSend } from '@/lib/content/cms-status';+import { draftShopping } from '@/lib/content/shopping-check';+import { shoppingPathSchema } from '@/lib/content/shopping-path';+import { assertSubscriptionActive } from './subscription-gate';++/**+ * Where a draft went and whether its shopping links still sell, for the MCP's+ * draft tools (B5), as the Content Library shows them: its last Send to CMS+ * (00262, 00284) and its shopping path's check after each catalog sync+ * (00351, 00352). Ansvisor's MCP never sends a page itself: the user's AI+ * tool does, with its own CMS connector, and marks it published here.+ */++/** A draft's last Send to CMS. */+export interface McpLastSend {+ /** queued, sent, failed (a send left queued reads as failed: interrupted) or published. */+ status: string;+ /** webhook, webflow, wordpress or framer: the brand's webhook, Webflow collection, WordPress site or Framer collection. */+ target: string;+ /** When it was published, sent or queued. */+ at: string;+ /** What the webhook answered, when it did. */+ http_status: number | null;+ error: string | null;+ /** Where the CMS says it went live. */+ published_url: string | null;+}++/** Whether a draft's shopping links still sell, as the Library's Shopping path column reads it. */+export type McpShoppingLinks =+ /** No shopping path: not a shop's page, or not one of the types that take one. */+ | { state: 'none' }+ /** A path, not checked since it was built. */+ | { state: 'unchecked' }+ | {+ /** attention: it links products that no longer sell. */+ state: 'ok' | 'attention';+ /** Read from the live page, or the draft when it isn't live. */+ read_from: 'page' | 'draft';+ checked_at: string;+ categories: number;+ categories_linked: number;+ products: number;+ products_linked: number;+ /** The linked products that no longer sell: sold out, refused by Merchant Center, or gone. */+ bad: { id: string; title: string; state: string }[];+ };++/** The columns a draft read adds for mcpShoppingLinks, as the Library's read embeds them. */+export const SHOPPING_COLUMNS =+ 'shopping_built:shopping_path->>builtAt, content_shopping_checks(read_from, checked_at, categories, categories_linked, products, products_linked, bad)';++export function mcpShoppingLinks(builtAt: string | null, check: unknown): McpShoppingLinks {+ const read = draftShopping(builtAt, check);+ if (read.state === 'none' || read.state === 'unchecked') return read;+ return {+ state: read.state,+ read_from: read.readFrom,+ checked_at: read.checkedAt,+ categories: read.categories,+ categories_linked: read.categoriesLinked,+ products: read.products,+ products_linked: read.productsLinked,+ bad: read.bad,+ };+}++/** Ids a read takes: content_draft_last_deliveries (00262) reads up to 500. */+const IDS_PER_READ = 500;++/** Each draft's last send, by draft id; a draft never sent has none. */+export async function lastSendsOf(draftIds: string[]): Promise<Map<string, McpLastSend>> {+ const chunks: string[][] = [];+ for (let i = 0; i < draftIds.length; i += IDS_PER_READ) {+ chunks.push(draftIds.slice(i, i + IDS_PER_READ));+ }+ const reads = await Promise.all(+ chunks.map((ids) => supabaseAdmin.rpc('content_draft_last_deliveries', { p_draft_ids: ids })),+ );+ const sends = new Map<string, McpLastSend>();+ for (const { data, error } of reads) {+ if (error) throw new Error(error.message);+ for (const row of data ?? []) {+ if (!row.draft_id) continue;+ const send = lastSend(row);+ sends.set(row.draft_id, {+ status: send.status,+ target: send.target,+ at: send.at,+ http_status: row.http_status,+ error: send.error,+ published_url: row.published_url,+ });+ }+ }+ return sends;+}++/** A draft's shopping path, as its Brief tab shows it: what the page should link. */+export interface McpShoppingPath {+ built_at: string;+ page_type: string | null;+ /** The category pages it should link. */+ categories: { name: string; url: string | null }[];+ /** The catalog products it should link, the best first. */+ products: {+ id: string;+ title: string;+ url: string | null;+ price: number | null;+ sale_price: number | null;+ currency: string | null;+ availability: string;+ }[];+ /** Products the path left out, and why (sold_out, refused, no_link, gone…). */+ left_out: { id: string; title: string | null; reason: string }[];+}++/** The stored shopping path in the MCP's shape; null for none, or one that can't be read. */+export function mcpShoppingPath(stored: unknown): McpShoppingPath | null {+ const parsed = shoppingPathSchema.safeParse(stored);+ if (!parsed.success) return null;+ const path = parsed.data;+ return {+ built_at: path.builtAt,+ page_type: path.pageType,+ categories: path.categories.map((c) => ({ name: c.name, url: c.url })),+ products: path.products.map((p) => ({+ id: p.id,+ title: p.title,+ url: p.url,+ price: p.price,+ sale_price: p.salePrice,+ currency: p.currency,+ availability: p.availability,+ })),+ left_out: path.leftOut.map((p) => ({ id: p.id, title: p.title, reason: p.reason })),+ };+}++/** Where a page was marked live, as the editor's Mark published answers. */+export interface McpPublished {+ published_url: string;+ published_at: string;+ /** The linked action's Publish task done: every page it names is live. */+ task_completed: boolean;+ /** Off the brand's domains the address is kept, but the Live page tab can't measure it. */+ on_brand_domain: boolean;+}++export type McpPublishError = { error: 'invalid_url' | 'not_found'; message: string };++/**+ * A page marked Published at the address it went live at, as the editor's+ * Mark published does (CE-013), for a page the user's own AI tool put on a+ * CMS: Ansvisor then measures that address (the Live page tab, its+ * citations and AI visits) and a linked action's Publish task completes+ * once all its pages are live. The API's publishDraft runs it for the key's+ * user through the CRON_SECRET internal endpoint; the draft must be the+ * key's organization's.+ *+ * TODO(demo-brand-mcp): add mark_content_draft_published to WRITE_TOOL_BRANDS+ * (lib/mcp/demo-gate.ts), its brand through content_drafts.brand_id, when+ * feature/demo-brand-mcp merges.+ */+export async function markContentDraftPublishedFor(+ auth: McpAuthContext,+ draftId: string,+ url: string,+): Promise<McpPublished | McpPublishError> {+ const notFound: McpPublishError = { error: 'not_found', message: 'Draft not found' };+ if (!auth.organizationId) return notFound;+ // Nothing marked for a read-only workspace, whoever asks: the API's+ // internal endpoint is outside its own read-only check.+ await assertSubscriptionActive(auth.organizationId);+ const cronSecret = process.env.CRON_SECRET;+ if (!cronSecret) throw new Error('CRON_SECRET must be configured for MCP publishing');++ const res = await fetch(+ `${API_BASE_URL}/api/internal/content-drafts/${encodeURIComponent(draftId)}/publish`,+ {+ method: 'POST',+ headers: { Authorization: `Bearer ${cronSecret}`, 'Content-Type': 'application/json' },+ body: JSON.stringify({ url, userId: auth.userId, orgId: auth.organizationId }),+ },+ );+ const body = (await res.json().catch(() => null)) as Record<string, unknown> | null;+ if (!res.ok) {+ if (body?.code === 'invalid_url') {+ return {+ error: 'invalid_url',+ message: 'Give the http(s) address the page is live at, with no sign-in details.',+ };+ }+ if (res.status === 404) return notFound;+ throw new Error(+ (body?.message as string | undefined) ?? `Internal publish endpoint returned ${res.status}`,+ );+ }+ return {+ published_url: String(body?.publishedUrl ?? url),+ published_at: String(body?.publishedAt ?? new Date().toISOString()),+ task_completed: body?.taskCompleted === true,+ on_brand_domain: body?.onBrandDomain !== false,+ };+}diff --git a/web/src/lib/mcp/content-plan.test.ts b/web/src/lib/mcp/content-plan.test.tsnew file mode 100644index 000000000..fac3a6d65--- /dev/null+++ b/web/src/lib/mcp/content-plan.test.ts@@ -0,0 +1,161 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { McpAuthContext } from '@/lib/mcp-auth';+import type { ContentPlanRead } from '@/lib/content/plan-read';++/**+ * get_content_plan (B5): the Content plan as the page ranks it, from the+ * page's own reads (readContentPlan) through the service role, once the+ * brand is the key's; snake_case, a card's rows when asked.+ */++let brand: Record<string, unknown> | null;+/** Each filter the brand read made: [table, column, value]. */+const filters: [string, string, unknown][] = [];+vi.mock('@/lib/supabase/admin', () => ({+ supabaseAdmin: {+ from: (table: string) => {+ const chain = {+ select: () => chain,+ eq: (column: string, value: unknown) => {+ filters.push([table, column, value]);+ return chain;+ },+ maybeSingle: async () => ({ data: brand, error: null }),+ };+ return chain;+ },+ },+}));++const readContentPlan = vi.hoisted(() => vi.fn());+vi.mock('@/lib/content/plan-read', () => ({ readContentPlan }));++const { getContentPlanFor } = await import('./content-plan');++const auth: McpAuthContext = {+ userId: 'user-1',+ email: null,+ organizationId: 'org-1',+ apiKeyId: 'key-1',+};++const READ: ContentPlanRead = {+ pages: [+ {+ page: 'https://acme.example/pricing',+ title: 'Pricing',+ citations: { cur: 4, prev: 12 },+ platformsDown: ['chatgpt-web'],+ aiVisits: 40,+ conversions: null,+ },+ ],+ answers: { cur: 100, prev: 100 },+ tracking: { prevFrom: '2026-08-29', trackedSince: '2026-06-01' },+ opportunities: [+ {+ id: '11111111-2222-3333-4444-555555555555',+ title: 'Cold brew at home',+ pageTitle: 'How to make cold brew at home',+ decision: 'create',+ score: 80,+ targetPage: null,+ targetTitle: null,+ competitorsCited: ['Rival'],+ visibility: 12,+ prompts: 6,+ assetType: null,+ },+ ],+ drafts: [+ {+ id: 'draft-1',+ author: 'agent',+ isMine: false,+ method: 'create',+ opportunityId: '11111111-2222-3333-4444-555555555555',+ sourceUrl: null,+ actionId: null,+ assignee: { id: 'person-1', name: 'Ada' },+ },+ ],+ marks: [],+};++beforeEach(() => {+ filters.length = 0;+ brand = { id: 'brand-1', site_type: 'b2b', industry: null, shopping_mode_enabled: false };+ readContentPlan.mockReset().mockResolvedValue(READ);+});++describe('getContentPlanFor', () => {+ it("ranks the brand's plan as the page does, in the MCP's names", async () => {+ const plan = await getContentPlanFor(auth, { brandId: 'brand-1', days: 30 });+ expect(readContentPlan).toHaveBeenCalledWith(+ expect.anything(),+ 'brand-1',+ 30,+ expect.any(Promise),+ );+ expect(plan).toMatchObject({+ days: 30,+ hidden: 0,+ tracked_since: '2026-06-01',+ previous_from: '2026-08-29',+ counts: { create: 1, optimize: 1, protect: expect.any(Number), priority: 0 },+ });+ const create = plan!.rows.find((r) => r.action === 'create')!;+ expect(create).toMatchObject({+ key: 'opportunity:11111111-2222-3333-4444-555555555555',+ title: 'How to make cold brew at home',+ page: null,+ opportunity_id: '11111111-2222-3333-4444-555555555555',+ why: { kind: 'competitors', names: ['Rival'], visibility: 12 },+ draft: {+ id: 'draft-1',+ author: 'agent',+ method: 'create',+ assignee: { id: 'person-1', name: 'Ada' },+ editor_path: expect.stringContaining('draft-1'),+ },+ priority: false,+ });+ expect(create.score_parts.map((p) => p.kind)).toEqual([+ 'severity',+ 'opportunity',+ 'pageValue',+ 'citations',+ ]);+ const optimize = plan!.rows.find((r) => r.action === 'optimize')!;+ expect(optimize.why).toMatchObject({ kind: 'citationsDown', platforms: ['chatgpt-web'] });+ });++ it("keeps to a card's rows when asked", async () => {+ const plan = await getContentPlanFor(auth, { brandId: 'brand-1', days: 7, card: 'create' });+ expect(plan!.rows.map((r) => r.action)).toEqual(['create']);+ });++ it("answers null for another organization's brand, without reading its plan", async () => {+ brand = null;+ expect(await getContentPlanFor(auth, { brandId: 'brand-2', days: 30 })).toBeNull();+ // The brand is read only as the key's organization's.+ expect(filters).toEqual([+ ['brands', 'id', 'brand-2'],+ ['brands', 'organization_id', 'org-1'],+ ]);+ expect(readContentPlan).not.toHaveBeenCalled();+ });++ it('reads nothing for a key without an organization', async () => {+ expect(+ await getContentPlanFor({ ...auth, organizationId: null }, { brandId: 'brand-1', days: 30 }),+ ).toBeNull();+ expect(filters).toEqual([]);+ expect(readContentPlan).not.toHaveBeenCalled();+ });++ it('marks the drafts of the key’s user as theirs', async () => {+ await getContentPlanFor(auth, { brandId: 'brand-1', days: 30 });+ await expect(readContentPlan.mock.calls[0][3]).resolves.toBe('user-1');+ });+});diff --git a/web/src/lib/mcp/content-plan.ts b/web/src/lib/mcp/content-plan.tsnew file mode 100644index 000000000..d8673f221--- /dev/null+++ b/web/src/lib/mcp/content-plan.ts@@ -0,0 +1,138 @@+import { supabaseAdmin } from '@/lib/supabase/admin';+import type { McpAuthContext } from '@/lib/mcp-auth';+import { contentEditorPath } from '@/lib/content/drafts';+import { siteTypeOf } from '@/lib/content/page-types';+import {+ buildPlan,+ rowsFor,+ type PlanCard,+ type PlanPeriod,+ type PlanRow,+ type PlanScorePart,+ type PlanWhy,+} from '@/lib/content/plan';+import { readContentPlan } from '@/lib/content/plan-read';++/**+ * The Content plan (CE-014) for the MCP tool get_content_plan and its REST+ * mirror: the brand's pages and opportunities ranked by the Priority Score,+ * as the Content plan page ranks them (buildPlan), from the same reads+ * (readContentPlan) through the service role, once the brand is the key's.+ */++export interface McpPlanRow {+ /** The row's key: `opportunity:<id>` or the page's address. */+ key: string;+ /** create (a new page), optimize (a page losing citations or an opportunity on it) or protect (a top page). */+ action: PlanRow['action'];+ title: string;+ /** The page it works on; null for a new page. */+ page: string | null;+ page_type: string | null;+ /** Why it's on the plan. */+ why: Record<string, unknown>;+ /** The Priority Score, 0–100, and what it's made of. */+ score: number;+ score_parts: Record<string, unknown>[];+ opportunity_id: string | null;+ /** The draft already being written for it, if any. */+ draft: {+ id: string;+ author: 'user' | 'agent';+ method: string;+ assignee: { id: string; name: string } | null;+ editor_path: string;+ } | null;+ /** Marked as a priority: at the top, as on the page. */+ priority: boolean;+}++export interface McpContentPlan {+ days: PlanPeriod;+ /** How many rows each card holds (create, optimize, protect, priority). */+ counts: Record<PlanCard, number>;+ /** Rows hidden from the plan by a person. */+ hidden: number;+ /** When the brand's tracking began, and where the earlier period starts. */+ tracked_since: string | null;+ previous_from: string | null;+ rows: McpPlanRow[];+}++/** camelCase keys as the MCP's snake_case, one level deep. */+function snake(value: object): Record<string, unknown> {+ return Object.fromEntries(+ Object.entries(value).map(([key, v]) => [+ key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`),+ v,+ ]),+ );+}++function mcpPlanRow(row: PlanRow): McpPlanRow {+ return {+ key: row.key,+ action: row.action,+ title: row.title,+ page: row.page,+ page_type: row.pageType,+ why: snake(row.why as PlanWhy),+ score: row.score,+ score_parts: row.scoreParts.map((part: PlanScorePart) => snake(part)),+ opportunity_id: row.opportunityId,+ draft: row.draft+ ? {+ id: row.draft.id,+ author: row.draft.author,+ method: row.draft.method,+ assignee: row.draft.assignee,+ editor_path: contentEditorPath(row.draft.id),+ }+ : null,+ priority: row.priority,+ };+}++/**+ * The brand's Content plan over `days` (7, 30 or 90), its rows ranked as the+ * page shows them: the first 50 of a card, or of every row without one.+ * Null for a brand outside the key's organization.+ */+export async function getContentPlanFor(+ auth: McpAuthContext,+ params: { brandId: string; days: PlanPeriod; card?: PlanCard },+): Promise<McpContentPlan | null> {+ if (!auth.organizationId) return null;+ const { data: brand, error } = await supabaseAdmin+ .from('brands')+ .select('id, site_type, industry, shopping_mode_enabled')+ .eq('id', params.brandId)+ .eq('organization_id', auth.organizationId)+ .maybeSingle();+ if (error) throw new Error(error.message);+ if (!brand) return null;++ const read = await readContentPlan(+ supabaseAdmin,+ params.brandId,+ params.days,+ Promise.resolve(auth.userId),+ );+ if (!read) return null;+ const plan = buildPlan({+ ...read,+ siteType: siteTypeOf({+ siteType: brand.site_type as string | null,+ industry: brand.industry as string | null,+ shoppingModeEnabled: brand.shopping_mode_enabled === true,+ }),+ });+ return {+ days: params.days,+ counts: plan.counts,+ hidden: plan.hidden.length,+ tracked_since: read.tracking.trackedSince,+ previous_from: read.tracking.prevFrom,+ rows: rowsFor(plan.rows, params.card ?? null).map(mcpPlanRow),+ };+}diff --git a/web/src/lib/mcp/content.test.ts b/web/src/lib/mcp/content.test.tsindex 5f0670cda..491b415f1 100644--- a/web/src/lib/mcp/content.test.ts+++ b/web/src/lib/mcp/content.test.ts@@ -54,6 +54,7 @@ vi.mock('@/lib/mcp/data', () => ({ brandInOrg }));const {createContentDraftFor,getContentDraftFor,+ listContentDraftsFor,getContentImpactFor,setContentDraftReadyFor,suggestContentChangesFor,@@ -410,3 +411,169 @@ describe('getContentImpactFor', () => {expect(db.rpcCalls[0][1]).toMatchObject({ p_page: 'https://acme.example/moved' });});});++describe('where a draft went, and its shopping links (B5)', () => {+ const CHECK = {+ read_from: 'page',+ checked_at: '2026-10-27T03:00:00Z',+ categories: 2,+ categories_linked: 1,+ products: 4,+ products_linked: 3,+ bad: [{ id: 'p9', title: 'Trail boots', state: 'sold_out' }],+ };++ it('lists each draft’s last send and whether its shopping links still sell', async () => {+ db.rows.content_drafts = [+ {+ ...draftRow(),+ shopping_built: '2026-10-20T10:00:00Z',+ content_shopping_checks: CHECK,+ },+ { ...draftRow({ id: 'd2' }), shopping_built: null, content_shopping_checks: null },+ ];+ db.rows.content_draft_suggestions = [];+ db.rpc.content_draft_last_deliveries = [+ {+ draft_id: 'd1',+ status: 'published',+ target: 'webflow',+ created_at: '2026-10-25T09:00:00Z',+ sent_at: '2026-10-25T09:00:05Z',+ published_at: '2026-10-25T09:30:00Z',+ error: null,+ http_status: 200,+ published_url: 'https://acme.example/blog/forecasting',+ },+ ];++ const drafts = (await listContentDraftsFor(auth, 'b1'))!;++ expect(db.rpcCalls).toContainEqual([+ 'content_draft_last_deliveries',+ { p_draft_ids: ['d1', 'd2'] },+ ]);+ expect(drafts[0]).toMatchObject({+ last_send: {+ status: 'published',+ target: 'webflow',+ at: '2026-10-25T09:30:00Z',+ http_status: 200,+ error: null,+ published_url: 'https://acme.example/blog/forecasting',+ },+ shopping_links: {+ state: 'attention',+ read_from: 'page',+ products: 4,+ products_linked: 3,+ bad: [{ id: 'p9', title: 'Trail boots', state: 'sold_out' }],+ },+ });+ // The embeds are the draft's own fields, not the list's.+ expect(drafts[0]).not.toHaveProperty('content_shopping_checks');+ expect(drafts[1]).toMatchObject({ last_send: null, shopping_links: { state: 'none' } });+ });++ it('reads a send left queued for long as failed, interrupted', async () => {+ db.rows.content_drafts = [+ { ...draftRow(), shopping_built: null, content_shopping_checks: null },+ ];+ db.rows.content_draft_suggestions = [];+ db.rpc.content_draft_last_deliveries = [+ {+ draft_id: 'd1',+ status: 'queued',+ target: 'webhook',+ created_at: '2026-10-01T09:00:00Z',+ sent_at: null,+ published_at: null,+ error: null,+ http_status: null,+ published_url: null,+ },+ ];+ const [draft] = (await listContentDraftsFor(auth, 'b1'))!;+ expect(draft.last_send).toMatchObject({ status: 'failed', error: 'Not sent: interrupted' });+ });++ it.each(['wordpress', 'framer'])('names a send to %s as such', async (target) => {+ db.rows.content_drafts = [+ { ...draftRow(), shopping_built: null, content_shopping_checks: null },+ ];+ db.rows.content_draft_suggestions = [];+ db.rpc.content_draft_last_deliveries = [+ {+ draft_id: 'd1',+ status: 'sent',+ target,+ created_at: '2026-10-25T09:00:00Z',+ sent_at: '2026-10-25T09:00:04Z',+ published_at: null,+ error: null,+ http_status: 201,+ published_url: null,+ },+ ];+ const [draft] = (await listContentDraftsFor(auth, 'b1'))!;+ expect(draft.last_send).toMatchObject({+ status: 'sent',+ target,+ at: '2026-10-25T09:00:04Z',+ });+ });++ it('gives one draft its shopping path, as its Brief tab shows it', async () => {+ db.rows.content_drafts = draftRow({+ shopping_built: '2026-10-20T10:00:00Z',+ content_shopping_checks: null,+ shopping_path: {+ version: 1,+ builtAt: '2026-10-20T10:00:00Z',+ savedAt: null,+ pageType: 'buying_guide',+ categories: [{ name: 'Boots', url: 'https://acme.example/boots', title: 'Boots' }],+ products: [+ {+ id: 'p1',+ title: 'Trail boots',+ url: 'https://acme.example/p/trail',+ price: 120,+ salePrice: null,+ currency: 'USD',+ availability: 'In Stock',+ image: null,+ issues: [],+ score: 0.9,+ },+ ],+ leftOut: [{ id: 'p9', title: 'Old boots', reason: 'sold_out' }],+ locked: [],+ removed: [],+ added: [],+ },+ });++ const draft = (await getContentDraftFor(auth, 'd1'))!;++ expect(draft.last_send).toBeNull();+ expect(draft.shopping_links).toEqual({ state: 'unchecked' });+ expect(draft.shopping_path).toEqual({+ built_at: '2026-10-20T10:00:00Z',+ page_type: 'buying_guide',+ categories: [{ name: 'Boots', url: 'https://acme.example/boots' }],+ products: [+ {+ id: 'p1',+ title: 'Trail boots',+ url: 'https://acme.example/p/trail',+ price: 120,+ sale_price: null,+ currency: 'USD',+ availability: 'in_stock',+ },+ ],+ left_out: [{ id: 'p9', title: 'Old boots', reason: 'sold_out' }],+ });+ });+});diff --git a/web/src/lib/mcp/content.ts b/web/src/lib/mcp/content.tsindex 21005e478..335d06307 100644--- a/web/src/lib/mcp/content.ts+++ b/web/src/lib/mcp/content.ts@@ -1,4 +1,13 @@import { supabaseAdmin } from '@/lib/supabase/admin';+import {+ SHOPPING_COLUMNS,+ lastSendsOf,+ mcpShoppingLinks,+ mcpShoppingPath,+ type McpLastSend,+ type McpShoppingLinks,+ type McpShoppingPath,+} from './content-delivery';import type { McpAuthContext } from '@/lib/mcp-auth';import { brandInOrg } from '@/lib/mcp/data';import {@@ -140,6 +149,24 @@ export interface McpDraftSummary {open_suggestions: number;updated_at: string;editor_path: string;+ /** Its last Send to CMS, as the Library shows it; null when never sent. */+ last_send: McpLastSend | null;+ /** Whether its shopping links still sell. */+ shopping_links: McpShoppingLinks;+}++/** How many agent suggestions wait for review on each draft, by draft id. */+async function openSuggestionCounts(draftIds: string[]): Promise<Map<string, number>> {+ const open = new Map<string, number>();+ if (!draftIds.length) return open;+ const { data, error } = await supabaseAdmin+ .from('content_draft_suggestions')+ .select('draft_id')+ .in('draft_id', draftIds)+ .eq('status', 'open');+ if (error) throw new Error(error.message);+ for (const s of data ?? []) open.set(s.draft_id, (open.get(s.draft_id) ?? 0) + 1);+ return open;}/** A brand's drafts, the latest changed first; null for a brand outside the organization. */@@ -151,7 +178,9 @@ export async function listContentDraftsFor(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')+ .select(+ `id, title, status, method, page_type, author, source_url, updated_at, ${SHOPPING_COLUMNS}`,+ ).eq('brand_id', brandId)// Archived drafts (00233) are set aside in the Library, and here..is('archived_at', null)@@ -162,23 +191,14 @@ export async function listContentDraftsFor(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) => ({+ const ids = rows.map((r) => r.id);+ const [open, sends] = await Promise.all([openSuggestionCounts(ids), lastSendsOf(ids)]);+ return rows.map(({ shopping_built, content_shopping_checks, ...row }) => ({...row,open_suggestions: open.get(row.id) ?? 0,editor_path: contentEditorPath(row.id),+ last_send: sends.get(row.id) ?? null,+ shopping_links: mcpShoppingLinks(shopping_built, content_shopping_checks),}));}@@ -207,6 +227,12 @@ export interface McpDraft {* links and inline citations. A link to anything else is unwrapped.*/link_targets: { own_pages: LinkTargets['own']; sources: LinkTargets['sources'] };+ /** Its last Send to CMS; null when never sent. */+ last_send: McpLastSend | null;+ /** What the page should link on an online shop (its Brief tab); null for none. */+ shopping_path: McpShoppingPath | null;+ /** Whether its shopping links still sell. */+ shopping_links: McpShoppingLinks;}/** One draft, its passages numbered and the locked ones marked; null outside the organization. */@@ -217,14 +243,21 @@ export async function getContentDraftFor(const draft = await draftFor(auth, draftId);if (!draft) return null;const passages = draftPassages(draft.body_html);- const [locked, openSuggestions, targets] = await Promise.all([+ const [locked, openSuggestions, targets, sends, shopping] = await Promise.all([lockedKeys(draft,passages.map((p) => p.text),),openSuggestionsOf(draft.id),linkTargetsOf(draft),+ lastSendsOf([draft.id]),+ supabaseAdmin+ .from('content_drafts')+ .select(`shopping_path, ${SHOPPING_COLUMNS}`)+ .eq('id', draft.id)+ .maybeSingle(),]);+ if (shopping.error) throw new Error(shopping.error.message);return {id: draft.id,@@ -248,6 +281,12 @@ export async function getContentDraftFor(})),open_suggestions: openSuggestions,link_targets: { own_pages: targets.own, sources: targets.sources },+ last_send: sends.get(draft.id) ?? null,+ shopping_path: mcpShoppingPath(shopping.data?.shopping_path ?? null),+ shopping_links: mcpShoppingLinks(+ shopping.data?.shopping_built ?? null,+ shopping.data?.content_shopping_checks ?? null,+ ),};}diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsindex ff21f508e..e54254e67 100644--- a/web/src/lib/mcp/server.ts+++ b/web/src/lib/mcp/server.ts@@ -78,6 +78,9 @@ import { MENTION_SENTIMENTS, MENTION_SORTS } from '@/lib/mentions-list';import { gateWriteTools } from './subscription-gate';import { getAiUsageFor, getMeFor } from './account';import { getActionScorecardFor } from './learning';+import { getContentPlanFor } from './content-plan';+import { markContentDraftPublishedFor } from './content-delivery';+import { PLAN_CARDS, PLAN_PERIODS } from '@/lib/content/plan';/*** Build a fresh MCP server bound to a single authenticated request.@@ -1577,7 +1580,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {'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.",+ "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. Also `last_send` (its last Send to CMS: status queued, sent, failed or published, target webhook, webflow, wordpress or framer, when, the webhook's HTTP status, the error, and where the CMS says it went live; null when never sent) and `shopping_links` (on a shop's page with a shopping path: whether its links still sell — state ok or attention, the category pages and products linked, and the linked products that no longer sell: sold out, refused by Merchant Center or gone; none or unchecked otherwise).",inputSchema: listDraftsShape,},async (args) => {@@ -1590,7 +1593,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {'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 where and since when the page is live (published_url, published_at; null until then), the action it belongs to, the agent suggestions still waiting for review, and link_targets: the only URLs suggest_content_changes may link to (own_pages for internal links, sources for outbound links and inline citations).',+ '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 where and since when the page is live (published_url, published_at; null until then), the action it belongs to, the agent suggestions still waiting for review, and link_targets: the only URLs suggest_content_changes may link to (own_pages for internal links, sources for outbound links and inline citations). With them, `last_send` and `shopping_links` as list_content_drafts gives them, and `shopping_path`: on a page of an online shop, the category pages and catalog products it should link (with price and stock) and those left out and why, as its Brief tab shows them; null for none.',inputSchema: {draft_id: relaxedUuid.describe('Draft UUID, from list_content_drafts.'),},@@ -1825,5 +1828,65 @@ export function createMcpServer(auth: McpAuthContext): McpServer {},);+ // ─── The Content plan and pages ready for a CMS (B5) ───++ server.registerTool(+ 'get_content_plan',+ {+ title: 'Content plan',+ description:+ "The brand's Content plan, as the Content › Plan page ranks it: what to write or fix next, by the Priority Score (0–100: severity 40, opportunity 30, page value 20, citations 10; `score_parts` says what each row's is made of). Each row: `action` (create a new page, optimize a page losing citations or with an opportunity on it, protect a top page), title, the page (null for a new one), page_type, `why` (competitors cited instead, an opportunity's prompts, a citation drop and its platforms, or a top page's citations and AI visits), opportunity_id, the draft already being written for it (with its assignee and editor path) and whether a person marked it a priority (those come first). `counts` per card and `hidden` (rows a person hid). Over `days` 7, 30 or 90 (default 30); `card` narrows to create, optimize, protect or priority. At most 50 rows.",+ inputSchema: {+ brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),+ days: z+ .union([+ z.literal(PLAN_PERIODS[0]),+ z.literal(PLAN_PERIODS[1]),+ z.literal(PLAN_PERIODS[2]),+ ])+ .optional()+ .describe('The period the plan reads: 7, 30 (default) or 90 days.'),+ card: z+ .enum(PLAN_CARDS)+ .optional()+ .describe('Only this card: create, optimize, protect or priority.'),+ },+ annotations: { readOnlyHint: true, openWorldHint: false },+ },+ async (args) => {+ const plan = await getContentPlanFor(auth, {+ brandId: args.brand_id,+ days: args.days ?? 30,+ card: args.card,+ });+ return plan ? json(plan) : notFound('Brand');+ },+ );++ server.registerTool(+ 'mark_content_draft_published',+ {+ title: 'Mark a draft published',+ description:+ "Mark a Content Editor draft Published at the address it went live at, as the editor's Mark published does: for a page you (the user's AI tool) put on their CMS with its own connector — Ansvisor never sends it. Ansvisor then measures that address (get_content_impact, the Live page tab: citations, AI visits, Google clicks) and a linked Action Center action's Publish task completes once every page it names is live. The address must be http(s), with no sign-in details; one off the brand's domains is kept but can't be measured (on_brand_domain false). Marking it again at a new address moves it. It is a write — only once the page is really live, on the user's say.",+ inputSchema: {+ draft_id: relaxedUuid.describe('Draft UUID, from list_content_drafts.'),+ url: z.string().max(2048).describe('The http(s) address the page is live at.'),+ },+ annotations: {+ readOnlyHint: false,+ destructiveHint: false,+ idempotentHint: true,+ openWorldHint: false,+ },+ },+ async (args) => {+ const result = await markContentDraftPublishedFor(auth, args.draft_id, args.url);+ return 'error' in result+ ? { content: [{ type: 'text' as const, text: result.message }], isError: true }+ : json(result);+ },+ );+return server;}diff --git a/web/src/lib/mcp/subscription-gate.test.ts b/web/src/lib/mcp/subscription-gate.test.tsindex 070f5652e..f1eccd407 100644--- a/web/src/lib/mcp/subscription-gate.test.ts+++ b/web/src/lib/mcp/subscription-gate.test.ts@@ -78,7 +78,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(39);+ expect(names.filter(isReadTool)).toHaveLength(40);expect(names.filter((name) => !isReadTool(name)).sort()).toEqual(['accept_prompt_suggestion','accept_topic_suggestion',@@ -88,6 +88,7 @@ describe('the MCP tools on a read-only workspace', () => {'dismiss_prompt_suggestion','dismiss_topic_suggestion','generate_content_brief',+ 'mark_content_draft_published','override_mention_sentiment','run_site_audit','set_content_draft_ready',@@ -111,7 +112,7 @@ describe('the MCP tools on a read-only workspace', () => {})._registeredTools;const gated = Object.keys(registered).filter((name) => !isReadTool(name));- expect(gated).toHaveLength(14);+ expect(gated).toHaveLength(15);for (const name of gated) {const result = (await registered[name].handler({}, {})) as {isError?: boolean;