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 AI usage, measured demand and who you are over MCP (B2) (#1711)
Cihan9aab2ae8d055
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex f15d52926..d6c0d0566 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -62,7 +62,7 @@ jobs:- uses: actions/checkout@v4- uses: actions/setup-node@v4with:- node-version: 24+ node-version: 20cache: npmcache-dependency-path: server/package-lock.json- run: npm cidiff --git a/docs/api-reference/metrics.mdx b/docs/api-reference/metrics.mdxindex a5d8953a0..0fa2c07ca 100644--- a/docs/api-reference/metrics.mdx+++ b/docs/api-reference/metrics.mdx@@ -21,10 +21,18 @@ curl "https://app.ansvisor.com/api/v1/brands" \Keys are scoped to the user who created them and resolve to that user's organization: every endpoint only returns data for brands the organization owns. Revoking a key (Settings → API Keys) takes effect immediately.-`GET /api/v1/whoami` echoes the resolved identity — useful as a connection test:+`GET /api/v1/whoami` echoes the resolved identity — useful as a connection test. It also says the key's user's role, their work areas and whether they may choose who sees which menu sections:```json-{ "userId": "…", "email": "[email protected]", "organizationId": "…" }+{+ "userId": "…",+ "email": "[email protected]",+ "organizationId": "…",+ "organizationName": "Acme",+ "role": "manager",+ "workAreas": [{ "id": "content", "name": "Content" }],+ "canManageMenus": false+}```## Conventionsdiff --git a/docs/guides/mcp-server.mdx b/docs/guides/mcp-server.mdxindex 37d22091b..eb254ec03 100644--- a/docs/guides/mcp-server.mdx+++ b/docs/guides/mcp-server.mdx@@ -220,7 +220,7 @@ instead.## Available tools-The MCP server exposes **50 tools**. Descriptions below match+The MCP server exposes **52 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.@@ -232,6 +232,15 @@ intent, not during exploratory queries.| `list_brands` | List the brands the authenticated user can access (id, name, slug, industry, region). Call first to resolve a `brand_id`. | || `list_competitors` | Configured competitors for a brand (id, name, domain); this is not a performance ranking. | |+### Your account++| Tool | What it does | Writes |+| --- | --- | --- |+| `get_me` | Who the key acts as: user, organization, role, work areas (from **Settings → Account**) and whether they may choose who sees which menu sections (`can_manage_menus`). | |+| `get_ai_usage` | How much of the workspace's monthly AI allowance is used this period, as **Settings → Billing** shows it: `percent_used`, each feature's share (`improve`, `content`, `action_center`, `other`), the plan, the trial and the period's dates. `unlimited` self-hosted; `active_plan: false` without an active plan. | |++The same reads are available over REST with the same `ans_` key: `GET /api/mcp/whoami` and `GET /api/mcp/ai-usage`.+### Visibility & analytics| Tool | What it does | Writes |@@ -282,7 +291,7 @@ curl "https://app.ansvisor.com/api/mcp/mentions/summary?brand_id=<brand_id>&plat| `list_prompt_suggestions` | Pending AI-generated prompt suggestions with source details, expiry and a stale flag. Does not generate new suggestions. | || `accept_prompt_suggestion` | Create a tracked prompt from one pending suggestion using the brand's default engines and plan/location checks. | **yes** || `dismiss_prompt_suggestion` | Dismiss one pending prompt suggestion so it no longer appears in future lists. | **yes** |-| `get_prompt_volumes` | Per-prompt Google and estimated AI search demand and competition for prompts that already have analysis. | |+| `get_prompt_volumes` | Per-prompt Google and estimated AI search demand and competition for prompts that already have analysis, with `measured_demand`: the real signs people ask it (Search Console, Google Trends, People Also Ask, YouTube) and their level, or `null` until any was read. | || `get_prompt_usage` | Tracked-prompt usage against the plan: the brand's active and paused prompts, and the account's active prompts, brands, prompt locations used and location limit. | |### Content opportunitiesdiff --git a/server/Dockerfile b/server/Dockerfileindex eb94a4548..eaf561bf9 100644--- a/server/Dockerfile+++ b/server/Dockerfile@@ -1,4 +1,4 @@-FROM node:24+FROM node:20ARG VERSION=0.1.0LABEL org.opencontainers.image.title="Ansvisor Server"diff --git a/server/README.md b/server/README.mdindex e3df7de76..2cc4028fb 100644--- a/server/README.md+++ b/server/README.md@@ -6,7 +6,7 @@ It is designed to run alongside the `web/` app during local development and can## Prerequisites-- Node.js 24 or newer+- Node.js 20 or newer- npm, or Yarn if you prefer using it for package scripts- A configured Supabase project- At least one AI provider API key for tracking and content generationdiff --git a/server/src/server.js b/server/src/server.jsindex 217947842..d0f2fa759 100644--- a/server/src/server.js+++ b/server/src/server.js@@ -1,5 +1,6 @@import 'dotenv/config';import express from 'express';+import { z } from 'zod';import http from 'http';import cors from 'cors';import helmet from 'helmet';@@ -41,7 +42,7 @@ import webhookContentDraftCallbackRoutes from './routes/webhook-content-draft-caimport { sendImproveActionForKeyUser } from './routes/prompts.js';import { readOpportunityInbox, startAutoAudits, startSiteAuditForBrand } from './routes/audits.js';import { sweepAutoAudits } from './lib/audit/auto-audit-sweep.js';-import { getSiteAuditQuotaStatus } from './lib/plan-guard.js';+import { PlanLimitError, getAiUsage, getSiteAuditQuotaStatus } from './lib/plan-guard.js';import { recountBrandCitations } from './lib/citation-recount.js';import supabaseAdmin from './config/supabase.js';import { getPlan, hasFeature, isCloud, isSubscriptionActive } from './config/plans.js';@@ -529,6 +530,35 @@ app.get('/api/internal/site-audit-quota', async (req, res) => {}});+// --- Internal AI usage endpoint (CRON_SECRET auth, called by web MCP layer) ---+// Read-only: this period's AI usage for the org, as GET /api/billing/ai-usage+// answers a member (getAiUsage), so the MCP `get_ai_usage` tool reads the+// Billing meter's own numbers. The web MCP layer passes its authenticated org+// id. Without an active plan there is no allowance to meter: 402 plan_limit.+app.get('/api/internal/ai-usage', 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' });+ }++ try {+ const raw = req.query.orgId;+ const orgId = z.guid().safeParse(Array.isArray(raw) ? raw[0] : raw);+ if (!orgId.success) {+ return res.status(400).json({ success: false, message: 'orgId must be a UUID' });+ }+ return res.json({ success: true, usage: await getAiUsage(orgId.data) });+ } catch (err) {+ if (err instanceof PlanLimitError) {+ return res+ .status(err.statusCode)+ .json({ success: false, error: 'plan_limit', message: err.message });+ }+ req.log.error({ err }, 'internal AI usage error');+ return res.status(500).json({ success: false, message: err.message });+ }+});+// --- Internal Improve send endpoint (CRON_SECRET auth, called by web MCP layer) ---// The web MCP layer verifies the caller's `ans_` API key org owns the prompt// before reaching here and passes the key's user, so this endpoint trusts thediff --git a/web/src/app/api/mcp/ai-usage/route.test.ts b/web/src/app/api/mcp/ai-usage/route.test.tsnew file mode 100644index 000000000..320e10bda--- /dev/null+++ b/web/src/app/api/mcp/ai-usage/route.test.ts@@ -0,0 +1,76 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * GET /api/mcp/ai-usage and GET /api/mcp/whoami: the REST mirrors of the MCP+ * tools get_ai_usage and get_me.+ */++const { getAiUsageFor, getMeFor } = vi.hoisted(() => ({+ getAiUsageFor: vi.fn(),+ getMeFor: vi.fn(),+}));+vi.mock('@/lib/mcp-auth', () => ({+ authenticateMcpRequest: vi.fn(async () => ({+ userId: 'user-1',+ email: '[email protected]',+ organizationId: 'org-1',+ apiKeyId: 'key-1',+ })),+}));+vi.mock('@/lib/mcp/account', () => ({ getAiUsageFor, getMeFor }));++const aiUsage = await import('./route');+const whoami = await import('../whoami/route');++const get = (route: { GET: (req: Request) => Promise<Response> }, path: string) =>+ route.GET(new Request(`http://localhost/api/mcp/${path}`));++beforeEach(() => {+ getAiUsageFor.mockReset();+ getMeFor.mockReset();+});++describe('GET /api/mcp/ai-usage', () => {+ it("answers the organization's usage", async () => {+ getAiUsageFor.mockResolvedValue({ active_plan: true, percent_used: 12.5, features: [] });+ const res = await get(aiUsage, 'ai-usage');+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({+ usage: { active_plan: true, percent_used: 12.5, features: [] },+ });+ });++ it('answers 404 for a key without an organization, and 500 on a failure', async () => {+ getAiUsageFor.mockResolvedValue(null);+ expect((await get(aiUsage, 'ai-usage')).status).toBe(404);+ getAiUsageFor.mockRejectedValue(new Error('Internal ai-usage endpoint returned 503'));+ const res = await get(aiUsage, 'ai-usage');+ expect(res.status).toBe(500);+ expect(await res.json()).toEqual({ error: 'Internal ai-usage endpoint returned 503' });+ });+});++describe('GET /api/mcp/whoami', () => {+ it('adds the role, the work areas and whether they change menus', async () => {+ getMeFor.mockResolvedValue({+ user_id: 'user-1',+ email: '[email protected]',+ organization_id: 'org-1',+ organization_name: 'Acme',+ role: 'manager',+ work_areas: [{ id: 'content', name: 'Content' }],+ can_manage_menus: true,+ });+ const res = await get(whoami, 'whoami');+ expect(await res.json()).toEqual({+ userId: 'user-1',+ email: '[email protected]',+ organizationId: 'org-1',+ organizationName: 'Acme',+ role: 'manager',+ workAreas: [{ id: 'content', name: 'Content' }],+ canManageMenus: true,+ });+ });+});diff --git a/web/src/app/api/mcp/ai-usage/route.ts b/web/src/app/api/mcp/ai-usage/route.tsnew file mode 100644index 000000000..3de8330d0--- /dev/null+++ b/web/src/app/api/mcp/ai-usage/route.ts@@ -0,0 +1,20 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { getAiUsageFor } from '@/lib/mcp/account';++/** This period's AI usage for the key's organization, as the MCP tool get_ai_usage answers. */+export async function GET(req: Request) {+ const auth = await authenticateMcpRequest(req);+ if (auth instanceof NextResponse) return auth;++ try {+ const usage = await getAiUsageFor(auth);+ if (usage === null) {+ return NextResponse.json({ error: 'Organization not found' }, { status: 404 });+ }+ return NextResponse.json({ usage });+ } catch (err) {+ const message = err instanceof Error ? err.message : 'Failed';+ return NextResponse.json({ error: message }, { status: 500 });+ }+}diff --git a/web/src/app/api/mcp/whoami/route.ts b/web/src/app/api/mcp/whoami/route.tsindex f3fec38f5..c03b8c4b8 100644--- a/web/src/app/api/mcp/whoami/route.ts+++ b/web/src/app/api/mcp/whoami/route.ts@@ -1,13 +1,25 @@import { NextResponse } from 'next/server';import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { getMeFor } from '@/lib/mcp/account';+/** Who the key acts as, with their role and work areas, as the MCP tool get_me answers. */export async function GET(req: Request) {const auth = await authenticateMcpRequest(req);if (auth instanceof NextResponse) return auth;- return NextResponse.json({- userId: auth.userId,- email: auth.email,- organizationId: auth.organizationId,- });+ try {+ const me = await getMeFor(auth);+ return NextResponse.json({+ userId: me.user_id,+ email: me.email,+ organizationId: me.organization_id,+ organizationName: me.organization_name,+ role: me.role,+ workAreas: me.work_areas,+ canManageMenus: me.can_manage_menus,+ });+ } catch (err) {+ const message = err instanceof Error ? err.message : 'Failed';+ return NextResponse.json({ error: message }, { status: 500 });+ }}diff --git a/web/src/lib/mcp/account.test.ts b/web/src/lib/mcp/account.test.tsnew file mode 100644index 000000000..cbee3d92e--- /dev/null+++ b/web/src/lib/mcp/account.test.ts@@ -0,0 +1,220 @@+// @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';++/**+ * get_me: the person a key acts as, with their role, their work areas by name+ * and whether they choose who sees which menu sections. get_ai_usage: the+ * Billing meter's own numbers, from the server, and no allowance without an+ * active plan.+ */++let profile: Record<string, unknown> | null;+let org: Record<string, unknown> | null;+/** A read that fails, by table. */+let failing: string | null = null;++vi.mock('@/lib/supabase/admin', () => ({+ supabaseAdmin: {+ from: (table: string) => ({+ select: () => ({+ eq: () => ({+ maybeSingle: async () =>+ failing === table+ ? { data: null, error: { message: `${table} read failed` } }+ : { data: table === 'profiles' ? profile : org, error: null },+ }),+ }),+ }),+ },+}));++const { getAiUsageFor, getMeFor } = await import('./account');+const { createMcpServer } = await import('./server');++const auth: McpAuthContext = {+ userId: 'user-1',+ email: '[email protected]',+ organizationId: 'org-1',+ apiKeyId: 'key-1',+};++describe('getMeFor', () => {+ beforeEach(() => {+ org = { name: 'Acme' };+ failing = null;+ });++ it('names the role, the work areas and that a manager may change menus', async () => {+ profile = {+ role: 'manager',+ work_areas: ['content', 'leaders', 'gone'],+ can_manage_menus: true,+ };+ expect(await getMeFor(auth)).toEqual({+ user_id: 'user-1',+ email: '[email protected]',+ organization_id: 'org-1',+ organization_name: 'Acme',+ role: 'manager',+ // A work area no longer offered is left out.+ work_areas: [+ { id: 'content', name: 'Content' },+ { id: 'leaders', name: 'Founders & leaders' },+ ],+ can_manage_menus: true,+ });+ });++ it('lets an admin change menus always, an analyst never', async () => {+ profile = { role: 'admin', work_areas: null, can_manage_menus: false };+ expect(await getMeFor(auth)).toMatchObject({ can_manage_menus: true, work_areas: [] });+ profile = { role: 'analyst', work_areas: [], can_manage_menus: true };+ expect(await getMeFor(auth)).toMatchObject({ can_manage_menus: false });+ });++ it('answers without a profile or an organization', async () => {+ profile = null;+ const me = await getMeFor({ ...auth, organizationId: null });+ expect(me).toMatchObject({+ organization_id: null,+ organization_name: null,+ role: null,+ work_areas: [],+ can_manage_menus: false,+ });+ });++ it('fails rather than answer a role it could not read', async () => {+ profile = { role: 'admin', work_areas: [], can_manage_menus: false };+ failing = 'profiles';+ await expect(getMeFor(auth)).rejects.toThrow('profiles read failed');+ failing = 'organizations';+ await expect(getMeFor(auth)).rejects.toThrow('organizations read failed');+ });+});++describe('getAiUsageFor', () => {+ const fetchMock = vi.fn();++ beforeEach(() => {+ fetchMock.mockReset();+ vi.stubGlobal('fetch', fetchMock);+ vi.stubEnv('CRON_SECRET', 'secret');+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ vi.unstubAllEnvs();+ });++ it("reads the Billing meter's numbers from the server, quality checks in the editor's row", async () => {+ fetchMock.mockResolvedValue(+ Response.json({+ success: true,+ usage: {+ plan: 'growth',+ planName: 'Growth',+ trial: false,+ periodStart: '2026-10-01T00:00:00Z',+ periodEnd: '2026-11-01T00:00:00Z',+ unlimited: false,+ percentUsed: 42.5,+ // An older server lists every feature, and the quality checks apart.+ features: [+ { feature: 'improve', percent: 20 },+ { feature: 'content', percent: 10 },+ { feature: 'quality', percent: 2.5 },+ { feature: 'action_center', percent: 10 },+ { feature: 'other', percent: 0 },+ ],+ },+ }),+ );+ expect(await getAiUsageFor(auth)).toEqual({+ active_plan: true,+ plan: 'growth',+ plan_name: 'Growth',+ trial: false,+ period_start: '2026-10-01T00:00:00Z',+ period_end: '2026-11-01T00:00:00Z',+ unlimited: false,+ percent_used: 42.5,+ features: [+ { feature: 'improve', percent: 20 },+ { feature: 'content', percent: 12.5 },+ { feature: 'action_center', percent: 10 },+ ],+ });+ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toMatch(/\/api\/internal\/ai-usage\?orgId=org-1$/);+ expect(init).toMatchObject({ headers: { Authorization: 'Bearer secret' } });+ });++ it('says there is no allowance without an active plan', async () => {+ fetchMock.mockResolvedValue(+ Response.json({ success: false, error: 'plan_limit', message: 'No plan' }, { status: 402 }),+ );+ expect(await getAiUsageFor(auth)).toMatchObject({+ active_plan: false,+ percent_used: null,+ features: [],+ });+ });++ it("passes on the server's failure", async () => {+ fetchMock.mockResolvedValue(Response.json({ message: 'boom' }, { status: 500 }));+ await expect(getAiUsageFor(auth)).rejects.toThrow('boom');+ });++ it('answers unlimited self-hosted, without asking the server', async () => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'false');+ expect(await getAiUsageFor(auth)).toMatchObject({+ active_plan: true,+ plan: 'self_hosted',+ unlimited: true,+ percent_used: null,+ });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('asks nothing without an organization, or without the internal secret', async () => {+ expect(await getAiUsageFor({ ...auth, organizationId: null })).toBeNull();+ vi.stubEnv('CRON_SECRET', '');+ await expect(getAiUsageFor(auth)).rejects.toThrow('CRON_SECRET');+ expect(fetchMock).not.toHaveBeenCalled();+ });+});++describe('the get_me and get_ai_usage tools', () => {+ it('list as read-only tools with a title, and answer as JSON', async () => {+ profile = { role: 'admin', work_areas: ['aeo'], can_manage_menus: false };+ org = { name: 'Acme' };+ failing = null;+ 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();+ for (const [name, title] of [+ ['get_me', 'Who am I'],+ ['get_ai_usage', 'AI usage this period'],+ ]) {+ const tool = tools.find((t) => t.name === name);+ expect(tool?.title, name).toBe(title);+ expect(tool?.annotations, name).toMatchObject({ readOnlyHint: true, openWorldHint: false });+ }++ const result = await client.callTool({ name: 'get_me', arguments: {} });+ expect(JSON.parse((result.content as { text: string }[])[0].text)).toMatchObject({+ role: 'admin',+ work_areas: [{ id: 'aeo', name: 'AEO/GEO & Audit' }],+ can_manage_menus: true,+ });+ });+});diff --git a/web/src/lib/mcp/account.ts b/web/src/lib/mcp/account.tsnew file mode 100644index 000000000..71e57f1c5--- /dev/null+++ b/web/src/lib/mcp/account.ts@@ -0,0 +1,162 @@+import messages from '../../../messages/en.json';+import { supabaseAdmin } from '@/lib/supabase/admin';+import type { McpAuthContext } from '@/lib/mcp-auth';+import { API_BASE_URL } from '@/config/api';+import { isCloud } from '@/config/plans';+import { aiUsageFromApi, type AiUsage, type AiUsageFeature } from '@/lib/billing/ai-usage';+import { canManageMenus, workAreasOf, type WorkAreaId } from '@/lib/menu-access';+import type { UserRole } from '@/types';++/**+ * Who the key acts as and what the workspace has left of its AI allowance,+ * for the MCP tools get_me and get_ai_usage and their REST mirrors+ * (/api/mcp/whoami, /api/mcp/ai-usage).+ */++/** The person a key acts as: their role and what they work on (menu access, 00374). */+export interface McpMe {+ user_id: string;+ email: string | null;+ organization_id: string | null;+ organization_name: string | null;+ role: UserRole | null;+ /** What they work on, from "What do you work on?" (Settings › Account). */+ work_areas: { id: WorkAreaId; name: string }[];+ /** Admin, or a manager an admin let choose who sees which menu sections. */+ can_manage_menus: boolean;+}++/** A work area's name, as Settings › Menu access shows it. */+function workAreaName(id: WorkAreaId): string {+ return messages.settings.menuAccess.areas[id].title;+}++export async function getMeFor(auth: McpAuthContext): Promise<McpMe> {+ const [{ data: profile, error: profileError }, { data: org, error: orgError }] =+ await Promise.all([+ supabaseAdmin+ .from('profiles')+ .select('role, work_areas, can_manage_menus')+ .eq('id', auth.userId)+ .maybeSingle(),+ auth.organizationId+ ? supabaseAdmin+ .from('organizations')+ .select('name')+ .eq('id', auth.organizationId)+ .maybeSingle()+ : Promise.resolve({ data: null, error: null }),+ ]);+ if (profileError) throw new Error(profileError.message);+ if (orgError) throw new Error(orgError.message);+ const role = (profile?.role as UserRole | null | undefined) ?? null;+ return {+ user_id: auth.userId,+ email: auth.email,+ organization_id: auth.organizationId,+ organization_name: (org?.name as string | null | undefined) ?? null,+ role,+ work_areas: workAreasOf((profile?.work_areas as string[] | null | undefined) ?? null).map(+ (id) => ({ id, name: workAreaName(id) }),+ ),+ can_manage_menus: role+ ? canManageMenus({+ role,+ can_manage_menus: (profile?.can_manage_menus as boolean | null | undefined) ?? null,+ })+ : false,+ };+}++/** This period's AI usage, as the Billing page's meter reads it. */+export interface McpAiUsage {+ /** Whether the workspace has an active plan (or free trial) to meter. */+ active_plan: boolean;+ plan: string | null;+ plan_name: string | null;+ /** The free trial's smaller allowance: more comes with paying for the plan. */+ trial: boolean;+ period_start: string | null;+ period_end: string | null;+ /** No allowance to meter (self-hosted, or a plan without one). */+ unlimited: boolean;+ /** Share of the monthly AI allowance used, 0–100 to a tenth; null when unlimited or no plan. */+ percent_used: number | null;+ /** Each feature's share of the allowance, only those that used some. */+ features: { feature: AiUsageFeature; percent: number }[];+}++/** Self-hosted: nothing is metered. */+const SELF_HOSTED: McpAiUsage = {+ active_plan: true,+ plan: 'self_hosted',+ plan_name: null,+ trial: false,+ period_start: null,+ period_end: null,+ unlimited: true,+ percent_used: null,+ features: [],+};++const NO_PLAN: McpAiUsage = {+ active_plan: false,+ plan: null,+ plan_name: null,+ trial: false,+ period_start: null,+ period_end: null,+ unlimited: false,+ percent_used: null,+ features: [],+};++function mcpAiUsage(usage: AiUsage): McpAiUsage {+ return {+ active_plan: true,+ plan: usage.plan,+ plan_name: usage.planName,+ trial: usage.trial === true,+ period_start: usage.periodStart,+ period_end: usage.periodEnd,+ unlimited: usage.unlimited,+ percent_used: usage.percentUsed,+ features: usage.features,+ };+}++/**+ * The org's AI usage this period, from the server's getAiUsage through the+ * CRON_SECRET internal endpoint, so the numbers are the Billing meter's own.+ * A workspace without an active plan has no allowance: active_plan false.+ * Self-hosted meters nothing, so it answers unlimited without asking.+ */+export async function getAiUsageFor(auth: McpAuthContext): Promise<McpAiUsage | null> {+ if (!isCloud()) return SELF_HOSTED;+ if (!auth.organizationId) return null;++ const cronSecret = process.env.CRON_SECRET;+ if (!cronSecret) {+ throw new Error('CRON_SECRET must be configured for MCP AI usage');+ }++ const url = `${API_BASE_URL}/api/internal/ai-usage?orgId=${encodeURIComponent(+ auth.organizationId,+ )}`;+ const res = await fetch(url, {+ method: 'GET',+ headers: { Authorization: `Bearer ${cronSecret}` },+ });+ const body = (await res.json().catch(() => null)) as {+ usage?: AiUsage;+ error?: string;+ message?: string;+ } | null;++ if (!res.ok) {+ if (res.status === 402 && body?.error === 'plan_limit') return NO_PLAN;+ throw new Error(body?.message ?? `Internal ai-usage endpoint returned ${res.status}`);+ }+ if (!body?.usage) throw new Error('Internal ai-usage endpoint returned no usage');+ return mcpAiUsage(aiUsageFromApi(body.usage));+}diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.tsindex f63e9ec54..829c2369d 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -39,6 +39,7 @@ import {} from '@/lib/action-center/task-details';import { locationCode, isValidLocation } from '@/lib/region';import { promptVolumeEstimate, type EstimateConfidence } from '@/lib/volume-estimate';+import { readPromptDemand, type PromptDemand } from './prompt-demand';import { getOrgLocationUsage, locationLimitMessage } from '@/lib/prompt-locations';import {filterPromptSuggestionEngines,@@ -2322,6 +2323,12 @@ export interface PromptVolumeRow {/** Bucketed competition label ("LOW" | "MEDIUM" | "HIGH"), or null. */competition: string | null;fetched_at: string | null;+ /**+ * The prompt's real demand (PROMPT-014): Search Console, Google Trends,+ * People Also Ask and YouTube, with the level they come to. Null until the+ * nightly sweep read any.+ */+ measured_demand: PromptDemand | null;}const PROMPT_VOLUMES_DEFAULT_LIMIT = 100;@@ -2388,6 +2395,10 @@ export async function getPromptVolumesFor(prompts: { text: string } | Array<{ text: string }> | null;}> | null) ?? [];+ const demand = await readPromptDemand(+ params.brandId,+ rows.map((r) => r.prompt_id),+ );const now = new Date();return rows.map((r) => {const prompt = Array.isArray(r.prompts) ? (r.prompts[0] ?? null) : r.prompts;@@ -2417,6 +2428,7 @@ export async function getPromptVolumesFor(competition_index: r.competition_index,competition: r.competition,fetched_at: r.fetched_at,+ measured_demand: demand.get(r.prompt_id) ?? null,};});}diff --git a/web/src/lib/mcp/prompt-demand.test.ts b/web/src/lib/mcp/prompt-demand.test.tsnew file mode 100644index 000000000..d77204e48--- /dev/null+++ b/web/src/lib/mcp/prompt-demand.test.ts@@ -0,0 +1,141 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * A prompt's real demand (PROMPT-014, 00370) as get_prompt_volumes returns+ * it: short, as a list of prompts carries one each (one read_at, the top+ * query alone, People Also Ask's count and first three questions); null for a+ * row the sweep wrote before reading anything; and a failed read never takes+ * the volumes down with it.+ */++const calls: { brandId: unknown; ids: string[] }[] = [];+let failing = false;+vi.mock('@/lib/supabase/admin', () => ({+ supabaseAdmin: {+ from: () => ({+ select: () => ({+ eq: (_brandColumn: string, brandId: unknown) => ({+ in: async (_column: string, ids: string[]) => {+ calls.push({ brandId, ids });+ if (failing) return { data: null, error: { message: 'statement timeout' } };+ return {+ data: ids.map((id) => ({ prompt_id: id, signals: 1, gsc: { impressions: 5 } })),+ error: null,+ };+ },+ }),+ }),+ }),+ },+}));++const { promptDemandOf, readPromptDemand } = await import('./prompt-demand');++describe('promptDemandOf', () => {+ it('reads each signal in short', () => {+ expect(+ promptDemandOf({+ prompt_id: 'p1',+ level: 'medium',+ signals: 4,+ keyword: 'espresso grinder',+ gsc: {+ impressions: 120,+ clicks: 3,+ queries: 2,+ top: { query: 'best espresso grinder', impressions: 90, clicks: 2 },+ at: '2026-10-27',+ },+ trends: { points: [1, 2], trend: 'steady', change: null, at: '2026-10-21' },+ paa: {+ questions: [+ { question: 'Which grinder is best?', url: 'https://a.example/', domain: 'a.example' },+ { question: 'Is a burr grinder worth it?', url: null, domain: null },+ { question: 'How fine for espresso?', url: null, domain: null },+ { question: 'Manual or electric?', url: null, domain: null },+ ],+ at: '2026-10-21',+ },+ youtube: { videos: 18, views: 240000, results: 900, top: null, at: '2026-10-21' },+ updated_at: '2026-10-27',+ }),+ ).toEqual({+ level: 'medium',+ signals_read: 4,+ read_at: '2026-10-27',+ search_console: {+ impressions: 120,+ clicks: 3,+ queries: 2,+ top_query: 'best espresso grinder',+ },+ google_trends: { trend: 'steady', change_percent: null },+ people_also_ask: {+ count: 4,+ questions: [+ 'Which grinder is best?',+ 'Is a burr grinder worth it?',+ 'How fine for espresso?',+ ],+ },+ youtube: { videos: 18, views: 240000 },+ });+ });++ it('leaves a signal never read null, and a level it does not know out', () => {+ const demand = promptDemandOf({+ prompt_id: 'p1',+ level: 'huge',+ signals: 1,+ gsc: null,+ trends: { trend: 'sideways', at: '2026-10-21' },+ });+ expect(demand).toMatchObject({+ level: null,+ signals_read: 1,+ search_console: null,+ google_trends: { trend: null, change_percent: null },+ people_also_ask: null,+ youtube: null,+ });+ });++ it('reads a row the sweep wrote before reading anything as no demand yet', () => {+ // The nightly sweep writes the row when it sets the paid tasks (prompt-demand.js).+ expect(+ promptDemandOf({+ prompt_id: 'p1',+ signals: 0,+ keyword: 'espresso grinder',+ gsc: null,+ trends: null,+ paa: null,+ youtube: null,+ tasks: { posted_at: '2026-10-28', trends: 'task-1', paa: null, youtube: null },+ }),+ ).toBeNull();+ });+});++describe('readPromptDemand', () => {+ beforeEach(() => {+ calls.length = 0;+ failing = false;+ });++ it("reads the brand's prompts a hundred at a time", async () => {+ const ids = Array.from({ length: 250 }, (_, i) => `p${i}`);+ const demand = await readPromptDemand('b1', ids);+ expect(calls.map((call) => call.ids.length)).toEqual([100, 100, 50]);+ expect(calls.every((call) => call.brandId === 'b1')).toBe(true);+ expect(demand.size).toBe(250);+ });++ it('answers none, logged, when the read fails', async () => {+ failing = true;+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ expect((await readPromptDemand('b1', ['p1'])).size).toBe(0);+ expect(error).toHaveBeenCalled();+ error.mockRestore();+ });+});diff --git a/web/src/lib/mcp/prompt-demand.ts b/web/src/lib/mcp/prompt-demand.tsnew file mode 100644index 000000000..e9e6f153b--- /dev/null+++ b/web/src/lib/mcp/prompt-demand.ts@@ -0,0 +1,134 @@+import { supabaseAdmin } from '@/lib/supabase/admin';++/**+ * A prompt's real demand (PROMPT-014, 00370) for get_prompt_volumes, beside+ * its estimated AI volume: the signs people really ask it and the level they+ * come to, as the prompt's Demand card shows them. The server's nightly sweep+ * writes them: Search Console every night, Google Trends, People Also Ask and+ * YouTube about once a week.+ *+ * Kept short, as a list of up to 500 prompts carries one each: a single+ * read_at for the row, the top Search Console query alone, People Also Ask's+ * count and first questions, no weekly Trends points or video lists. The+ * paid signals are read for the prompt's keyword with the most Google+ * searches (its google_volumes' top one), so the keyword isn't repeated.+ */+export interface PromptDemand {+ /** high / medium / low, from the signals read; null until one was. */+ level: 'high' | 'medium' | 'low' | null;+ /** How many of the four signals were read (0–4). */+ signals_read: number;+ /** When the sweep last wrote the row. */+ read_at: string | null;+ /** The brand's matching Search Console queries over the last 28 days. */+ search_console: {+ impressions: number;+ clicks: number;+ queries: number;+ top_query: string | null;+ } | null;+ /** Google Trends for the keyword over 12 months. */+ google_trends: {+ trend: 'rising' | 'steady' | 'falling' | null;+ /** Change from the first weeks to the last, in percent; null without a base. */+ change_percent: number | null;+ } | null;+ /** The People Also Ask questions Google lists for the keyword: how many, and the first few. */+ people_also_ask: { count: number; questions: string[] } | null;+ /** The videos YouTube lists for the keyword, and their views. */+ youtube: { videos: number; views: number } | null;+}++/** People Also Ask questions a row carries. */+export const DEMAND_QUESTIONS_SHOWN = 3;++type Json = Record<string, unknown> | null | undefined;++const num = (value: unknown) => (Number.isFinite(Number(value)) ? Number(value) : 0);+const text = (value: unknown) => (typeof value === 'string' ? value : null);+const object = (value: unknown): Json =>+ value && typeof value === 'object' && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : null;++/**+ * A prompt_demand row as get_prompt_volumes returns it; null for one with+ * nothing read yet (the sweep writes a row when it sets the paid tasks, before+ * any is read).+ */+export function promptDemandOf(row: Record<string, unknown>): PromptDemand | null {+ const gsc = object(row.gsc);+ const trends = object(row.trends);+ const paa = object(row.paa);+ const youtube = object(row.youtube);+ if (num(row.signals) === 0 && !gsc && !trends && !paa && !youtube) return null;+ const level = text(row.level);+ const trend = text(trends?.trend);+ const questions = (Array.isArray(paa?.questions) ? paa.questions : [])+ .map((q) => text(object(q)?.question))+ .filter((q): q is string => q !== null);+ return {+ level: level === 'high' || level === 'medium' || level === 'low' ? level : null,+ signals_read: num(row.signals),+ read_at: text(row.updated_at),+ search_console: gsc+ ? {+ impressions: num(gsc.impressions),+ clicks: num(gsc.clicks),+ queries: num(gsc.queries),+ top_query: text(object(gsc.top)?.query),+ }+ : null,+ google_trends: trends+ ? {+ trend: trend === 'rising' || trend === 'steady' || trend === 'falling' ? trend : null,+ change_percent: trends.change == null ? null : num(trends.change),+ }+ : null,+ people_also_ask: paa+ ? { count: questions.length, questions: questions.slice(0, DEMAND_QUESTIONS_SHOWN) }+ : null,+ youtube: youtube ? { videos: num(youtube.videos), views: num(youtube.views) } : null,+ };+}++/** Prompt ids per `.in()` filter, so the request stays short. */+const DEMAND_CHUNK = 100;++/**+ * The brand's prompts' real demand, by prompt id; a prompt with nothing read+ * has none. A read that fails is logged and leaves every prompt without it:+ * the volumes still answer.+ */+export async function readPromptDemand(+ brandId: string,+ promptIds: string[],+): Promise<Map<string, PromptDemand>> {+ const chunks: string[][] = [];+ for (let i = 0; i < promptIds.length; i += DEMAND_CHUNK) {+ chunks.push(promptIds.slice(i, i + DEMAND_CHUNK));+ }+ const demand = new Map<string, PromptDemand>();+ try {+ const results = await Promise.all(+ chunks.map((ids) =>+ supabaseAdmin+ .from('prompt_demand')+ .select('prompt_id, level, signals, gsc, trends, paa, youtube, updated_at')+ .eq('brand_id', brandId)+ .in('prompt_id', ids),+ ),+ );+ for (const { data, error } of results) {+ if (error) throw new Error(error.message);+ for (const row of (data ?? []) as Record<string, unknown>[]) {+ const read = promptDemandOf(row);+ if (read) demand.set(row.prompt_id as string, read);+ }+ }+ } catch (err) {+ console.error('[mcp] prompt demand read failed; volumes answer without it', err);+ return new Map();+ }+ return demand;+}diff --git a/web/src/lib/mcp/prompt-volumes.test.ts b/web/src/lib/mcp/prompt-volumes.test.tsindex 5b3218434..50ea769ec 100644--- a/web/src/lib/mcp/prompt-volumes.test.ts+++ b/web/src/lib/mcp/prompt-volumes.test.ts@@ -1,18 +1,25 @@-import { describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';import type { McpAuthContext } from '@/lib/mcp-auth';/*** get_prompt_volumes (PROMPT-013): each prompt's estimated AI volume comes* with its likely range, how sure it is and that it is an estimate, worked out- * as the dashboard does.+ * as the dashboard does; and its real demand (PROMPT-014), where it was read.*/let rows: Record<string, unknown>[] = [];+/** prompt_demand's rows (00370). */+let demandRows: Record<string, unknown>[] = [];+let demandFails = false;function builder(table: string) {const chain = {select: () => chain,eq: () => chain,+ in: async (_column: string, ids: string[]) =>+ demandFails+ ? { data: null, error: { message: 'statement timeout' } }+ : { data: demandRows.filter((r) => ids.includes(r.prompt_id as string)), error: null },order: () => chain,limit: async () => ({ data: rows, error: null }),maybeSingle: async () => ({ data: table === 'brands' ? { id: 'b1' } : null, error: null }),@@ -49,6 +56,11 @@ const row = (over: Record<string, unknown>) => ({});describe('getPromptVolumesFor', () => {+ beforeEach(() => {+ demandRows = [];+ demandFails = false;+ });+it('adds the range, confidence and type to each prompt', async () => {rows = [row({}),@@ -83,4 +95,53 @@ describe('getPromptVolumesFor', () => {const [volume] = (await getPromptVolumesFor(auth, { brandId: 'b1' }))!;expect(volume.volume_confidence).toBe('medium');});++ it("adds each prompt's real demand where it was read, null where it wasn't", async () => {+ rows = [row({}), row({ prompt_id: 'p2' })];+ demandRows = [+ {+ prompt_id: 'p1',+ level: 'high',+ signals: 2,+ keyword: 'espresso grinder',+ gsc: {+ impressions: 1800,+ clicks: 40,+ queries: 3,+ top: { query: 'best espresso grinder', impressions: 1200, clicks: 30 },+ at: '2026-10-27T02:00:00Z',+ },+ trends: { points: [10, 20], trend: 'rising', change: 35, at: '2026-10-25T02:00:00Z' },+ paa: null,+ youtube: null,+ updated_at: '2026-10-27T02:00:00Z',+ },+ ];+ const volumes = (await getPromptVolumesFor(auth, { brandId: 'b1' }))!;+ expect(volumes[0].measured_demand).toEqual({+ level: 'high',+ signals_read: 2,+ read_at: '2026-10-27T02:00:00Z',+ search_console: {+ impressions: 1800,+ clicks: 40,+ queries: 3,+ top_query: 'best espresso grinder',+ },+ google_trends: { trend: 'rising', change_percent: 35 },+ people_also_ask: null,+ youtube: null,+ });+ expect(volumes[1].measured_demand).toBeNull();+ });++ it('still answers the volumes when the demand read fails', async () => {+ rows = [row({})];+ demandFails = true;+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ const [volume] = (await getPromptVolumesFor(auth, { brandId: 'b1' }))!;+ expect(volume.est_ai_volume).toBe(540);+ expect(volume.measured_demand).toBeNull();+ error.mockRestore();+ });});diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsindex 6500d555f..a14c7200a 100644--- a/web/src/lib/mcp/server.ts+++ b/web/src/lib/mcp/server.ts@@ -76,6 +76,7 @@ import {} from './mentions';import { MENTION_SENTIMENTS, MENTION_SORTS } from '@/lib/mentions-list';import { gateWriteTools } from './subscription-gate';+import { getAiUsageFor, getMeFor } from './account';/*** Build a fresh MCP server bound to a single authenticated request.@@ -965,7 +966,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {'get_prompt_volumes',{description:- 'Get per-prompt search demand and competition for a brand. Returns one row per analyzed prompt with its keywords, the Google search volume of each keyword, total_google_volume (the Google volume of the prompt: the median of its keyword volumes, not their sum), est_ai_volume (estimated AI search demand: total_google_volume × the AI adoption rate), est_ai_volume_low and est_ai_volume_high (its likely range, from how far the keyword volumes agree), volume_confidence (high / medium / low; one level less once the volumes are over six months old), volume_type (always "estimate": AI engines publish no search volumes, so quote the range rather than a single number), competition_index (0-100), and competition label (LOW / MEDIUM / HIGH). Sorted by est_ai_volume descending. Use this for "which prompts have the most demand?" or "which prompts have the least competition?" prioritization questions. Only returns prompts that already have volume analysis — triggering a new analysis is not available here.',+ 'Get per-prompt search demand and competition for a brand. Returns one row per analyzed prompt with its keywords, the Google search volume of each keyword, total_google_volume (the Google volume of the prompt: the median of its keyword volumes, not their sum), est_ai_volume (estimated AI search demand: total_google_volume × the AI adoption rate), est_ai_volume_low and est_ai_volume_high (its likely range, from how far the keyword volumes agree), volume_confidence (high / medium / low; one level less once the volumes are over six months old), volume_type (always "estimate": AI engines publish no search volumes, so quote the range rather than a single number), competition_index (0-100), competition label (LOW / MEDIUM / HIGH), and measured_demand: the real signs people ask it — search_console (the brand Search Console queries that match it over 28 days: impressions, clicks, top_query), google_trends (12 months: rising / steady / falling and change_percent), people_also_ask (how many questions Google lists for its top keyword, and the first 3), youtube (videos and their views) — the level they come to (high / medium / low) and read_at, or null until any was read. Sorted by est_ai_volume descending. Use this for "which prompts have the most demand?" or "which prompts have the least competition?" prioritization questions. Only returns prompts that already have volume analysis — triggering a new analysis is not available here.',inputSchema: {brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),limit: z@@ -1765,5 +1766,34 @@ export function createMcpServer(auth: McpAuthContext): McpServer {},);+ // ─── The account: who the key acts as, and the AI allowance (B2) ───++ server.registerTool(+ 'get_me',+ {+ title: 'Who am I',+ description:+ "Who this connection acts as: the user's id and email, their organization (id and name), their role (admin, manager, analyst or agency_partner), their work areas (what they work on, from Settings › Account, e.g. Content or Founders & leaders) and whether they can choose who sees which menu sections (can_manage_menus). Use it to tailor answers to the person — lead with what their work areas cover — and before suggesting something only an admin or a manager may do.",+ inputSchema: {},+ annotations: { readOnlyHint: true, openWorldHint: false },+ },+ async () => json(await getMeFor(auth)),+ );++ server.registerTool(+ 'get_ai_usage',+ {+ title: 'AI usage this period',+ description:+ "How much of the workspace's monthly AI allowance is used this period, as the Billing page's meter shows it: percent_used (0–100, to a tenth; the allowance is one budget that Improve suggestions, the Content Editor's AI and quality checks, and the Action Center's task writing all draw on), each feature's share (features: improve, content, action_center, other — only those that used some), the plan, whether it is the free trial's smaller allowance, and when the period started and renews. unlimited is true where nothing is metered (self-hosted); active_plan is false when the workspace has no active plan, so there is no allowance. Dollars are not shown. Use it before suggesting AI-heavy work (many Improve runs or drafts), or when asked how much AI is left.",+ inputSchema: {},+ annotations: { readOnlyHint: true, openWorldHint: false },+ },+ async () => {+ const usage = await getAiUsageFor(auth);+ return usage ? json(usage) : notFound('Organization');+ },+ );+return server;}diff --git a/web/src/lib/mcp/subscription-gate.test.ts b/web/src/lib/mcp/subscription-gate.test.tsindex 92f5c955b..e5da5ea0f 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(36);+ expect(names.filter(isReadTool)).toHaveLength(38);expect(names.filter((name) => !isReadTool(name)).sort()).toEqual(['accept_prompt_suggestion','accept_topic_suggestion',