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): expose the Action Center through the MCP server (#902)
Gökhan Geyik5ca43604019c
diff --git a/docs/guides/mcp-server.mdx b/docs/guides/mcp-server.mdxindex 2fd00c073..e306a1ecb 100644--- a/docs/guides/mcp-server.mdx+++ b/docs/guides/mcp-server.mdx@@ -57,6 +57,11 @@ instead.| `get_visibility_summary` | Aggregate visibility score, mentions, citations, top competitors for a brand over an optional date range / model / region. || `list_topics` | List the topics on a brand with a prompt count per topic. Use for coverage audits (empty / over-concentrated topics). || `list_prompts` | List the prompts tracked on a brand, optionally filtered by topic, active status, or capped via `limit`. Returns the prompt text, topic, platforms, models, regions, and active flag. |+| `list_actions` | List a brand's Action Center actions with category, kind, impact, status, outcome, assignee, due date and task progress. Filter by status or category. |+| `get_action` | One action in full: payload, triggering signals, task list (with each task's `mode` and `permission`) and event trail. |+| `list_signals` | Detected signals for a brand with their previous, current and change values. Filter by status or kind. |+| `list_action_history` | Closed actions with their outcome and the before/after values the validation sweep measured. |+| `update_task_status` | Mark a task in_progress, completed, skipped (with a reason) or failed. Records progress; it never carries the task out. |More tools land regularly — check the [project roadmap](https://github.com/ansvisor/ansvisor#whats-next).diff --git a/web/src/app/api/mcp/action-history/route.ts b/web/src/app/api/mcp/action-history/route.tsnew file mode 100644index 000000000..fc1c5391e--- /dev/null+++ b/web/src/app/api/mcp/action-history/route.ts@@ -0,0 +1,32 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { listActionHistoryFor } from '@/lib/mcp/data';++/** GET /api/mcp/action-history — REST mirror of the `list_action_history` 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 = url.searchParams.get('brand_id');+ if (!brandId) {+ return NextResponse.json({ error: 'brand_id is required' }, { status: 400 });+ }++ const limitRaw = url.searchParams.get('limit');+ const limit = limitRaw ? Number.parseInt(limitRaw, 10) : undefined;++ try {+ const history = await listActionHistoryFor(auth, {+ brandId,+ limit: Number.isFinite(limit) ? limit : undefined,+ });+ if (history === null) {+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });+ }+ return NextResponse.json({ actions: history });+ } 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/action-tasks/[id]/status/route.ts b/web/src/app/api/mcp/action-tasks/[id]/status/route.tsnew file mode 100644index 000000000..492bc2363--- /dev/null+++ b/web/src/app/api/mcp/action-tasks/[id]/status/route.ts@@ -0,0 +1,54 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { MCP_TASK_STATUSES, updateTaskStatusFor, type McpTaskStatus } from '@/lib/mcp/data';++/**+ * PATCH /api/mcp/action-tasks/[id]/status+ *+ * REST mirror of the `update_task_status` MCP tool — same data-layer function,+ * same ownership check. Body: `{ "status": "skipped", "skip_reason": "…" }`+ * (status one of in_progress | completed | skipped | failed; skip_reason+ * required for skipped).+ */+export async function PATCH(req: Request, { params }: { params: Promise<{ id: string }> }) {+ const auth = await authenticateMcpRequest(req);+ if (auth instanceof NextResponse) return auth;++ const { id } = await params;+ if (!id) {+ return NextResponse.json({ error: 'id is required' }, { status: 400 });+ }++ let body: { status?: unknown; skip_reason?: unknown };+ try {+ body = (await req.json()) as { status?: unknown; skip_reason?: unknown };+ } catch {+ return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });+ }++ const status = body.status;+ if (typeof status !== 'string' || !(MCP_TASK_STATUSES as readonly string[]).includes(status)) {+ return NextResponse.json(+ { error: `status is required and must be one of: ${MCP_TASK_STATUSES.join(', ')}` },+ { status: 400 },+ );+ }+ const skipReason = typeof body.skip_reason === 'string' ? body.skip_reason : undefined;+ if (status === 'skipped' && !skipReason?.trim()) {+ return NextResponse.json(+ { error: 'skip_reason is required when status is skipped' },+ { status: 400 },+ );+ }++ try {+ const updated = await updateTaskStatusFor(auth, id, status as McpTaskStatus, skipReason);+ if (!updated) {+ return NextResponse.json({ error: 'Task not found' }, { status: 404 });+ }+ return NextResponse.json(updated);+ } 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/actions/[id]/route.ts b/web/src/app/api/mcp/actions/[id]/route.tsnew file mode 100644index 000000000..ae2d4fc72--- /dev/null+++ b/web/src/app/api/mcp/actions/[id]/route.ts@@ -0,0 +1,25 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { getActionFor } from '@/lib/mcp/data';++/** GET /api/mcp/actions/[id] — REST mirror of the `get_action` MCP tool. */+export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {+ const auth = await authenticateMcpRequest(req);+ if (auth instanceof NextResponse) return auth;++ const { id } = await params;+ if (!id) {+ return NextResponse.json({ error: 'id is required' }, { status: 400 });+ }++ try {+ const action = await getActionFor(auth, id);+ if (!action) {+ return NextResponse.json({ error: 'Action not found' }, { status: 404 });+ }+ return NextResponse.json(action);+ } 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/actions/route.ts b/web/src/app/api/mcp/actions/route.tsnew file mode 100644index 000000000..90a107bac--- /dev/null+++ b/web/src/app/api/mcp/actions/route.ts@@ -0,0 +1,39 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { listActionsFor } from '@/lib/mcp/data';++const STATUSES = ['new', 'in_progress', 'on_hold', 'completed', 'dismissed'];+const CATEGORIES = ['growth', 'protect', 'recover', 'fix', 'compete'];++/** GET /api/mcp/actions — REST mirror of the `list_actions` 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 = url.searchParams.get('brand_id');+ if (!brandId) {+ return NextResponse.json({ error: 'brand_id is required' }, { status: 400 });+ }++ const statusRaw = url.searchParams.get('status');+ const categoryRaw = url.searchParams.get('category');+ const limitRaw = url.searchParams.get('limit');+ const limit = limitRaw ? Number.parseInt(limitRaw, 10) : undefined;++ try {+ const actions = await listActionsFor(auth, {+ brandId,+ status: statusRaw && STATUSES.includes(statusRaw) ? statusRaw : undefined,+ category: categoryRaw && CATEGORIES.includes(categoryRaw) ? categoryRaw : undefined,+ limit: Number.isFinite(limit) ? limit : undefined,+ });+ if (actions === null) {+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });+ }+ return NextResponse.json({ actions });+ } 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/signals/route.ts b/web/src/app/api/mcp/signals/route.tsnew file mode 100644index 000000000..735dffb9a--- /dev/null+++ b/web/src/app/api/mcp/signals/route.ts@@ -0,0 +1,38 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { listSignalsFor } from '@/lib/mcp/data';++const STATUSES = ['new', 'acknowledged', 'resolved', 'dismissed'];++/** GET /api/mcp/signals — REST mirror of the `list_signals` 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 = url.searchParams.get('brand_id');+ if (!brandId) {+ return NextResponse.json({ error: 'brand_id is required' }, { status: 400 });+ }++ const statusRaw = url.searchParams.get('status');+ const kind = url.searchParams.get('kind') || undefined;+ const limitRaw = url.searchParams.get('limit');+ const limit = limitRaw ? Number.parseInt(limitRaw, 10) : undefined;++ try {+ const signals = await listSignalsFor(auth, {+ brandId,+ status: statusRaw && STATUSES.includes(statusRaw) ? statusRaw : undefined,+ kind,+ limit: Number.isFinite(limit) ? limit : undefined,+ });+ if (signals === null) {+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });+ }+ return NextResponse.json({ signals });+ } catch (err) {+ const message = err instanceof Error ? err.message : 'Failed';+ return NextResponse.json({ error: message }, { status: 500 });+ }+}diff --git a/web/src/lib/mcp/action-center.test.ts b/web/src/lib/mcp/action-center.test.tsnew file mode 100644index 000000000..28ae43317--- /dev/null+++ b/web/src/lib/mcp/action-center.test.ts@@ -0,0 +1,122 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { McpAuthContext } from '@/lib/mcp-auth';++/**+ * update_task_status is the only Action Center write exposed over MCP. These+ * pin the rules it shares with the dashboard: nothing is written for a task+ * outside the caller's org, a skip must say why, and the change lands in the+ * action's event trail under the API key's user.+ */++type Op = { table: string; op: 'select' | 'update' | 'insert'; payload?: unknown };++let ops: Op[] = [];+let taskOwned = true;++function builder(table: string) {+ let current: Op = { table, op: 'select' };+ const chain = {+ select: () => {+ if (current.op === 'select') ops.push(current);+ return chain;+ },+ update: (payload: unknown) => {+ current = { table, op: 'update', payload };+ ops.push(current);+ return chain;+ },+ insert: async (payload: unknown) => {+ ops.push({ table, op: 'insert', payload });+ return { error: null };+ },+ eq: () => chain,+ maybeSingle: async () => ({+ data: taskOwned ? { id: 'task-1', action_id: 'action-1' } : null,+ error: null,+ }),+ single: async () => ({+ data: {+ id: 'task-1',+ action_id: 'action-1',+ status: (current.payload as { status: string }).status,+ skip_reason: (current.payload as { skip_reason: string | null }).skip_reason,+ updated_at: '2026-10-04T00:00:00.000Z',+ },+ error: null,+ }),+ then: (resolve: (v: { error: null }) => void) => resolve({ error: null }),+ };+ return chain;+}++vi.mock('@/lib/supabase/admin', () => ({+ supabaseAdmin: { from: (table: string) => builder(table) },+}));++const { updateTaskStatusFor } = await import('./data');++const auth: McpAuthContext = {+ userId: 'user-1',+ email: null,+ organizationId: 'org-1',+ apiKeyId: 'key-1',+};++const writes = () => ops.filter((o) => o.op !== 'select');++describe('updateTaskStatusFor', () => {+ beforeEach(() => {+ ops = [];+ taskOwned = true;+ });++ it('returns null and writes nothing for a task outside the caller org', async () => {+ taskOwned = false;+ expect(await updateTaskStatusFor(auth, 'task-1', 'completed')).toBeNull();+ expect(writes()).toEqual([]);+ });++ it('refuses a skip without a reason before touching the database', async () => {+ await expect(updateTaskStatusFor(auth, 'task-1', 'skipped', ' ')).rejects.toThrow(+ /skip_reason/,+ );+ expect(ops).toEqual([]);+ });++ it('updates the task and logs the change under the key user', async () => {+ const result = await updateTaskStatusFor(auth, 'task-1', 'skipped', ' Already covered ');++ expect(result).toMatchObject({+ id: 'task-1',+ status: 'skipped',+ skip_reason: 'Already covered',+ });+ expect(writes()).toEqual([+ {+ table: 'action_tasks',+ op: 'update',+ payload: expect.objectContaining({ status: 'skipped', skip_reason: 'Already covered' }),+ },+ {+ table: 'action_events',+ op: 'insert',+ payload: {+ action_id: 'action-1',+ event: 'task_status',+ data: { taskId: 'task-1', to: 'skipped', reason: 'Already covered' },+ actor_id: 'user-1',+ },+ },+ {+ table: 'actions',+ op: 'update',+ payload: expect.objectContaining({ updated_at: expect.any(String) }),+ },+ ]);+ });++ it('clears the skip reason for any other status', async () => {+ await updateTaskStatusFor(auth, 'task-1', 'completed', 'ignored');+ expect(writes()[0].payload).toMatchObject({ status: 'completed', skip_reason: null });+ });+});diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.tsindex b1e8ab979..d49771926 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -2431,3 +2431,395 @@ export async function getPromptPerformanceFor(prompts,};}++// ── Action Center ────────────────────────────────────────────────────────────+//+// The engine's output: detected signals, the actions consolidated from them,+// each action's task plan and, once closed, its measured result. Read with the+// same field names as `lib/actions/action-center.ts`, but through the API-key+// context rather than the signed-in user. `kind` stays an opaque string: the+// server's definition registry grows on its own release cycle.++/** Task statuses an MCP client may set. Approval and its states stay with the+ * dashboard, and nothing here lets an agent execute a task — only report on it. */+export const MCP_TASK_STATUSES = ['in_progress', 'completed', 'skipped', 'failed'] as const;+export type McpTaskStatus = (typeof MCP_TASK_STATUSES)[number];++/** Skipped and failed tasks are not outstanding work, so they leave the+ * progress denominator — same rule as the dashboard. */+const UNCOUNTED_TASK_STATUSES = ['skipped', 'failed'];++const MCP_SIGNAL_COLUMNS =+ 'id, category, kind, impact, status, source, detected_at, last_detected_at, resolved_at, previous_value, current_value, change_value, payload, kpi_keys, action_id';++async function brandInOrg(auth: McpAuthContext, brandId: string): Promise<boolean> {+ if (!auth.organizationId) return false;+ const { data } = await supabaseAdmin+ .from('brands')+ .select('id')+ .eq('id', brandId)+ .eq('organization_id', auth.organizationId)+ .maybeSingle();+ return Boolean(data);+}++async function assigneeNames(ids: (string | null)[]): Promise<Map<string, string | null>> {+ const unique = [...new Set(ids.filter(Boolean))] as string[];+ if (unique.length === 0) return new Map();+ const { data, error } = await supabaseAdmin+ .from('profiles')+ .select('id, full_name')+ .in('id', unique);+ if (error) throw new Error(error.message);+ return new Map((data ?? []).map((p) => [p.id as string, (p.full_name as string | null) ?? null]));+}++export interface ActionListRow {+ id: string;+ action_no: number;+ category: string;+ kind: string;+ impact: string;+ status: string;+ outcome: string | null;+ assignee: { id: string; full_name: string | null } | null;+ due_date: string | null;+ task_progress: { completed: number; total: number };+ created_at: string;+ updated_at: string;+}++export interface ListActionsParams {+ brandId: string;+ status?: string;+ category?: string;+ limit?: number;+}++export async function listActionsFor(+ auth: McpAuthContext,+ params: ListActionsParams,+): Promise<ActionListRow[] | null> {+ if (!(await brandInOrg(auth, params.brandId))) return null;++ const limit = Math.min(Math.max(params.limit ?? 50, 1), 200);+ let query = supabaseAdmin+ .from('actions')+ .select(+ 'id, action_no, category, kind, impact, status, outcome, assignee_id, due_date, created_at, updated_at',+ )+ .eq('brand_id', params.brandId)+ .order('updated_at', { ascending: false })+ .limit(limit);+ if (params.status) query = query.eq('status', params.status);+ if (params.category) query = query.eq('category', params.category);++ const { data, error } = await query;+ if (error) throw new Error(error.message);+ const rows = data ?? [];+ if (rows.length === 0) return [];++ const { data: tasks, error: taskError } = await supabaseAdmin+ .from('action_tasks')+ .select('action_id, status')+ .in(+ 'action_id',+ rows.map((r) => r.id),+ );+ if (taskError) throw new Error(taskError.message);++ const progress = new Map<string, { completed: number; total: number }>();+ for (const task of tasks ?? []) {+ if (UNCOUNTED_TASK_STATUSES.includes(task.status)) continue;+ const acc = progress.get(task.action_id) ?? { completed: 0, total: 0 };+ acc.total += 1;+ if (task.status === 'completed') acc.completed += 1;+ progress.set(task.action_id, acc);+ }+ const names = await assigneeNames(rows.map((r) => r.assignee_id));++ return rows.map((r) => ({+ id: r.id,+ action_no: Number(r.action_no),+ category: r.category,+ kind: r.kind,+ impact: r.impact,+ status: r.status,+ outcome: r.outcome ?? null,+ assignee: r.assignee_id+ ? { id: r.assignee_id, full_name: names.get(r.assignee_id) ?? null }+ : null,+ due_date: r.due_date ?? null,+ task_progress: progress.get(r.id) ?? { completed: 0, total: 0 },+ created_at: r.created_at,+ updated_at: r.updated_at,+ }));+}++export interface ActionDetailForMcp {+ id: string;+ action_no: number;+ brand_id: string;+ category: string;+ kind: string;+ impact: string;+ status: string;+ outcome: string | null;+ payload: Record<string, unknown>;+ kpi_keys: string[];+ assignee: { id: string; full_name: string | null } | null;+ due_date: string | null;+ created_at: string;+ updated_at: string;+ completed_at: string | null;+ tasks: Array<{+ id: string;+ position: number;+ task_key: string | null;+ title: string | null;+ title_params: Record<string, unknown>;+ status: string;+ skip_reason: string | null;+ mode: string | null;+ permission: string | null;+ depends_on: string[];+ }>;+ signals: Record<string, unknown>[];+ events: Array<{ event: string; data: Record<string, unknown>; created_at: string }>;+}++export async function getActionFor(+ auth: McpAuthContext,+ actionId: string,+): Promise<ActionDetailForMcp | null> {+ if (!auth.organizationId) return null;++ const { data: action, error } = await supabaseAdmin+ .from('actions')+ .select(+ 'id, action_no, brand_id, category, kind, impact, status, outcome, payload, kpi_keys, assignee_id, due_date, created_at, updated_at, completed_at, brands!inner(organization_id)',+ )+ .eq('id', actionId)+ .eq('brands.organization_id', auth.organizationId)+ .maybeSingle();+ if (error) throw new Error(error.message);+ if (!action) return null;++ const [tasksRes, signalsRes, eventsRes, names] = await Promise.all([+ supabaseAdmin+ .from('action_tasks')+ .select(+ 'id, position, task_key, title, title_params, status, skip_reason, mode, permission, depends_on',+ )+ .eq('action_id', actionId)+ .order('position'),+ supabaseAdmin+ .from('signals')+ .select(MCP_SIGNAL_COLUMNS)+ .eq('brand_id', action.brand_id)+ .eq('action_id', actionId)+ .order('detected_at', { ascending: false }),+ supabaseAdmin+ .from('action_events')+ .select('event, data, created_at')+ .eq('action_id', actionId)+ .order('created_at'),+ assigneeNames([action.assignee_id]),+ ]);+ if (tasksRes.error) throw new Error(tasksRes.error.message);+ if (signalsRes.error) throw new Error(signalsRes.error.message);+ if (eventsRes.error) throw new Error(eventsRes.error.message);++ return {+ id: action.id,+ action_no: Number(action.action_no),+ brand_id: action.brand_id,+ category: action.category,+ kind: action.kind,+ impact: action.impact,+ status: action.status,+ outcome: action.outcome ?? null,+ payload: (action.payload ?? {}) as Record<string, unknown>,+ kpi_keys: action.kpi_keys ?? [],+ assignee: action.assignee_id+ ? { id: action.assignee_id, full_name: names.get(action.assignee_id) ?? null }+ : null,+ due_date: action.due_date ?? null,+ created_at: action.created_at,+ updated_at: action.updated_at,+ completed_at: action.completed_at ?? null,+ tasks: (tasksRes.data ?? []).map((t) => ({+ id: t.id,+ position: t.position,+ task_key: t.task_key ?? null,+ title: t.title ?? null,+ title_params: (t.title_params ?? {}) as Record<string, unknown>,+ status: t.status,+ skip_reason: t.skip_reason ?? null,+ mode: t.mode ?? null,+ permission: t.permission ?? null,+ depends_on: (t.depends_on ?? []) as string[],+ })),+ signals: (signalsRes.data ?? []) as Record<string, unknown>[],+ events: (eventsRes.data ?? []).map((e) => ({+ event: e.event,+ data: (e.data ?? {}) as Record<string, unknown>,+ created_at: e.created_at,+ })),+ };+}++export interface ListSignalsParams {+ brandId: string;+ status?: string;+ kind?: string;+ limit?: number;+}++export async function listSignalsFor(+ auth: McpAuthContext,+ params: ListSignalsParams,+): Promise<Record<string, unknown>[] | null> {+ if (!(await brandInOrg(auth, params.brandId))) return null;++ const limit = Math.min(Math.max(params.limit ?? 50, 1), 200);+ let query = supabaseAdmin+ .from('signals')+ .select(MCP_SIGNAL_COLUMNS)+ .eq('brand_id', params.brandId)+ .order('detected_at', { ascending: false })+ .limit(limit);+ if (params.status) query = query.eq('status', params.status);+ if (params.kind) query = query.eq('kind', params.kind);++ const { data, error } = await query;+ if (error) throw new Error(error.message);+ return (data ?? []) as Record<string, unknown>[];+}++export interface ActionHistoryRow {+ id: string;+ action_no: number;+ category: string;+ kind: string;+ impact: string;+ status: string;+ outcome: string | null;+ created_at: string;+ completed_at: string | null;+ /** Before/after pairs the validation sweep measured; empty until it runs. */+ results: Array<{ metric: string; unit: string; before: number; after: number }>;+}++interface ValidationMetric {+ metric: string;+ unit: string;+ before: number | null;+ after: number | null;+}++export async function listActionHistoryFor(+ auth: McpAuthContext,+ params: { brandId: string; limit?: number },+): Promise<ActionHistoryRow[] | null> {+ if (!(await brandInOrg(auth, params.brandId))) return null;++ const limit = Math.min(Math.max(params.limit ?? 50, 1), 200);+ const { data, error } = await supabaseAdmin+ .from('actions')+ .select(+ 'id, action_no, category, kind, impact, status, outcome, validation, created_at, completed_at',+ )+ .eq('brand_id', params.brandId)+ .in('status', ['completed', 'dismissed'])+ .order('completed_at', { ascending: false, nullsFirst: false })+ .limit(limit);+ if (error) throw new Error(error.message);++ return (data ?? []).map((r) => {+ const metrics = (r.validation as { metrics?: ValidationMetric[] } | null)?.metrics ?? [];+ return {+ id: r.id,+ action_no: Number(r.action_no),+ category: r.category,+ kind: r.kind,+ impact: r.impact,+ status: r.status,+ outcome: r.outcome ?? null,+ created_at: r.created_at,+ completed_at: r.completed_at ?? null,+ // A metric missing either half was not measured; dropped, as on the dashboard.+ results: metrics+ .filter((m) => m.before != null && m.after != null)+ .map((m) => ({+ metric: m.metric,+ unit: m.unit,+ before: m.before as number,+ after: m.after as number,+ })),+ };+ });+}++export interface UpdatedTaskStatus {+ id: string;+ action_id: string;+ status: McpTaskStatus;+ skip_reason: string | null;+ updated_at: string;+}++/**+ * Move one task of an action — the MCP counterpart of the drawer's task menu.+ *+ * Ownership first: a task outside the caller's org returns null before any+ * write. Then the same rules and trail as the dashboard: a skip must say why,+ * the change is logged as a `task_status` event under the key's user, and the+ * action's updated stamp moves.+ */+export async function updateTaskStatusFor(+ auth: McpAuthContext,+ taskId: string,+ status: McpTaskStatus,+ skipReason?: string,+): Promise<UpdatedTaskStatus | null> {+ if (!auth.organizationId) return null;++ const reason = status === 'skipped' ? (skipReason ?? '').trim().slice(0, 200) : null;+ if (status === 'skipped' && !reason) throw new Error('A skipped task needs a skip_reason');++ const { data: owned } = await supabaseAdmin+ .from('action_tasks')+ .select('id, action_id, actions!inner(brand_id, brands!inner(organization_id))')+ .eq('id', taskId)+ .eq('actions.brands.organization_id', auth.organizationId)+ .maybeSingle();+ if (!owned) return null;++ const updatedAt = new Date().toISOString();+ const { data, error } = await supabaseAdmin+ .from('action_tasks')+ .update({ status, skip_reason: reason, updated_at: updatedAt })+ .eq('id', taskId)+ .select('id, action_id, status, skip_reason, updated_at')+ .single();+ if (error) throw new Error(error.message);++ // Best-effort, as on the dashboard: a missing trail entry must not fail the+ // change it records.+ await supabaseAdmin.from('action_events').insert({+ action_id: owned.action_id,+ event: 'task_status',+ data: { taskId, to: status, ...(reason ? { reason } : {}) },+ actor_id: auth.userId,+ });+ await supabaseAdmin.from('actions').update({ updated_at: updatedAt }).eq('id', owned.action_id);++ return {+ id: data.id,+ action_id: data.action_id,+ status: data.status as McpTaskStatus,+ skip_reason: data.skip_reason ?? null,+ updated_at: data.updated_at ?? updatedAt,+ };+}diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsindex 85af714e1..a53910d62 100644--- a/web/src/lib/mcp/server.ts+++ b/web/src/lib/mcp/server.ts@@ -27,6 +27,12 @@ import {getSiteAuditFor,listSiteAuditsFor,getSiteAuditQuotaFor,+ MCP_TASK_STATUSES,+ getActionFor,+ listActionHistoryFor,+ listActionsFor,+ listSignalsFor,+ updateTaskStatusFor,} from './data';/**@@ -843,5 +849,184 @@ export function createMcpServer(auth: McpAuthContext): McpServer {},);+ server.registerTool(+ 'list_actions',+ {+ description:+ 'List the Action Center actions for a brand: what the product thinks should be done about its AI visibility. Each action was consolidated from one or more detected signals and carries a task plan. Returns category, kind, impact, status, outcome, assignee, due date and task progress, most recently updated first. `kind` is an opaque definition id (e.g. "close_competitor_gap"); the action payload with the specifics is on get_action. Use this to see open work ("what should we do next?") or to check what is in progress.',+ inputSchema: {+ brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),+ status: z+ .enum(['new', 'in_progress', 'on_hold', 'completed', 'dismissed'])+ .optional()+ .describe('Filter by action status.'),+ category: z+ .enum(['growth', 'protect', 'recover', 'fix', 'compete'])+ .optional()+ .describe('Filter by action category.'),+ limit: z+ .number()+ .int()+ .min(1)+ .max(200)+ .optional()+ .describe('Row cap limit (default 50, max 200).'),+ },+ },+ async (args) => {+ const actions = await listActionsFor(auth, {+ brandId: args.brand_id,+ status: args.status,+ category: args.category,+ limit: args.limit,+ });+ if (actions === null) {+ return {+ content: [{ type: 'text', text: 'Brand not found' }],+ isError: true,+ };+ }+ return {+ content: [{ type: 'text', text: JSON.stringify(actions, null, 2) }],+ };+ },+ );++ server.registerTool(+ 'get_action',+ {+ description:+ 'Get one Action Center action in full: its payload (the prompts, pages, competitors or numbers it is about), the signals that triggered it, its task list and its event trail. Each task carries `mode` (who carries it out: system, agent, human or human_or_agent) and `permission` (read, write or execute). Read both before proposing to act on a task — anything beyond read needs a human to approve it in the dashboard. A task is described by `title` when someone wrote one, otherwise by `task_key` with `title_params`.',+ inputSchema: {+ action_id: relaxedUuid.describe('Action UUID, from list_actions or list_action_history.'),+ },+ },+ async (args) => {+ const action = await getActionFor(auth, args.action_id);+ if (!action) {+ return {+ content: [{ type: 'text', text: 'Action not found' }],+ isError: true,+ };+ }+ return {+ content: [{ type: 'text', text: JSON.stringify(action, null, 2) }],+ };+ },+ );++ server.registerTool(+ 'list_signals',+ {+ description:+ 'List the signals the Action Center detected for a brand: measured changes such as a visibility drop, a competitor gaining citations or a page losing AI traffic. Each signal carries previous_value, current_value and change_value, its payload, and the action_id it was consolidated into (null when no action covers it yet). Newest first. Use this to explain why an action exists or what has changed recently.',+ inputSchema: {+ brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),+ status: z+ .enum(['new', 'acknowledged', 'resolved', 'dismissed'])+ .optional()+ .describe('Filter by signal status.'),+ kind: z+ .string()+ .optional()+ .describe('Filter by signal kind, an opaque detector id as returned in earlier rows.'),+ limit: z+ .number()+ .int()+ .min(1)+ .max(200)+ .optional()+ .describe('Row cap limit (default 50, max 200).'),+ },+ },+ async (args) => {+ const signals = await listSignalsFor(auth, {+ brandId: args.brand_id,+ status: args.status,+ kind: args.kind,+ limit: args.limit,+ });+ if (signals === null) {+ return {+ content: [{ type: 'text', text: 'Brand not found' }],+ isError: true,+ };+ }+ return {+ content: [{ type: 'text', text: JSON.stringify(signals, null, 2) }],+ };+ },+ );++ server.registerTool(+ 'list_action_history',+ {+ description:+ 'List closed Action Center actions (completed or dismissed) for a brand with their measured result, most recently closed first. `outcome` is the verdict (improved, no_meaningful_change, declined, not_measurable, or pending_measurement while the after-window is still open) and `results` holds the before/after values the validation sweep measured. Use this to answer "did what we did last month work?".',+ inputSchema: {+ brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),+ limit: z+ .number()+ .int()+ .min(1)+ .max(200)+ .optional()+ .describe('Row cap limit (default 50, max 200).'),+ },+ },+ async (args) => {+ const history = await listActionHistoryFor(auth, {+ brandId: args.brand_id,+ limit: args.limit,+ });+ if (history === null) {+ return {+ content: [{ type: 'text', text: 'Brand not found' }],+ isError: true,+ };+ }+ return {+ content: [{ type: 'text', text: JSON.stringify(history, null, 2) }],+ };+ },+ );++ server.registerTool(+ 'update_task_status',+ {+ description:+ "Record progress on one task of an Action Center action: in_progress, completed, skipped (skip_reason required) or failed. This reports work a person has done or decided; it does not carry the task out. It is a write logged under the API key's user — only fire on explicit user intent for a specific task, never as part of an exploratory query.",+ inputSchema: {+ task_id: relaxedUuid.describe('Task UUID, from get_action.'),+ status: z+ .enum(MCP_TASK_STATUSES)+ .describe('New task status. One of: in_progress, completed, skipped, failed.'),+ skip_reason: z+ .string()+ .max(200)+ .optional()+ .describe('Why the task was skipped. Required when status is skipped.'),+ },+ },+ async (args) => {+ if (args.status === 'skipped' && !args.skip_reason?.trim()) {+ return {+ content: [{ type: 'text', text: 'skip_reason is required when status is skipped' }],+ isError: true,+ };+ }+ const updated = await updateTaskStatusFor(auth, args.task_id, args.status, args.skip_reason);+ if (!updated) {+ return {+ content: [{ type: 'text', text: 'Task not found' }],+ isError: true,+ };+ }+ return {+ content: [{ type: 'text', text: JSON.stringify(updated, null, 2) }],+ };+ },+ );+return server;}