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): read the demo brand and refuse its writes over MCP (demo brand, part 6) (#1739)

Cihan284140616a8d
diff --git a/web/src/app/api/mcp/action-tasks/[id]/status/route.ts b/web/src/app/api/mcp/action-tasks/[id]/status/route.ts
index 492bc2363..52d36388e 100644
--- a/web/src/app/api/mcp/action-tasks/[id]/status/route.ts
+++ b/web/src/app/api/mcp/action-tasks/[id]/status/route.ts
@@ -1,5 +1,6 @@
import { NextResponse } from 'next/server';
import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { demoBrandRefusal } from '@/lib/mcp/demo-gate';
import { MCP_TASK_STATUSES, updateTaskStatusFor, type McpTaskStatus } from '@/lib/mcp/data';
/**
@@ -42,6 +43,11 @@ export async function PATCH(req: Request, { params }: { params: Promise<{ id: st
}
try {
+ // Nothing written on the demo brand's sample data, as the tool refuses it.
+ const refused = await demoBrandRefusal('update_task_status', auth.organizationId, {
+ task_id: id,
+ });
+ if (refused) return refused;
const updated = await updateTaskStatusFor(auth, id, status as McpTaskStatus, skipReason);
if (!updated) {
return NextResponse.json({ error: 'Task not found' }, { status: 404 });
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.ts
index dba64d349..31d34b81c 100644
--- a/web/src/app/api/mcp/content-drafts/[id]/published/route.ts
+++ b/web/src/app/api/mcp/content-drafts/[id]/published/route.ts
@@ -1,6 +1,7 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { demoBrandRefusal } from '@/lib/mcp/demo-gate';
import { markContentDraftPublishedFor } from '@/lib/mcp/content-delivery';
import { failedCallResponse } from '@/lib/mcp/subscription-gate';
import { contentUuid } from '@/lib/mcp/content-schemas';
@@ -20,6 +21,11 @@ export async function POST(req: Request, { params }: { params: Promise<{ id: str
return NextResponse.json({ error: 'Invalid request' }, { status: 400 });
}
try {
+ // Nothing written on the demo brand's sample data, as the tool refuses it.
+ const refused = await demoBrandRefusal('mark_content_draft_published', auth.organizationId, {
+ draft_id: id,
+ });
+ if (refused) return refused;
const result = await markContentDraftPublishedFor(auth, id, parsed.data.url);
if ('error' in result) {
return NextResponse.json(
diff --git a/web/src/app/api/mcp/content-drafts/[id]/ready/route.ts b/web/src/app/api/mcp/content-drafts/[id]/ready/route.ts
index fde39a1f2..891da3bf4 100644
--- a/web/src/app/api/mcp/content-drafts/[id]/ready/route.ts
+++ b/web/src/app/api/mcp/content-drafts/[id]/ready/route.ts
@@ -1,5 +1,6 @@
import { NextResponse } from 'next/server';
import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { demoBrandRefusal } from '@/lib/mcp/demo-gate';
import { setContentDraftReadyFor } from '@/lib/mcp/content';
import { contentUuid } from '@/lib/mcp/content-schemas';
@@ -12,6 +13,11 @@ export async function POST(req: Request, { params }: { params: Promise<{ id: str
return NextResponse.json({ error: 'id must be a draft UUID' }, { status: 400 });
}
try {
+ // Nothing written on the demo brand's sample data, as the tool refuses it.
+ const refused = await demoBrandRefusal('set_content_draft_ready', auth.organizationId, {
+ draft_id: id,
+ });
+ if (refused) return refused;
const result = await setContentDraftReadyFor(auth, id);
if (result === 'in_review') {
return NextResponse.json(
diff --git a/web/src/app/api/mcp/content-drafts/[id]/sources/route.ts b/web/src/app/api/mcp/content-drafts/[id]/sources/route.ts
index 21afe6c62..74bbba217 100644
--- a/web/src/app/api/mcp/content-drafts/[id]/sources/route.ts
+++ b/web/src/app/api/mcp/content-drafts/[id]/sources/route.ts
@@ -1,6 +1,7 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { demoBrandRefusal } from '@/lib/mcp/demo-gate';
import { addContentSourceFor, getContentSourcesFor } from '@/lib/mcp/content';
import { addSourceShape, contentUuid, sourceRefError } from '@/lib/mcp/content-schemas';
@@ -40,6 +41,11 @@ export async function POST(req: Request, { params }: { params: Promise<{ id: str
const refError = sourceRefError(kind, ref);
if (refError) return NextResponse.json({ error: refError }, { status: 400 });
try {
+ // Nothing written on the demo brand's sample data, as the tool refuses it.
+ const refused = await demoBrandRefusal('add_content_source', auth.organizationId, {
+ draft_id: id,
+ });
+ if (refused) return refused;
const result = await addContentSourceFor(
auth,
id,
diff --git a/web/src/app/api/mcp/content-drafts/[id]/suggestions/route.ts b/web/src/app/api/mcp/content-drafts/[id]/suggestions/route.ts
index ae9181d8c..9ffc96ce4 100644
--- a/web/src/app/api/mcp/content-drafts/[id]/suggestions/route.ts
+++ b/web/src/app/api/mcp/content-drafts/[id]/suggestions/route.ts
@@ -1,6 +1,7 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { demoBrandRefusal } from '@/lib/mcp/demo-gate';
import { suggestContentChangesFor } from '@/lib/mcp/content';
import { contentUuid, suggestionsShape } from '@/lib/mcp/content-schemas';
@@ -17,6 +18,11 @@ export async function POST(req: Request, { params }: { params: Promise<{ id: str
return NextResponse.json({ error: 'Invalid request' }, { status: 400 });
}
try {
+ // Nothing written on the demo brand's sample data, as the tool refuses it.
+ const refused = await demoBrandRefusal('suggest_content_changes', auth.organizationId, {
+ draft_id: id,
+ });
+ if (refused) return refused;
const result = await suggestContentChangesFor(auth, id, parsed.data.suggestions);
if (result === 'published') {
return NextResponse.json(
diff --git a/web/src/app/api/mcp/content-drafts/route.ts b/web/src/app/api/mcp/content-drafts/route.ts
index a66f5972b..1170bef64 100644
--- a/web/src/app/api/mcp/content-drafts/route.ts
+++ b/web/src/app/api/mcp/content-drafts/route.ts
@@ -1,6 +1,7 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { demoBrandRefusal } from '@/lib/mcp/demo-gate';
import { createContentDraftFor, listContentDraftsFor } from '@/lib/mcp/content';
import { createDraftShape, listDraftsShape } from '@/lib/mcp/content-schemas';
@@ -50,6 +51,11 @@ export async function POST(req: Request) {
}
const body = parsed.data;
try {
+ // Nothing written on the demo brand's sample data, as the tool refuses it.
+ const refused = await demoBrandRefusal('create_content_draft', auth.organizationId, {
+ brand_id: body.brand_id,
+ });
+ if (refused) return refused;
const created = await createContentDraftFor(auth, {
brandId: body.brand_id,
title: body.title,
diff --git a/web/src/app/api/mcp/content-opportunities/[id]/status/route.ts b/web/src/app/api/mcp/content-opportunities/[id]/status/route.ts
index c9417ea7d..4880d4dd6 100644
--- a/web/src/app/api/mcp/content-opportunities/[id]/status/route.ts
+++ b/web/src/app/api/mcp/content-opportunities/[id]/status/route.ts
@@ -1,5 +1,6 @@
import { NextResponse } from 'next/server';
import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { demoBrandRefusal } from '@/lib/mcp/demo-gate';
import {
CONTENT_OPPORTUNITY_STATUSES,
updateOpportunityStatusFor,
@@ -47,6 +48,11 @@ export async function PATCH(req: Request, { params }: { params: Promise<{ id: st
}
try {
+ // Nothing written on the demo brand's sample data, as the tool refuses it.
+ const refused = await demoBrandRefusal('update_opportunity_status', auth.organizationId, {
+ opportunity_id: opportunityId,
+ });
+ if (refused) return refused;
const updated = await updateOpportunityStatusFor(
auth,
opportunityId,
diff --git a/web/src/app/api/mcp/mentions/[id]/sentiment-override/route.ts b/web/src/app/api/mcp/mentions/[id]/sentiment-override/route.ts
index cd9febb58..8ade891d1 100644
--- a/web/src/app/api/mcp/mentions/[id]/sentiment-override/route.ts
+++ b/web/src/app/api/mcp/mentions/[id]/sentiment-override/route.ts
@@ -1,5 +1,6 @@
import { NextResponse } from 'next/server';
import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { demoBrandRefusal } from '@/lib/mcp/demo-gate';
import { isMentionSentiment, overrideMentionSentimentFor } from '@/lib/mcp/mentions';
const STATUS = { forbidden: 403, invalid: 400, missing: 404 } as const;
@@ -38,6 +39,11 @@ export async function POST(req: Request, { params }: { params: Promise<{ id: str
}
try {
+ // Nothing written on the demo brand's sample data, as the tool refuses it.
+ const refused = await demoBrandRefusal('override_mention_sentiment', auth.organizationId, {
+ id,
+ });
+ if (refused) return refused;
const result = await overrideMentionSentimentFor(auth, id, body.sentiment, body.note);
if ('error' in result) {
return NextResponse.json({ error: result.message }, { status: STATUS[result.error] });
diff --git a/web/src/app/api/mcp/task-reviews/[id]/approve/route.ts b/web/src/app/api/mcp/task-reviews/[id]/approve/route.ts
index 6d9dcb795..d7ee03dd6 100644
--- a/web/src/app/api/mcp/task-reviews/[id]/approve/route.ts
+++ b/web/src/app/api/mcp/task-reviews/[id]/approve/route.ts
@@ -1,6 +1,7 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { demoBrandRefusal } from '@/lib/mcp/demo-gate';
import { failedCallResponse } from '@/lib/mcp/subscription-gate';
import {
TASK_REVIEW_ERROR_STATUS,
@@ -33,6 +34,11 @@ export async function POST(req: Request, { params }: { params: Promise<{ id: str
}
try {
+ // Nothing written on the demo brand's sample data, as the tool refuses it.
+ const refused = await demoBrandRefusal('approve_task_review', auth.organizationId, {
+ review_id: id,
+ });
+ if (refused) return refused;
const result = await approveTaskReviewFor(auth, id, body.data);
if ('error' in result) {
return NextResponse.json(
diff --git a/web/src/app/api/mcp/task-reviews/[id]/dismiss/route.ts b/web/src/app/api/mcp/task-reviews/[id]/dismiss/route.ts
index 58373bdc7..3d4ec1e21 100644
--- a/web/src/app/api/mcp/task-reviews/[id]/dismiss/route.ts
+++ b/web/src/app/api/mcp/task-reviews/[id]/dismiss/route.ts
@@ -1,5 +1,6 @@
import { NextResponse } from 'next/server';
import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { demoBrandRefusal } from '@/lib/mcp/demo-gate';
import { failedCallResponse } from '@/lib/mcp/subscription-gate';
import { TASK_REVIEW_ERROR_STATUS, dismissTaskReviewFor } from '@/lib/mcp/task-reviews';
@@ -10,6 +11,11 @@ export async function POST(req: Request, { params }: { params: Promise<{ id: str
const { id } = await params;
try {
+ // Nothing written on the demo brand's sample data, as the tool refuses it.
+ const refused = await demoBrandRefusal('dismiss_task_review', auth.organizationId, {
+ review_id: id,
+ });
+ if (refused) return refused;
const result = await dismissTaskReviewFor(auth, id);
if ('error' in result) {
return NextResponse.json(
diff --git a/web/src/app/api/mcp/topic-suggestions/[id]/accept/route.ts b/web/src/app/api/mcp/topic-suggestions/[id]/accept/route.ts
index 66c8dbbf8..c4398d278 100644
--- a/web/src/app/api/mcp/topic-suggestions/[id]/accept/route.ts
+++ b/web/src/app/api/mcp/topic-suggestions/[id]/accept/route.ts
@@ -1,5 +1,6 @@
import { NextResponse } from 'next/server';
import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { demoBrandRefusal } from '@/lib/mcp/demo-gate';
import { acceptTopicSuggestionFor } from '@/lib/mcp/data';
import { failedCallResponse } from '@/lib/mcp/subscription-gate';
@@ -22,6 +23,11 @@ export async function POST(req: Request, { params }: { params: Promise<{ id: str
}
try {
+ // Nothing written on the demo brand's sample data, as the tool refuses it.
+ const refused = await demoBrandRefusal('accept_topic_suggestion', auth.organizationId, {
+ suggestion_id: suggestionId,
+ });
+ if (refused) return refused;
const result = await acceptTopicSuggestionFor(auth, suggestionId);
if (!result) {
return NextResponse.json(
diff --git a/web/src/app/api/mcp/topic-suggestions/[id]/dismiss/route.ts b/web/src/app/api/mcp/topic-suggestions/[id]/dismiss/route.ts
index 0f65e8e4b..13375184d 100644
--- a/web/src/app/api/mcp/topic-suggestions/[id]/dismiss/route.ts
+++ b/web/src/app/api/mcp/topic-suggestions/[id]/dismiss/route.ts
@@ -1,5 +1,6 @@
import { NextResponse } from 'next/server';
import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { demoBrandRefusal } from '@/lib/mcp/demo-gate';
import { dismissTopicSuggestionFor } from '@/lib/mcp/data';
import { failedCallResponse } from '@/lib/mcp/subscription-gate';
@@ -21,6 +22,11 @@ export async function POST(req: Request, { params }: { params: Promise<{ id: str
}
try {
+ // Nothing written on the demo brand's sample data, as the tool refuses it.
+ const refused = await demoBrandRefusal('dismiss_topic_suggestion', auth.organizationId, {
+ suggestion_id: suggestionId,
+ });
+ if (refused) return refused;
const result = await dismissTopicSuggestionFor(auth, suggestionId);
if (!result) {
return NextResponse.json(
diff --git a/web/src/lib/mcp/content-delivery.ts b/web/src/lib/mcp/content-delivery.ts
index 05623000d..7ce352950 100644
--- a/web/src/lib/mcp/content-delivery.ts
+++ b/web/src/lib/mcp/content-delivery.ts
@@ -160,11 +160,8 @@ export type McpPublishError = { error: 'invalid_url' | 'not_found'; message: str
* 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.
+ * key's organization's. Never on a demo brand (00380): the tool and its REST
+ * mirror refuse it (lib/mcp/demo-gate.ts), and so does the endpoint.
*/
export async function markContentDraftPublishedFor(
auth: McpAuthContext,
diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.ts
index c38105f59..4fb4f2c79 100644
--- a/web/src/lib/mcp/data.ts
+++ b/web/src/lib/mcp/data.ts
@@ -18,6 +18,7 @@ import { API_BASE_URL } from '@/config/api';
import { ORG_PLAN_COLUMNS, planFromOrgRow, usagePlanFromOrgRow } from '@/lib/guards/plan-guard';
import { PLANS, type Feature, getMinimumPlanForFeature, hasFeature, isCloud } from '@/config/plans';
import { assertSubscriptionActive } from '@/lib/mcp/subscription-gate';
+import { DemoBrandError, assertNotDemoBrand, callOnDemoBrand } from '@/lib/mcp/demo-gate';
import { MEMBER_ROLES, requireManager, requireRole } from '@/lib/mcp/role-gate';
import {
fetchPromptUsageRow,
@@ -64,15 +65,23 @@ export interface BrandRow {
industry: string | null;
region: string | null;
created_at: string;
+ /** The demo brand (00380): sample data, read like any brand; nothing on it is written or run. */
+ is_demo: boolean;
}
+/**
+ * The organization's brands, newest first. The demo brand is one of them,
+ * marked is_demo, unless the organization hid it (once a plan was bought, or
+ * from the brand menu).
+ */
export async function listBrandsFor(auth: McpAuthContext): Promise<BrandRow[]> {
if (!auth.organizationId) return [];
const { data, error } = await supabaseAdmin
.from('brands')
- .select('id, name, slug, industry, region, created_at')
+ .select('id, name, slug, industry, region, created_at, is_demo')
.eq('organization_id', auth.organizationId)
+ .or('is_demo.eq.false,demo_hidden_at.is.null')
.order('created_at', { ascending: false });
if (error) throw new Error(error.message);
@@ -1041,7 +1050,15 @@ export async function generateBriefFor(
.eq('brands.organization_id', auth.organizationId)
.maybeSingle();
if (!ownership) return null;
- // No brief (an LLM call) for a read-only workspace, whoever asks.
+ // No brief (an LLM call) on the demo brand, nor for a read-only workspace, whoever asks.
+ // Only Ansvisor Cloud has demo brands: self-hosted reads nothing for it.
+ if (
+ await callOnDemoBrand('generate_content_brief', auth.organizationId, {
+ opportunity_id: opportunityId,
+ })
+ ) {
+ throw new DemoBrandError();
+ }
await assertSubscriptionActive(auth.organizationId);
const apiUrl = API_BASE_URL;
@@ -1227,7 +1244,8 @@ export async function runSiteAuditFor(
.eq('organization_id', auth.organizationId)
.maybeSingle();
if (!brand) return null;
- // No audit (quota and crawling) for a read-only workspace, whoever asks.
+ // No audit (quota and crawling) on the demo brand, nor for a read-only workspace, whoever asks.
+ await assertNotDemoBrand(auth.organizationId, brandId);
await assertSubscriptionActive(auth.organizationId);
const cronSecret = process.env.CRON_SECRET;
@@ -3561,7 +3579,15 @@ export async function createImproveActionFor(
.eq('prompt_sets.brands.organization_id', auth.organizationId)
.maybeSingle();
if (!ownership) return null;
- // No Improve action (an LLM call) for a read-only workspace, whoever asks.
+ // No Improve action (an LLM call) on the demo brand, nor for a read-only workspace, whoever asks.
+ // Only Ansvisor Cloud has demo brands: self-hosted reads nothing for it.
+ if (
+ await callOnDemoBrand('create_improve_action', auth.organizationId, {
+ prompt_id: input.promptId,
+ })
+ ) {
+ throw new DemoBrandError();
+ }
await assertSubscriptionActive(auth.organizationId);
const cronSecret = process.env.CRON_SECRET;
diff --git a/web/src/lib/mcp/demo-gate-routes.test.ts b/web/src/lib/mcp/demo-gate-routes.test.ts
new file mode 100644
index 000000000..a1378d8f5
--- /dev/null
+++ b/web/src/lib/mcp/demo-gate-routes.test.ts
@@ -0,0 +1,116 @@
+// @vitest-environment node
+import { readFileSync, readdirSync } from 'node:fs';
+import { join, relative } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * The demo brand (00380) on the MCP's REST mirrors: a route that writes,
+ * runs or spends refuses it with 402 demo_brand, as its tool does, before
+ * the data function writes anything with the service role.
+ */
+
+const ORG = 'org-1';
+const AUTH = {
+ userId: 'user-1',
+ email: null,
+ organizationId: ORG,
+ apiKeyId: 'key-1',
+ role: 'admin' as const,
+};
+
+/** The rows the fake database holds, by table and id. */
+let rows: Record<string, Record<string, Record<string, unknown>>>;
+
+function from(table: string) {
+ const filters: [string, unknown][] = [];
+ const query = {
+ select: () => query,
+ eq: (key: string, value: unknown) => {
+ filters.push([key, value]);
+ return query;
+ },
+ maybeSingle: async () => {
+ const found = Object.entries(rows[table] ?? {})
+ .map(([id, row]) => ({ id, ...row }) as Record<string, unknown>)
+ .filter((row) => filters.every(([key, value]) => row[key] === value));
+ return { data: found[0] ?? null, error: null };
+ },
+ };
+ return query;
+}
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: { from } }));
+vi.mock('@/lib/mcp-auth', () => ({ authenticateMcpRequest: async () => AUTH }));
+
+const data = vi.hoisted(() => ({
+ updateOpportunityStatusFor: vi.fn(async () => ({ id: 'opportunity-1', status: 'done' })),
+}));
+vi.mock('@/lib/mcp/data', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/lib/mcp/data')>()),
+ ...data,
+}));
+
+const { PATCH } = await import('@/app/api/mcp/content-opportunities/[id]/status/route');
+
+const patchStatus = (id: string) =>
+ PATCH(
+ new Request(`http://localhost/api/mcp/content-opportunities/${id}/status`, {
+ method: 'PATCH',
+ body: JSON.stringify({ status: 'done' }),
+ }),
+ { params: Promise.resolve({ id }) },
+ );
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');
+ rows = {
+ brands: {
+ 'demo-brand': { organization_id: ORG, is_demo: true },
+ 'own-brand': { organization_id: ORG, is_demo: false },
+ },
+ content_opportunities: {
+ 'opportunity-1': { brand_id: 'demo-brand' },
+ 'opportunity-2': { brand_id: 'own-brand' },
+ },
+ };
+});
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
+describe('the REST mirrors on the demo brand', () => {
+ it('refuse a write on it with 402 demo_brand, before the data function runs', async () => {
+ const res = await patchStatus('opportunity-1');
+ expect(res.status).toBe(402);
+ expect(await res.json()).toMatchObject({ code: 'demo_brand' });
+ expect(data.updateOpportunityStatusFor).not.toHaveBeenCalled();
+ });
+
+ it("run it on the organization's own brand", async () => {
+ const res = await patchStatus('opportunity-2');
+ expect(res.status).toBe(200);
+ expect(data.updateOpportunityStatusFor).toHaveBeenCalledWith(AUTH, 'opportunity-2', 'done');
+ });
+
+ it('check every route that writes, runs or spends', () => {
+ const root = join(process.cwd(), 'src/app/api/mcp');
+ const routes = (readdirSync(root, { recursive: true }) as string[])
+ .filter((file) => file.endsWith('route.ts'))
+ .map((file) => join(root, file));
+ // Through the data function, which refuses the demo brand itself.
+ const SELF_CHECKED = /\b(runSiteAuditFor|generateBriefFor|createImproveActionFor)\(/;
+ const unchecked = routes
+ .filter((file) => relative(root, file) !== 'route.ts') // the MCP endpoint: its tools are gated
+ .filter((file) => {
+ const source = readFileSync(file, 'utf8');
+ if (!/export (async function|const) (POST|PUT|PATCH|DELETE)\b/.test(source)) return false;
+ return !source.includes('demoBrandRefusal(') && !SELF_CHECKED.test(source);
+ })
+ .map((file) => relative(root, file));
+ // A route here writes on whatever brand it's given: call demoBrandRefusal
+ // with its tool's name and arguments before the data function.
+ expect(unchecked).toEqual([]);
+ expect(routes.length).toBeGreaterThan(10);
+ });
+});
diff --git a/web/src/lib/mcp/demo-gate.test.ts b/web/src/lib/mcp/demo-gate.test.ts
new file mode 100644
index 000000000..eaf7c62db
--- /dev/null
+++ b/web/src/lib/mcp/demo-gate.test.ts
@@ -0,0 +1,208 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * The demo brand (00380) on the MCP surface: every tool that writes, runs or
+ * spends answers demo_brand on it, whatever the plan; reading stays open; the
+ * brand list marks it, and leaves it out once hidden.
+ */
+
+const ORG = 'org-1';
+
+/** The rows the fake database holds, by table and id. */
+let rows: Record<string, Record<string, Record<string, unknown>>>;
+
+function from(table: string) {
+ const filters: [string, unknown][] = [];
+ let demoShown = false;
+ const run = () => {
+ let list: Record<string, unknown>[] = Object.entries(rows[table] ?? {}).map(([id, row]) => ({
+ id,
+ ...row,
+ }));
+ // A filter on an embedded table (brands.organization_id) is the caller's ownership check.
+ for (const [key, value] of filters) {
+ if (!key.includes('.')) list = list.filter((row) => row[key] === value);
+ }
+ if (demoShown) list = list.filter((row) => row.is_demo === false || row.demo_hidden_at == null);
+ return list;
+ };
+ const query = {
+ select: () => query,
+ eq: (key: string, value: unknown) => {
+ filters.push([key, value]);
+ return query;
+ },
+ or: (expression: string) => {
+ expect(expression).toBe('is_demo.eq.false,demo_hidden_at.is.null');
+ demoShown = true;
+ return query;
+ },
+ order: () => query,
+ maybeSingle: async () => ({ data: run()[0] ?? null, error: null }),
+ then: (resolve: (value: unknown) => unknown) =>
+ Promise.resolve({ data: run(), error: null }).then(resolve),
+ };
+ return query;
+}
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: { from } }));
+
+const data = vi.hoisted(() => ({
+ getVisibilitySummaryFor: vi.fn(async () => ({ brand: { id: 'demo-brand', name: 'Brewline' } })),
+ runSiteAuditFor: vi.fn(async () => ({ id: 'audit-1', status: 'running' })),
+}));
+vi.mock('@/lib/mcp/data', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/lib/mcp/data')>()),
+ ...data,
+}));
+
+const { createMcpServer } = await import('./server');
+const { isReadTool } = await import('./subscription-gate');
+const { WRITE_TOOL_BRANDS, DemoBrandError } = await import('./demo-gate');
+const { listBrandsFor, generateBriefFor } = await import('./data');
+
+const AUTH = {
+ userId: 'user-1',
+ email: null,
+ organizationId: ORG,
+ apiKeyId: 'key-1',
+ role: 'admin' as const,
+};
+
+/** Each tool's arguments for a call on the demo brand. */
+const ON_DEMO: Record<string, Record<string, unknown>> = {
+ accept_topic_suggestion: { suggestion_id: 'topic-suggestion-1' },
+ dismiss_topic_suggestion: { suggestion_id: 'topic-suggestion-1' },
+ accept_prompt_suggestion: { suggestion_id: 'prompt-suggestion-1' },
+ dismiss_prompt_suggestion: { suggestion_id: 'prompt-suggestion-1' },
+ generate_content_brief: { opportunity_id: 'opportunity-1' },
+ update_opportunity_status: { opportunity_id: 'opportunity-1', status: 'dismissed' },
+ run_site_audit: { brand_id: 'demo-brand', url: 'https://brewline.example/' },
+ update_task_status: { task_id: 'task-1', status: 'completed' },
+ create_improve_action: { prompt_id: 'prompt-1', range: { preset: '7d' } },
+ override_mention_sentiment: { id: 'result-1', sentiment: 'positive' },
+ create_content_draft: { brand_id: 'demo-brand', title: 'T', body_html: '<h1>T</h1>' },
+ add_content_source: { draft_id: 'draft-1', kind: 'url', ref: 'https://brewline.example/' },
+ suggest_content_changes: { draft_id: 'draft-1', suggestions: [] },
+ set_content_draft_ready: { draft_id: 'draft-1' },
+ mark_content_draft_published: { draft_id: 'draft-1', url: 'https://brewline.example/blog/' },
+ approve_task_review: { review_id: 'review-1' },
+ dismiss_task_review: { review_id: 'review-1' },
+};
+
+/** The handlers the SDK calls once a call's arguments are checked. */
+function handlers() {
+ const server = createMcpServer(AUTH);
+ return (
+ server as unknown as {
+ _registeredTools: Record<string, { handler: (...args: unknown[]) => unknown }>;
+ }
+ )._registeredTools;
+}
+
+type ToolResult = { isError?: boolean; content: { text: string }[] };
+const body = (result: unknown) => JSON.parse((result as ToolResult).content[0].text);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');
+ rows = {
+ organizations: { [ORG]: { subscription_status: 'active' } },
+ brands: {
+ 'demo-brand': { organization_id: ORG, is_demo: true, demo_hidden_at: null, name: 'Brewline' },
+ 'own-brand': { organization_id: ORG, is_demo: false, demo_hidden_at: null, name: 'Acme' },
+ 'other-demo': { organization_id: 'org-2', is_demo: true, demo_hidden_at: null },
+ },
+ topic_suggestions: { 'topic-suggestion-1': { brand_id: 'demo-brand' } },
+ prompt_suggestions: { 'prompt-suggestion-1': { brand_id: 'demo-brand' } },
+ content_opportunities: { 'opportunity-1': { brand_id: 'demo-brand' } },
+ action_tasks: { 'task-1': { action_id: 'action-1' } },
+ action_task_reviews: { 'review-1': { action_id: 'action-1' } },
+ actions: { 'action-1': { brand_id: 'demo-brand' } },
+ prompts: { 'prompt-1': { prompt_set_id: 'set-1' } },
+ prompt_sets: { 'set-1': { brand_id: 'demo-brand' } },
+ prompt_results: { 'result-1': { brand_id: 'demo-brand' } },
+ content_drafts: { 'draft-1': { brand_id: 'demo-brand' } },
+ };
+});
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
+describe('the MCP tools on the demo brand', () => {
+ it('knows how every tool that writes, runs or spends finds its brand', () => {
+ const gated = Object.keys(handlers()).filter((name) => !isReadTool(name));
+ // A new such tool fails here until WRITE_TOOL_BRANDS says how it finds its brand.
+ expect(Object.keys(WRITE_TOOL_BRANDS).sort()).toEqual(gated.sort());
+ expect(Object.keys(ON_DEMO).sort()).toEqual(gated.sort());
+ });
+
+ it('refuses each of them on the demo brand, whatever the plan', async () => {
+ const registered = handlers();
+ for (const [name, args] of Object.entries(ON_DEMO)) {
+ const result = (await registered[name].handler(args, {})) as ToolResult;
+ expect(result.isError, name).toBe(true);
+ expect(body(result), name).toMatchObject({ code: 'demo_brand' });
+ }
+ expect(data.runSiteAuditFor).not.toHaveBeenCalled();
+ });
+
+ it('runs them on the organization’s own brand', async () => {
+ const result = await handlers().run_site_audit.handler(
+ { brand_id: 'own-brand', url: 'https://acme.example/' },
+ {},
+ );
+ expect((result as ToolResult).isError).toBeUndefined();
+ expect(data.runSiteAuditFor).toHaveBeenCalledWith(AUTH, 'own-brand', 'https://acme.example/');
+ });
+
+ it('leaves another organization’s demo brand to the tool’s own check', async () => {
+ await handlers().run_site_audit.handler(
+ { brand_id: 'other-demo', url: 'https://brewline.example/' },
+ {},
+ );
+ expect(data.runSiteAuditFor).toHaveBeenCalled();
+ });
+
+ it('keeps reading open on the demo brand', async () => {
+ const result = (await handlers().get_visibility_summary.handler(
+ { brand_id: 'demo-brand' },
+ {},
+ )) as ToolResult;
+ expect(result.isError).toBeUndefined();
+ expect(data.getVisibilitySummaryFor).toHaveBeenCalled();
+ });
+
+ it('checks nothing self-hosted, where there is no demo brand', async () => {
+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'false');
+ await handlers().run_site_audit.handler(
+ { brand_id: 'demo-brand', url: 'https://brewline.example/' },
+ {},
+ );
+ expect(data.runSiteAuditFor).toHaveBeenCalled();
+ });
+
+ it('refuses a brief on the demo brand on the REST route’s path too', async () => {
+ const fetchSpy = vi.spyOn(globalThis, 'fetch');
+ await expect(generateBriefFor(AUTH, 'opportunity-1')).rejects.toBeInstanceOf(DemoBrandError);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ fetchSpy.mockRestore();
+ });
+});
+
+describe('listBrandsFor', () => {
+ it('marks the demo brand', async () => {
+ const brands = await listBrandsFor(AUTH);
+ expect(brands.map((b) => [b.id, b.is_demo])).toEqual([
+ ['demo-brand', true],
+ ['own-brand', false],
+ ]);
+ });
+
+ it('leaves the demo brand out once hidden', async () => {
+ rows.brands['demo-brand'].demo_hidden_at = '2026-10-28T12:00:00Z';
+ const brands = await listBrandsFor(AUTH);
+ expect(brands.map((b) => b.id)).toEqual(['own-brand']);
+ });
+});
diff --git a/web/src/lib/mcp/demo-gate.ts b/web/src/lib/mcp/demo-gate.ts
new file mode 100644
index 000000000..09a507040
--- /dev/null
+++ b/web/src/lib/mcp/demo-gate.ts
@@ -0,0 +1,156 @@
+import { NextResponse } from 'next/server';
+import { isCloud } from '@/config/plans';
+import { supabaseAdmin } from '@/lib/supabase/admin';
+import { DEMO_BRAND, DemoBrandError } from '@/lib/subscription-guard';
+
+/**
+ * The demo brand (00380) on the API key surface: its data is a sample, so
+ * the MCP tools and REST routes read it like any brand, and refuse to write,
+ * run or spend anything on it, whatever the plan, with the body the web
+ * app's writes answer (DEMO_BRAND), which tells the agent the same thing
+ * runs on the workspace's own brand once a plan is picked. Demo brands are
+ * Ansvisor Cloud's: self-hosted is never checked.
+ */
+export { DEMO_BRAND, DemoBrandError };
+
+type Args = Record<string, unknown>;
+
+/** How a tool that writes, runs or spends finds the brand it acts on; null when it names none. */
+type BrandOf = (args: Args) => Promise<string | null>;
+
+const idIn = (args: Args, key: string): string | null =>
+ typeof args?.[key] === 'string' ? (args[key] as string) : null;
+
+/** One row's column, by id; null when the row isn't there. */
+async function columnOf(table: string, id: string | null, column: string): Promise<string | null> {
+ if (!id) return null;
+ const { data, error } = await supabaseAdmin
+ .from(table as never)
+ .select(column)
+ .eq('id', id)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ const value = (data as Record<string, unknown> | null)?.[column];
+ return typeof value === 'string' ? value : null;
+}
+
+const brandOfRow =
+ (table: string, key: string): BrandOf =>
+ (args) =>
+ columnOf(table, idIn(args, key), 'brand_id');
+
+/** A task waiting for review (00293) belongs to its action's brand. */
+const brandOfTaskReview: BrandOf = async (args) =>
+ columnOf(
+ 'actions',
+ await columnOf('action_task_reviews', idIn(args, 'review_id'), 'action_id'),
+ 'brand_id',
+ );
+
+/**
+ * Every MCP tool that writes, runs or spends, and how it finds its brand.
+ * Its test fails on a tool missing here, so a new one can't skip the demo
+ * brand's refusal.
+ */
+export const WRITE_TOOL_BRANDS: Record<string, BrandOf> = {
+ accept_topic_suggestion: brandOfRow('topic_suggestions', 'suggestion_id'),
+ dismiss_topic_suggestion: brandOfRow('topic_suggestions', 'suggestion_id'),
+ accept_prompt_suggestion: brandOfRow('prompt_suggestions', 'suggestion_id'),
+ dismiss_prompt_suggestion: brandOfRow('prompt_suggestions', 'suggestion_id'),
+ generate_content_brief: brandOfRow('content_opportunities', 'opportunity_id'),
+ update_opportunity_status: brandOfRow('content_opportunities', 'opportunity_id'),
+ run_site_audit: async (args) => idIn(args, 'brand_id'),
+ update_task_status: async (args) =>
+ columnOf(
+ 'actions',
+ await columnOf('action_tasks', idIn(args, 'task_id'), 'action_id'),
+ 'brand_id',
+ ),
+ create_improve_action: async (args) =>
+ columnOf(
+ 'prompt_sets',
+ await columnOf('prompts', idIn(args, 'prompt_id'), 'prompt_set_id'),
+ 'brand_id',
+ ),
+ override_mention_sentiment: brandOfRow('prompt_results', 'id'),
+ create_content_draft: async (args) => idIn(args, 'brand_id'),
+ add_content_source: brandOfRow('content_drafts', 'draft_id'),
+ suggest_content_changes: brandOfRow('content_drafts', 'draft_id'),
+ set_content_draft_ready: brandOfRow('content_drafts', 'draft_id'),
+ mark_content_draft_published: brandOfRow('content_drafts', 'draft_id'),
+ approve_task_review: brandOfTaskReview,
+ dismiss_task_review: brandOfTaskReview,
+};
+
+/**
+ * Whether a brand of the organization is its demo brand. Another
+ * organization's brand reads as not: the call itself then answers it as
+ * missing, as it always has.
+ */
+export async function isDemoBrandOf(
+ organizationId: string | null,
+ brandId: string | null,
+): Promise<boolean> {
+ if (!isCloud() || !organizationId || !brandId) return false;
+ const { data, error } = await supabaseAdmin
+ .from('brands')
+ .select('is_demo')
+ .eq('id', brandId)
+ .eq('organization_id', organizationId)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ return data?.is_demo === true;
+}
+
+/**
+ * Refuse a costly call on the demo brand (a brief, a Site Audit, an Improve
+ * action), whoever calls it: an MCP tool, a REST route or the in-product
+ * agent, as assertSubscriptionActive refuses it while read-only.
+ */
+export async function assertNotDemoBrand(
+ organizationId: string | null,
+ brandId: string | null,
+): Promise<void> {
+ if (await isDemoBrandOf(organizationId, brandId)) throw new DemoBrandError();
+}
+
+/** Whether a tool's call acts on the organization's demo brand. */
+export async function callOnDemoBrand(
+ name: string,
+ organizationId: string | null,
+ args: unknown,
+): Promise<boolean> {
+ const brandOf = WRITE_TOOL_BRANDS[name];
+ if (!brandOf || !isCloud() || !organizationId) return false;
+ return isDemoBrandOf(organizationId, await brandOf((args ?? {}) as Args));
+}
+
+/** A tool's answer to a call on the demo brand: a tool error carrying the same body. */
+export function demoBrandToolResult() {
+ return {
+ content: [{ type: 'text' as const, text: JSON.stringify(DEMO_BRAND, null, 2) }],
+ isError: true,
+ };
+}
+
+/**
+ * A REST mirror's answer to a write on the demo brand: 402 with the body the
+ * tool answers, or null when the call may go on. `tool` and `args` are the
+ * mirrored tool's, so the route finds the brand as the tool does. A brand
+ * that can't be read refuses too (500): the write never runs unchecked.
+ * Every REST route that writes, runs or spends calls this, or a data
+ * function that refuses the demo brand itself (demo-gate.test.ts).
+ */
+export async function demoBrandRefusal(
+ tool: keyof typeof WRITE_TOOL_BRANDS,
+ organizationId: string | null,
+ args: Args,
+): Promise<NextResponse | null> {
+ try {
+ if (!(await callOnDemoBrand(tool, organizationId, args))) return null;
+ return NextResponse.json(DEMO_BRAND, { status: 402 });
+ } catch (err) {
+ console.error('[mcp] demo brand check failed:', err);
+ return NextResponse.json({ error: 'Failed' }, { status: 500 });
+ }
+}
diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.ts
index 60bc41589..af961c70b 100644
--- a/web/src/lib/mcp/server.ts
+++ b/web/src/lib/mcp/server.ts
@@ -188,7 +188,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
{
title: 'Brands',
description:
- 'List the brands the authenticated user can access. Returns one row per brand with id, name, slug, industry, region, and creation date. Always call this first to resolve a brand id before using other tools.',
+ 'List the brands the authenticated user can access. Returns one row per brand with id, name, slug, industry, region, creation date and is_demo. A brand with is_demo true is the demo brand: sample data for exploring Ansvisor, read like any brand, but nothing on it can be changed, run or generated (those tools answer demo_brand); say so when you report on it. Always call this first to resolve a brand id before using other tools.',
inputSchema: {},
annotations: { readOnlyHint: true, openWorldHint: false },
},
diff --git a/web/src/lib/mcp/subscription-gate.ts b/web/src/lib/mcp/subscription-gate.ts
index 47a393ba9..c3162c2ad 100644
--- a/web/src/lib/mcp/subscription-gate.ts
+++ b/web/src/lib/mcp/subscription-gate.ts
@@ -7,6 +7,7 @@ import {
failedCallResponse,
subscriptionInactiveResponse,
} from '@/lib/subscription-guard';
+import { callOnDemoBrand, demoBrandToolResult } from './demo-gate';
/**
* Ansvisor Cloud's read-only mode on the API key surface (MCP tools, the
@@ -68,7 +69,8 @@ type LooseRegisterTool = (name: string, config: unknown, cb: AnyToolCallback) =>
* tool, check the organization's plan before it runs. The plan that can't be
* read refuses the call too (subscriptionActiveFor throws). The plan is read once
* per server, which the MCP route builds per request, and only when a gated
- * tool is called.
+ * tool is called. A call on the demo brand is refused first, whatever the
+ * plan (demo-gate.ts).
*/
export function gateWriteTools(server: McpServer, organizationId: string | null): McpServer {
let active: Promise<boolean> | null = null;
@@ -80,6 +82,7 @@ export function gateWriteTools(server: McpServer, organizationId: string | null)
isReadTool(name)
? cb
: async (...args: unknown[]) => {
+ if (await callOnDemoBrand(name, organizationId, args[0])) return demoBrandToolResult();
active ??= subscriptionActiveFor(organizationId);
if (!(await active)) return subscriptionInactiveToolResult();
return cb(...args);
diff --git a/web/src/lib/mcp/task-reviews.ts b/web/src/lib/mcp/task-reviews.ts
index 06e1e5eb3..bb4b44c6c 100644
--- a/web/src/lib/mcp/task-reviews.ts
+++ b/web/src/lib/mcp/task-reviews.ts
@@ -21,13 +21,10 @@ import { requireManager } from './role-gate';
* (requireManager): everyone else reads and changes none, as the table's RLS
* has it.
*
- * TODO(demo-brand-mcp): approve_task_review and dismiss_task_review find
- * their brand through action_task_reviews → actions.brand_id. When
- * feature/demo-brand-mcp merges, add them to WRITE_TOOL_BRANDS
- * (lib/mcp/demo-gate.ts) and call assertNotDemoBrand in
- * approveTaskReviewFor and dismissTaskReviewFor, so the REST mirrors refuse
- * a demo brand too: they write as the service role, which the demo trigger
- * (00381) lets through.
+ * On a demo brand (00380) the tools and their REST mirrors refuse both
+ * (WRITE_TOOL_BRANDS, demoBrandRefusal in lib/mcp/demo-gate.ts) before
+ * anything is written: these write as the service role, which the demo
+ * trigger (00381) lets through.
*/
/** A field a task waiting for review was written without, as the MCP names it. */