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.

fix(mcp): check the key's role before adding prompts or topics and dismissing (#1762)

Cihanaf343331bd5b
diff --git a/docs/guides/mcp-server.mdx b/docs/guides/mcp-server.mdx
index c9739f52a..b9d899fb5 100644
--- a/docs/guides/mcp-server.mdx
+++ b/docs/guides/mcp-server.mdx
@@ -223,7 +223,8 @@ instead.
The MCP server exposes **55 tools**. Descriptions below match
[`web/src/lib/mcp/server.ts`](https://github.com/ansvisor/ansvisor/blob/main/web/src/lib/mcp/server.ts).
Tools that change data are marked **writes** — only call them on explicit user
-intent, not during exploratory queries.
+intent, not during exploratory queries. A write that needs a particular role
+names it in brackets; see [Roles](#roles).
### Brands
@@ -270,7 +271,7 @@ The Mentions & Sentiment page's figures, under the page's filters: `date_from` /
| `get_mention` | One response in full: text, citations, competitors named, sentiment and its latest correction. | |
| `get_mention_competitors` | How often AI names each competitor in the brand's responses, and how often in the same response as the brand. | |
| `get_mentions_perception` | What AI associates with the brand: its terms, the attributes that set it apart from its top competitors, co-mentions and the biggest gap. | |
-| `override_mention_sentiment` | "Sentiment is wrong": correct one response's sentiment, with an optional note. The key's user must be an admin or manager. | **yes** |
+| `override_mention_sentiment` | "Sentiment is wrong": correct one response's sentiment, with an optional note. The key's user must be an admin or manager. | **yes** (admin, manager) |
The same reads are available over REST with the same `ans_` key: `GET /api/mcp/mentions/summary`, `/api/mcp/mentions`, `/api/mcp/mentions/<id>`, `/api/mcp/mentions/competitors` and `/api/mcp/mentions/perception`, with the filters as query parameters. A correction is `POST /api/mcp/mentions/<id>/sentiment-override` with `{ "sentiment": "negative", "note": "…" }`.
@@ -286,11 +287,11 @@ curl "https://app.ansvisor.com/api/mcp/mentions/summary?brand_id=<brand_id>&plat
| `list_topics` | Topics on a brand with prompt counts — for coverage audits before drilling into prompts. | |
| `list_prompts` | Tracked prompts with text, topic, platforms, models, regions, and active flag; filter by topic or active/inactive (`is_active`). | |
| `list_topic_suggestions` | Pending AI-generated topic suggestions awaiting accept or dismiss. | |
-| `accept_topic_suggestion` | Accept one pending suggestion: creates a topic and marks the suggestion added. | **yes** |
-| `dismiss_topic_suggestion` | Dismiss one pending suggestion so it does not reappear in future batches. | **yes** |
+| `accept_topic_suggestion` | Accept one pending suggestion: creates a topic and marks the suggestion added. | **yes** (admin, manager) |
+| `dismiss_topic_suggestion` | Dismiss one pending suggestion so it does not reappear in future batches. | **yes** (admin, manager) |
| `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** |
+| `accept_prompt_suggestion` | Create a tracked prompt from one pending suggestion using the brand's default engines and plan/location checks. | **yes** (admin, manager) |
+| `dismiss_prompt_suggestion` | Dismiss one pending prompt suggestion so it no longer appears in future lists. | **yes** (admin, manager, analyst) |
| `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. | |
@@ -302,7 +303,7 @@ curl "https://app.ansvisor.com/api/mcp/mentions/summary?brand_id=<brand_id>&plat
| `get_content_plan` | The Content plan, as **Content → Plan** ranks it by the Priority Score: what to create, optimize or protect next, why, the score's parts, the draft already being written and the rows marked a priority. Over 7, 30 or 90 days; optional `card`. | |
| `get_content_opportunity` | Full details for one opportunity, including metrics, intent, competitors, and any existing brief. | |
| `generate_content_brief` | Generate or overwrite an AI content brief for an opportunity (LLM cost/latency). | **yes** |
-| `update_opportunity_status` | Move an opportunity through workflow states (`new`, `reviewed`, `sent`, `in_progress`, `done`, `dismissed`). | **yes** |
+| `update_opportunity_status` | Move an opportunity through workflow states (`new`, `reviewed`, `sent`, `in_progress`, `done`, `dismissed`). Dismissing one, or moving a dismissed one back, needs an admin or a manager. | **yes** |
The plan is also available over REST with the same `ans_` key: `GET /api/mcp/content-plan?brand_id=<brand_id>&days=30`, with `card` as an optional query parameter.
@@ -385,6 +386,26 @@ Ask your client things like:
The model picks the right tool, fills in the brand id and filters, and
answers in plain English using the returned data.
+## Roles
+
+A key acts as the person who created it, with their role in the
+organization. `get_me` returns it. Day-to-day work is open to every role:
+reading, drafts and suggestions in the Content Editor, briefs, Site Audits,
+task progress and an opportunity's progress. Adding prompts or topics and
+dismissing are for admins and managers. Dismissing a prompt suggestion is open
+to analysts too. The tools marked with roles above refuse anyone else before
+they change anything. The call fails with text like this:
+
+```text
+Only an admin or a manager can do this. This API key acts as an analyst: ask an admin or a manager of the organization to do it.
+```
+
+The REST routes under `/api/mcp/…` answer the same refusal with `403`:
+
+```json
+{ "error": "forbidden", "code": "role_required", "message": "Only an admin or a manager can do this. …" }
+```
+
## When the plan has ended
On Ansvisor Cloud, a workspace without an active plan is read-only (see
diff --git a/web/src/app/api/mcp/content-opportunities/[id]/status/route.test.ts b/web/src/app/api/mcp/content-opportunities/[id]/status/route.test.ts
new file mode 100644
index 000000000..d40d4c6ed
--- /dev/null
+++ b/web/src/app/api/mcp/content-opportunities/[id]/status/route.test.ts
@@ -0,0 +1,69 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * PATCH /api/mcp/content-opportunities/[id]/status: a change the key's role
+ * doesn't allow (updateOpportunityStatusFor's own check) answers 403 with the
+ * reason; any other failure is still a 500.
+ */
+
+const { updateOpportunityStatusFor } = vi.hoisted(() => ({
+ updateOpportunityStatusFor: vi.fn(),
+}));
+vi.mock('@/lib/mcp-auth', () => ({
+ authenticateMcpRequest: vi.fn(async () => ({
+ userId: 'user-1',
+ email: null,
+ organizationId: 'org-1',
+ role: 'analyst',
+ apiKeyId: 'key-1',
+ })),
+}));
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));
+vi.mock('@/lib/mcp/data', () => ({
+ CONTENT_OPPORTUNITY_STATUSES: ['new', 'reviewed', 'sent', 'in_progress', 'done', 'dismissed'],
+ updateOpportunityStatusFor,
+}));
+
+const { PATCH } = await import('./route');
+const { RoleRequiredError, MANAGER_ROLES } = await import('@/lib/mcp/role-gate');
+
+const patch = (status: string) =>
+ PATCH(
+ new Request('http://localhost/api/mcp/content-opportunities/opp-1/status', {
+ method: 'PATCH',
+ body: JSON.stringify({ status }),
+ }),
+ { params: Promise.resolve({ id: 'opp-1' }) },
+ );
+
+beforeEach(() => {
+ updateOpportunityStatusFor.mockReset();
+});
+
+describe('PATCH /api/mcp/content-opportunities/[id]/status', () => {
+ it('answers 403 with the reason when the role may not make the change', async () => {
+ updateOpportunityStatusFor.mockRejectedValue(new RoleRequiredError(MANAGER_ROLES, 'analyst'));
+ const res = await patch('dismissed');
+ expect(res.status).toBe(403);
+ expect(await res.json()).toEqual({
+ error: 'forbidden',
+ code: 'role_required',
+ message:
+ 'Only an admin or a manager can do this. This API key acts as an analyst: ask an admin or a manager of the organization to do it.',
+ });
+ });
+
+ it('keeps any other failure a 500 with its message', async () => {
+ updateOpportunityStatusFor.mockRejectedValue(new Error('connection reset'));
+ const res = await patch('done');
+ expect(res.status).toBe(500);
+ expect(await res.json()).toEqual({ error: 'connection reset' });
+ });
+
+ it('answers the updated row otherwise', async () => {
+ updateOpportunityStatusFor.mockResolvedValue({ id: 'opp-1', status: 'done', updated_at: 'x' });
+ const res = await patch('done');
+ expect(res.status).toBe(200);
+ });
+});
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 2fbb8b5ce..c9417ea7d 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
@@ -5,6 +5,7 @@ import {
updateOpportunityStatusFor,
type ContentOpportunityStatus,
} from '@/lib/mcp/data';
+import { failedCallResponse } from '@/lib/mcp/subscription-gate';
/**
* PATCH /api/mcp/content-opportunities/[id]/status
@@ -12,6 +13,8 @@ import {
* Parallel REST surface for the `update_opportunity_status` MCP tool —
* same data-layer function, same ownership guarantee, same enum validation.
* Body: `{ "status": "in_progress" }` (one of new | sent | in_progress | done | dismissed).
+ * Dismissing one, or moving a dismissed one back, answers 403 unless the
+ * key's user is an admin or a manager.
*/
export async function PATCH(req: Request, { params }: { params: Promise<{ id: string }> }) {
const auth = await authenticateMcpRequest(req);
@@ -54,7 +57,6 @@ export async function PATCH(req: Request, { params }: { params: Promise<{ id: st
}
return NextResponse.json(updated);
} catch (err) {
- const message = err instanceof Error ? err.message : 'Failed';
- return NextResponse.json({ error: message }, { status: 500 });
+ return failedCallResponse(err);
}
}
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 9777a80c6..66c8dbbf8 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,13 +1,15 @@
import { NextResponse } from 'next/server';
import { authenticateMcpRequest } from '@/lib/mcp-auth';
import { acceptTopicSuggestionFor } from '@/lib/mcp/data';
+import { failedCallResponse } from '@/lib/mcp/subscription-gate';
/**
* POST /api/mcp/topic-suggestions/[id]/accept
*
* Parallel REST surface for the `accept_topic_suggestion` MCP tool — same
* data-layer function, same ownership guarantee, same status = 'new' guard
- * that keeps a repeated accept from creating a second topic.
+ * that keeps a repeated accept from creating a second topic. 403 unless the
+ * key's user is an admin or a manager.
*/
export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
const auth = await authenticateMcpRequest(req);
@@ -29,7 +31,6 @@ export async function POST(req: Request, { params }: { params: Promise<{ id: str
}
return NextResponse.json(result);
} catch (err) {
- const message = err instanceof Error ? err.message : 'Failed';
- return NextResponse.json({ error: message }, { status: 500 });
+ return failedCallResponse(err);
}
}
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 5c5d52045..0f65e8e4b 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,12 +1,14 @@
import { NextResponse } from 'next/server';
import { authenticateMcpRequest } from '@/lib/mcp-auth';
import { dismissTopicSuggestionFor } from '@/lib/mcp/data';
+import { failedCallResponse } from '@/lib/mcp/subscription-gate';
/**
* POST /api/mcp/topic-suggestions/[id]/dismiss
*
* Parallel REST surface for the `dismiss_topic_suggestion` MCP tool — same
- * data-layer function, same ownership guarantee.
+ * data-layer function, same ownership guarantee. 403 unless the key's user
+ * is an admin or a manager.
*/
export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
const auth = await authenticateMcpRequest(req);
@@ -28,7 +30,6 @@ export async function POST(req: Request, { params }: { params: Promise<{ id: str
}
return NextResponse.json(result);
} catch (err) {
- const message = err instanceof Error ? err.message : 'Failed';
- return NextResponse.json({ error: message }, { status: 500 });
+ return failedCallResponse(err);
}
}
diff --git a/web/src/lib/agent/auth.ts b/web/src/lib/agent/auth.ts
index 995f21843..8656bcd0f 100644
--- a/web/src/lib/agent/auth.ts
+++ b/web/src/lib/agent/auth.ts
@@ -1,6 +1,7 @@
import { createClient } from '@/lib/supabase/server';
import { supabaseAdmin } from '@/lib/supabase/admin';
import type { McpAuthContext } from '@/lib/mcp-auth';
+import type { UserRole } from '@/types';
/**
* Resolve the current dashboard session into the same shape the MCP data
@@ -20,7 +21,7 @@ export async function resolveAgentAuth(): Promise<McpAuthContext | null> {
const { data: profile } = await supabaseAdmin
.from('profiles')
- .select('organization_id')
+ .select('organization_id, role')
.eq('id', user.id)
.maybeSingle();
@@ -30,6 +31,7 @@ export async function resolveAgentAuth(): Promise<McpAuthContext | null> {
userId: user.id,
email: user.email ?? '',
organizationId: profile.organization_id,
+ role: (profile.role as UserRole | null | undefined) ?? null,
// The MCP-auth shape expects an apiKeyId — the agent isn't behind an
// API key, this is just a marker so downstream code that switches on
// the field knows the call came from the in-product agent rather than
diff --git a/web/src/lib/mcp-auth.test.ts b/web/src/lib/mcp-auth.test.ts
index 327ed3bf9..3a58795f7 100644
--- a/web/src/lib/mcp-auth.test.ts
+++ b/web/src/lib/mcp-auth.test.ts
@@ -15,7 +15,7 @@ vi.mock('@/lib/supabase/admin', () => ({
table === 'api_keys'
? { id: 'key-1', user_id: 'user-1', revoked_at: null }
: table === 'profiles'
- ? { organization_id: 'org-1' }
+ ? { organization_id: 'org-1', role: 'analyst' }
: { subscription_status: status };
const query = {
select: () => query,
@@ -53,6 +53,10 @@ describe('authenticateMcpRequest on a read-only workspace', () => {
expect(auth).toMatchObject({ userId: 'user-1', organizationId: 'org-1' });
});
+ it("carries the user's role, for the tools that check it", async () => {
+ expect(await authenticateMcpRequest(request('GET'))).toMatchObject({ role: 'analyst' });
+ });
+
it('answers a write with 402 subscription_inactive', async () => {
for (const method of ['POST', 'PUT', 'PATCH', 'DELETE']) {
const res = (await authenticateMcpRequest(request(method))) as Response;
diff --git a/web/src/lib/mcp-auth.ts b/web/src/lib/mcp-auth.ts
index cd19f85fe..c092ab21d 100644
--- a/web/src/lib/mcp-auth.ts
+++ b/web/src/lib/mcp-auth.ts
@@ -2,6 +2,7 @@ import { createHash, randomBytes } from 'node:crypto';
import { NextResponse } from 'next/server';
import { supabaseAdmin } from '@/lib/supabase/admin';
import { subscriptionActiveFor, subscriptionInactiveResponse } from '@/lib/mcp/subscription-gate';
+import type { UserRole } from '@/types';
export const API_KEY_PREFIX = 'ans_';
export const API_KEY_DISPLAY_PREFIX_LEN = 12;
@@ -21,6 +22,8 @@ export interface McpAuthContext {
userId: string;
email: string | null;
organizationId: string | null;
+ /** The user's role in the organization: the tools that need one check it (lib/mcp/role-gate.ts). */
+ role: UserRole | null;
apiKeyId: string;
}
@@ -65,7 +68,7 @@ export async function authenticateMcpRequest(
// Resolve the owning user + their organization so handlers don't have to.
const { data: profile } = await supabaseAdmin
.from('profiles')
- .select('organization_id')
+ .select('organization_id, role')
.eq('id', key.user_id)
.maybeSingle();
@@ -93,6 +96,7 @@ export async function authenticateMcpRequest(
userId: key.user_id,
email: user?.email ?? null,
organizationId,
+ role: (profile?.role as UserRole | null | undefined) ?? null,
apiKeyId: key.id,
};
}
diff --git a/web/src/lib/mcp/account.test.ts b/web/src/lib/mcp/account.test.ts
index cbee3d92e..9f3baacae 100644
--- a/web/src/lib/mcp/account.test.ts
+++ b/web/src/lib/mcp/account.test.ts
@@ -39,6 +39,7 @@ const auth: McpAuthContext = {
organizationId: 'org-1',
apiKeyId: 'key-1',
+ role: 'admin',
};
describe('getMeFor', () => {
diff --git a/web/src/lib/mcp/action-center.test.ts b/web/src/lib/mcp/action-center.test.ts
index 3b28b4ddc..e0ef4339b 100644
--- a/web/src/lib/mcp/action-center.test.ts
+++ b/web/src/lib/mcp/action-center.test.ts
@@ -65,6 +65,7 @@ const auth: McpAuthContext = {
email: null,
organizationId: 'org-1',
apiKeyId: 'key-1',
+ role: 'admin',
};
const writes = () => ops.filter((o) => o.op !== 'select');
diff --git a/web/src/lib/mcp/action-export.test.ts b/web/src/lib/mcp/action-export.test.ts
index bda6a98f4..fa33c5cbf 100644
--- a/web/src/lib/mcp/action-export.test.ts
+++ b/web/src/lib/mcp/action-export.test.ts
@@ -79,6 +79,7 @@ const auth: McpAuthContext = {
email: null,
organizationId: 'org-1',
apiKeyId: 'key-1',
+ role: 'admin',
};
const actionRow = (over: Row = {}): Row => ({
diff --git a/web/src/lib/mcp/action-history.test.ts b/web/src/lib/mcp/action-history.test.ts
index 28f9246ff..4572c9fd8 100644
--- a/web/src/lib/mcp/action-history.test.ts
+++ b/web/src/lib/mcp/action-history.test.ts
@@ -36,6 +36,7 @@ const auth: McpAuthContext = {
email: null,
organizationId: 'org-1',
apiKeyId: 'key-1',
+ role: 'admin',
};
function action(outcome: string | null, validation: Record<string, unknown> | null) {
diff --git a/web/src/lib/mcp/action-priority.test.ts b/web/src/lib/mcp/action-priority.test.ts
index 17cfc0172..17568ceaa 100644
--- a/web/src/lib/mcp/action-priority.test.ts
+++ b/web/src/lib/mcp/action-priority.test.ts
@@ -91,6 +91,7 @@ const auth: McpAuthContext = {
email: null,
organizationId: 'org-1',
apiKeyId: 'key-1',
+ role: 'admin',
};
describe('listActionsFor', () => {
diff --git a/web/src/lib/mcp/content-delivery.test.ts b/web/src/lib/mcp/content-delivery.test.ts
index 91a60af92..2a10c1a6f 100644
--- a/web/src/lib/mcp/content-delivery.test.ts
+++ b/web/src/lib/mcp/content-delivery.test.ts
@@ -35,6 +35,7 @@ const auth: McpAuthContext = {
email: null,
organizationId: 'org-1',
apiKeyId: 'key-1',
+ role: 'admin',
};
const LIVE = 'https://acme.example/blog/cold-brew';
const fetchMock = vi.fn();
diff --git a/web/src/lib/mcp/content-plan.test.ts b/web/src/lib/mcp/content-plan.test.ts
index fac3a6d65..42ec2edb1 100644
--- a/web/src/lib/mcp/content-plan.test.ts
+++ b/web/src/lib/mcp/content-plan.test.ts
@@ -37,6 +37,7 @@ const auth: McpAuthContext = {
email: null,
organizationId: 'org-1',
apiKeyId: 'key-1',
+ role: 'admin',
};
const READ: ContentPlanRead = {
diff --git a/web/src/lib/mcp/content.test.ts b/web/src/lib/mcp/content.test.ts
index 491b415f1..52a3aabcb 100644
--- a/web/src/lib/mcp/content.test.ts
+++ b/web/src/lib/mcp/content.test.ts
@@ -65,6 +65,7 @@ const auth: McpAuthContext = {
email: null,
organizationId: 'org-1',
apiKeyId: 'key-1',
+ role: 'admin',
};
const QUOTED =
diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.ts
index 1dc5d0f09..1372a6a4a 100644
--- a/web/src/lib/mcp/data.ts
+++ b/web/src/lib/mcp/data.ts
@@ -17,6 +17,7 @@ import { computeAiVisibilityScore } from '@/lib/visibility-score';
import { API_BASE_URL } from '@/config/api';
import { ORG_PLAN_COLUMNS, planFromOrgRow, usagePlanFromOrgRow } from '@/lib/guards/plan-guard';
import { assertSubscriptionActive } from '@/lib/mcp/subscription-gate';
+import { MEMBER_ROLES, requireManager, requireRole } from '@/lib/mcp/role-gate';
import {
fetchPromptUsageRow,
toPromptUsageSummary,
@@ -453,13 +454,14 @@ export interface DismissedTopicSuggestion {
* Dismiss a pending suggestion so it never reappears in future refreshes.
* Scoped to status = 'new' so dismissing an already-decided suggestion (added
* or already dismissed) is a no-op that returns null rather than silently
- * "succeeding" twice.
+ * "succeeding" twice. An admin's or a manager's call, as on the Topics page.
*/
export async function dismissTopicSuggestionFor(
auth: McpAuthContext,
suggestionId: string,
): Promise<DismissedTopicSuggestion | null> {
if (!auth.organizationId) return null;
+ requireManager(auth);
const { data: ownership } = await supabaseAdmin
.from('topic_suggestions')
@@ -493,13 +495,15 @@ export interface AcceptedTopicSuggestion {
* createTopic action), then mark the suggestion added with a pointer to the
* new topic. Scoped to status = 'new' up front, so accepting the same
* suggestion twice fails the ownership lookup on the second call instead of
- * creating a second topic.
+ * creating a second topic. An admin's or a manager's call, as on the Topics
+ * page.
*/
export async function acceptTopicSuggestionFor(
auth: McpAuthContext,
suggestionId: string,
): Promise<AcceptedTopicSuggestion | null> {
if (!auth.organizationId) return null;
+ requireManager(auth);
const { data: suggestion } = await supabaseAdmin
.from('topic_suggestions')
@@ -588,12 +592,17 @@ export interface DismissedPromptSuggestion {
status: 'dismissed';
}
-/** Dismiss only a pending suggestion belonging to the authenticated organization. */
+/**
+ * Dismiss only a pending suggestion belonging to the authenticated
+ * organization. Any member but an agency partner may, as the table's update
+ * rule.
+ */
export async function dismissPromptSuggestionFor(
auth: McpAuthContext,
suggestionId: string,
): Promise<DismissedPromptSuggestion | null> {
if (!auth.organizationId) return null;
+ requireRole(auth, MEMBER_ROLES);
const { data: owned, error: lookupError } = await supabaseAdmin
.from('prompt_suggestions')
@@ -635,12 +644,14 @@ export type AcceptPromptSuggestionResult =
* plan engine filtering, shopping-mode behavior, region choice and location
* quota check. Every lookup is organization-scoped; duplicate acceptance
* removes any losing concurrent insert rather than leaving duplicate prompts.
+ * Adding a prompt is an admin's or a manager's call, as on the Prompts page.
*/
export async function acceptPromptSuggestionFor(
auth: McpAuthContext,
suggestionId: string,
): Promise<AcceptPromptSuggestionResult | null> {
if (!auth.organizationId) return null;
+ requireManager(auth);
const { data: suggestion, error: suggestionError } = await supabaseAdmin
.from('prompt_suggestions')
@@ -1408,7 +1419,9 @@ export interface UpdatedOpportunityStatus {
*
* Ownership-check-first: the update only runs after we've verified the
* opportunity's brand belongs to the caller's org. Wrong-org or missing
- * id returns null (→ 404) with no DB write.
+ * id returns null (→ 404) with no DB write. Any member may record progress;
+ * dismissing one, or bringing a dismissed one back, is an admin's or a
+ * manager's call.
*/
export async function updateOpportunityStatusFor(
auth: McpAuthContext,
@@ -1421,11 +1434,12 @@ export async function updateOpportunityStatusFor(
// A wrong-org id misses here and we return null *before* any update.
const { data: ownership } = await supabaseAdmin
.from('content_opportunities')
- .select('id, brands!inner(organization_id)')
+ .select('id, status, brands!inner(organization_id)')
.eq('id', opportunityId)
.eq('brands.organization_id', auth.organizationId)
.maybeSingle();
if (!ownership) return null;
+ if (status === 'dismissed' || ownership.status === 'dismissed') requireManager(auth);
const updatedAt = new Date().toISOString();
diff --git a/web/src/lib/mcp/improve-action.test.ts b/web/src/lib/mcp/improve-action.test.ts
index 9622dc035..b3554ea96 100644
--- a/web/src/lib/mcp/improve-action.test.ts
+++ b/web/src/lib/mcp/improve-action.test.ts
@@ -35,6 +35,7 @@ const auth: McpAuthContext = {
email: null,
organizationId: 'org-1',
apiKeyId: 'key-1',
+ role: 'admin',
};
const input = {
diff --git a/web/src/lib/mcp/learning.test.ts b/web/src/lib/mcp/learning.test.ts
index ca5823b03..13556982e 100644
--- a/web/src/lib/mcp/learning.test.ts
+++ b/web/src/lib/mcp/learning.test.ts
@@ -40,6 +40,7 @@ const auth: McpAuthContext = {
email: null,
organizationId: 'org-1',
apiKeyId: 'key-1',
+ role: 'admin',
};
const rpcRow = (over: Record<string, unknown>) => ({
diff --git a/web/src/lib/mcp/mentions.test.ts b/web/src/lib/mcp/mentions.test.ts
index 3af98d9c2..3a1c79a51 100644
--- a/web/src/lib/mcp/mentions.test.ts
+++ b/web/src/lib/mcp/mentions.test.ts
@@ -49,6 +49,7 @@ const auth: McpAuthContext = {
email: null,
organizationId: 'org-1',
apiKeyId: 'key-1',
+ role: 'admin',
};
const brand = {
diff --git a/web/src/lib/mcp/prompt-volumes.test.ts b/web/src/lib/mcp/prompt-volumes.test.ts
index 50ea769ec..b17542151 100644
--- a/web/src/lib/mcp/prompt-volumes.test.ts
+++ b/web/src/lib/mcp/prompt-volumes.test.ts
@@ -38,6 +38,7 @@ const auth: McpAuthContext = {
email: null,
organizationId: 'org-1',
apiKeyId: 'key-1',
+ role: 'admin',
};
const row = (over: Record<string, unknown>) => ({
diff --git a/web/src/lib/mcp/role-gate.test.ts b/web/src/lib/mcp/role-gate.test.ts
new file mode 100644
index 000000000..2bda108b5
--- /dev/null
+++ b/web/src/lib/mcp/role-gate.test.ts
@@ -0,0 +1,206 @@
+// @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 { UserRole } from '@/types';
+
+/**
+ * The MCP tools write with the service role, so they check the key's role
+ * themselves: adding a prompt or a topic, and dismissing, are an admin's or a
+ * manager's; recording an opportunity's progress is any member's. A refused
+ * call writes nothing.
+ */
+
+/** Each row read or written, by table and kind. */
+const calls: { table: string; op: 'select' | 'update' | 'insert' }[] = [];
+/** The opportunity the status tool finds, with the status it has now. */
+let opportunity: { id: string; status: string } | null;
+
+vi.mock('@/lib/supabase/admin', () => ({
+ supabaseAdmin: {
+ from: (table: string) => {
+ let op: 'select' | 'update' | 'insert' = 'select';
+ let written: Record<string, unknown> = {};
+ const chain = {
+ select: () => chain,
+ update: (values: Record<string, unknown>) => {
+ op = 'update';
+ written = values;
+ return chain;
+ },
+ insert: () => {
+ op = 'insert';
+ return chain;
+ },
+ eq: () => chain,
+ // A suggestion is never found: past the role check, the tool answers "not found".
+ maybeSingle: async () => {
+ calls.push({ table, op });
+ return { data: table === 'content_opportunities' ? opportunity : null, error: null };
+ },
+ single: async () => {
+ calls.push({ table, op });
+ return { data: { id: opportunity?.id, ...written }, error: null };
+ },
+ };
+ return chain;
+ },
+ },
+}));
+
+const { createMcpServer } = await import('./server');
+const { RoleRequiredError, requireManager, requireRole, MEMBER_ROLES } =
+ await import('./role-gate');
+
+const ID = '11111111-2222-3333-4444-555555555555';
+
+/** A client on a server built for a key whose user has `role`. */
+async function connect(role: UserRole | null) {
+ const server = createMcpServer({
+ userId: 'user-1',
+ email: null,
+ organizationId: 'org-1',
+ role,
+ apiKeyId: 'key-1',
+ });
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ await server.connect(serverTransport);
+ const client = new Client({ name: 'test', version: '1.0.0' });
+ await client.connect(clientTransport);
+ return client;
+}
+
+const text = (result: Awaited<ReturnType<Client['callTool']>>) =>
+ (result.content as { text: string }[])[0].text;
+
+beforeEach(() => {
+ // Self-hosted: the plan gate lets every tool through without a read.
+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'false');
+ calls.length = 0;
+ opportunity = { id: ID, status: 'new' };
+});
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
+describe('requireManager', () => {
+ it('lets an admin and a manager through', () => {
+ expect(() => requireManager({ role: 'admin' })).not.toThrow();
+ expect(() => requireManager({ role: 'manager' })).not.toThrow();
+ });
+
+ it('refuses an analyst, an agency partner and a user without a role, saying who can', () => {
+ for (const role of ['analyst', 'agency_partner', null] as const) {
+ expect(() => requireManager({ role })).toThrow(RoleRequiredError);
+ }
+ expect(() => requireManager({ role: 'analyst' })).toThrow(
+ 'Only an admin or a manager can do this. This API key acts as an analyst: ask an admin or a manager of the organization to do it.',
+ );
+ });
+
+ it('names every role allowed when more than two are', () => {
+ expect(() => requireRole({ role: 'agency_partner' }, MEMBER_ROLES)).toThrow(
+ 'Only an admin, a manager or an analyst can do this. This API key acts as an agency partner',
+ );
+ expect(() => requireRole({ role: 'analyst' }, MEMBER_ROLES)).not.toThrow();
+ });
+});
+
+describe('the tools only an admin or a manager may call', () => {
+ const managerTools = [
+ 'accept_prompt_suggestion',
+ 'accept_topic_suggestion',
+ 'dismiss_topic_suggestion',
+ ];
+
+ it('refuses an analyst before anything is read or written', async () => {
+ const client = await connect('analyst');
+ for (const name of managerTools) {
+ const result = await client.callTool({ name, arguments: { suggestion_id: ID } });
+ expect(result.isError, name).toBe(true);
+ expect(text(result), name).toMatch(/^Only an admin or a manager can do this/);
+ }
+ expect(calls).toEqual([]);
+ });
+
+ it('lets a manager through to the suggestion', async () => {
+ const client = await connect('manager');
+ for (const name of managerTools) {
+ const result = await client.callTool({ name, arguments: { suggestion_id: ID } });
+ expect(text(result), name).toBe('Suggestion not found, not pending, or already processed');
+ }
+ expect(calls.map((call) => call.table)).toEqual([
+ 'prompt_suggestions',
+ 'topic_suggestions',
+ 'topic_suggestions',
+ ]);
+ });
+});
+
+describe('dismiss_prompt_suggestion', () => {
+ it('refuses an agency partner', async () => {
+ const client = await connect('agency_partner');
+ const result = await client.callTool({
+ name: 'dismiss_prompt_suggestion',
+ arguments: { suggestion_id: ID },
+ });
+ expect(result.isError).toBe(true);
+ expect(text(result)).toMatch(/^Only an admin, a manager or an analyst can do this/);
+ expect(calls).toEqual([]);
+ });
+
+ it('lets an analyst through, as the table does', async () => {
+ const client = await connect('analyst');
+ const result = await client.callTool({
+ name: 'dismiss_prompt_suggestion',
+ arguments: { suggestion_id: ID },
+ });
+ expect(text(result)).toBe('Suggestion not found, not pending, or already processed');
+ expect(calls).toEqual([{ table: 'prompt_suggestions', op: 'select' }]);
+ });
+});
+
+describe('update_opportunity_status', () => {
+ const update = (client: Client, status: string) =>
+ client.callTool({
+ name: 'update_opportunity_status',
+ arguments: { opportunity_id: ID, status },
+ });
+ const updates = () => calls.filter((call) => call.op === 'update');
+
+ it("records an analyst's progress", async () => {
+ const client = await connect('analyst');
+ const result = await update(client, 'in_progress');
+ expect(result.isError).toBeFalsy();
+ expect(JSON.parse(text(result))).toMatchObject({ id: ID, status: 'in_progress' });
+ expect(updates()).toHaveLength(1);
+ });
+
+ it('refuses an analyst a dismissal, or bringing a dismissed one back, without a write', async () => {
+ const client = await connect('analyst');
+ const dismissed = await update(client, 'dismissed');
+ expect(dismissed.isError).toBe(true);
+ expect(text(dismissed)).toMatch(/^Only an admin or a manager can do this/);
+
+ opportunity = { id: ID, status: 'dismissed' };
+ const restored = await update(client, 'new');
+ expect(restored.isError).toBe(true);
+ expect(updates()).toEqual([]);
+ });
+
+ it('lets a manager dismiss one', async () => {
+ const client = await connect('manager');
+ const result = await update(client, 'dismissed');
+ expect(result.isError).toBeFalsy();
+ expect(JSON.parse(text(result))).toMatchObject({ status: 'dismissed' });
+ expect(updates()).toHaveLength(1);
+ });
+
+ it('says not found, not forbidden, for an opportunity outside the organization', async () => {
+ opportunity = null;
+ const client = await connect('analyst');
+ const result = await update(client, 'dismissed');
+ expect(text(result)).toBe('Content opportunity not found');
+ });
+});
diff --git a/web/src/lib/mcp/role-gate.ts b/web/src/lib/mcp/role-gate.ts
new file mode 100644
index 000000000..fa254c192
--- /dev/null
+++ b/web/src/lib/mcp/role-gate.ts
@@ -0,0 +1,67 @@
+import { NextResponse } from 'next/server';
+import type { McpAuthContext } from '@/lib/mcp-auth';
+import type { UserRole } from '@/types';
+
+/**
+ * Who may do what over an API key. The key acts as its user, with that
+ * user's role, and the MCP layer writes with the service role, so the row
+ * rules the dashboard relies on don't apply: the tools check the role
+ * themselves. The split follows the dashboard: day-to-day work (drafts,
+ * tasks, audits, briefs, reports) is open to every member; adding prompts or
+ * topics, dismissing what the team decides on, and settings are for admins
+ * and managers.
+ */
+export const MANAGER_ROLES = ['admin', 'manager'] as const satisfies readonly UserRole[];
+
+/** Everyone but an agency partner, as prompt_suggestions' update rule (00048). */
+export const MEMBER_ROLES = ['admin', 'manager', 'analyst'] as const satisfies readonly UserRole[];
+
+const ROLE_NAMES: Record<UserRole, string> = {
+ admin: 'an admin',
+ manager: 'a manager',
+ analyst: 'an analyst',
+ agency_partner: 'an agency partner',
+};
+
+/** "an admin or a manager", "an admin, a manager or an analyst". */
+function roleList(roles: readonly UserRole[]): string {
+ const names = roles.map((role) => ROLE_NAMES[role]);
+ return names.length > 1 ? `${names.slice(0, -1).join(', ')} or ${names.at(-1)}` : names[0];
+}
+
+/**
+ * A call the key's user may not make with their role. An MCP tool that throws
+ * it answers as a tool error with the message (the SDK turns a thrown error
+ * into one); a REST route answers 403 (roleRequiredResponse).
+ */
+export class RoleRequiredError extends Error {
+ readonly status = 403;
+ readonly code = 'role_required';
+
+ constructor(roles: readonly UserRole[], role: UserRole | null) {
+ super(
+ `Only ${roleList(roles)} can do this. This API key acts as ${
+ role ? ROLE_NAMES[role] : 'a user without a role'
+ }: ask an admin or a manager of the organization to do it.`,
+ );
+ this.name = 'RoleRequiredError';
+ }
+}
+
+/** Refuse the call unless the key's user has one of `roles`. */
+export function requireRole(auth: Pick<McpAuthContext, 'role'>, roles: readonly UserRole[]): void {
+ if (!auth.role || !roles.includes(auth.role)) throw new RoleRequiredError(roles, auth.role);
+}
+
+/** Refuse the call unless the key's user is an admin or a manager. */
+export function requireManager(auth: Pick<McpAuthContext, 'role'>): void {
+ requireRole(auth, MANAGER_ROLES);
+}
+
+/** The REST routes' answer to a call refused for the role. */
+export function roleRequiredResponse(err: RoleRequiredError): NextResponse {
+ return NextResponse.json(
+ { error: 'forbidden', code: err.code, message: err.message },
+ { status: 403 },
+ );
+}
diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.ts
index e54254e67..333b73860 100644
--- a/web/src/lib/mcp/server.ts
+++ b/web/src/lib/mcp/server.ts
@@ -311,7 +311,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
'accept_topic_suggestion',
{
description:
- 'Accept a pending topic suggestion: creates exactly one new topic from it and marks the suggestion as added. Only fire on explicit user intent for a specific suggestion (from list_topic_suggestions), never as part of an exploratory query. Accepting the same suggestion twice fails cleanly — it is not accepted or already decided — no duplicate topic is created.',
+ 'Accept a pending topic suggestion: creates exactly one new topic from it and marks the suggestion as added. Only fire on explicit user intent for a specific suggestion (from list_topic_suggestions), never as part of an exploratory query. Accepting the same suggestion twice fails cleanly — it is not accepted or already decided — no duplicate topic is created. Needs an admin or a manager (get_me returns the role).',
inputSchema: {
suggestion_id: relaxedUuid.describe('Topic suggestion UUID, from list_topic_suggestions.'),
},
@@ -336,7 +336,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
'dismiss_topic_suggestion',
{
description:
- 'Dismiss a pending topic suggestion so it never reappears in future suggestion batches. Only fire on explicit user intent for a specific suggestion (from list_topic_suggestions), never as part of an exploratory query.',
+ 'Dismiss a pending topic suggestion so it never reappears in future suggestion batches. Only fire on explicit user intent for a specific suggestion (from list_topic_suggestions), never as part of an exploratory query. Needs an admin or a manager (get_me returns the role).',
inputSchema: {
suggestion_id: relaxedUuid.describe('Topic suggestion UUID, from list_topic_suggestions.'),
},
@@ -384,7 +384,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
'accept_prompt_suggestion',
{
description:
- "Accept one pending prompt suggestion by creating a tracked prompt with the brand's default platform/model settings and marking the suggestion added. This consumes one active prompt location and respects the organization's plan limit and allowed engines. Only fire on explicit user intent for a specific suggestion from list_prompt_suggestions, never as part of an exploratory query. Accepting the same suggestion twice does not create a duplicate prompt.",
+ "Accept one pending prompt suggestion by creating a tracked prompt with the brand's default platform/model settings and marking the suggestion added. This consumes one active prompt location and respects the organization's plan limit and allowed engines. Only fire on explicit user intent for a specific suggestion from list_prompt_suggestions, never as part of an exploratory query. Accepting the same suggestion twice does not create a duplicate prompt. Needs an admin or a manager (get_me returns the role).",
inputSchema: {
suggestion_id: relaxedUuid.describe(
'Prompt suggestion UUID, from list_prompt_suggestions.',
@@ -417,7 +417,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
'dismiss_prompt_suggestion',
{
description:
- 'Dismiss a pending prompt suggestion so it no longer appears in future suggestion lists. Only fire on explicit user intent for a specific suggestion from list_prompt_suggestions, never as part of an exploratory query.',
+ 'Dismiss a pending prompt suggestion so it no longer appears in future suggestion lists. Only fire on explicit user intent for a specific suggestion from list_prompt_suggestions, never as part of an exploratory query. Needs an admin, a manager or an analyst, not an agency partner (get_me returns the role).',
inputSchema: {
suggestion_id: relaxedUuid.describe(
'Prompt suggestion UUID, from list_prompt_suggestions.',
@@ -745,7 +745,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
'update_opportunity_status',
{
description:
- 'Move a content opportunity between workflow states. Valid statuses are: "new" (just generated), "sent" (delivered to a CMS / writer via webhook), "in_progress" (someone is actively writing), "done" (published), "dismissed" (intentionally skipped). Use this to close the loop on the content backlog from inside an MCP conversation — e.g. "mark that opportunity as in_progress" once the user starts writing, or "dismiss this one, we already cover it." This is a write — only fire on explicit user intent for a specific opportunity, never as part of an exploratory query.',
+ 'Move a content opportunity between workflow states. Valid statuses are: "new" (just generated), "sent" (delivered to a CMS / writer via webhook), "in_progress" (someone is actively writing), "done" (published), "dismissed" (intentionally skipped). Use this to close the loop on the content backlog from inside an MCP conversation — e.g. "mark that opportunity as in_progress" once the user starts writing, or "dismiss this one, we already cover it." This is a write — only fire on explicit user intent for a specific opportunity, never as part of an exploratory query. Any member may record progress; dismissing one, or moving a dismissed one back, needs an admin or a manager (get_me returns the role).',
inputSchema: {
opportunity_id: relaxedUuid.describe(
'Content opportunity UUID, from list_content_opportunities.',
diff --git a/web/src/lib/mcp/signals.test.ts b/web/src/lib/mcp/signals.test.ts
index ded09fd6e..fbff1c1fa 100644
--- a/web/src/lib/mcp/signals.test.ts
+++ b/web/src/lib/mcp/signals.test.ts
@@ -50,6 +50,7 @@ const auth: McpAuthContext = {
email: null,
organizationId: 'org-1',
apiKeyId: 'key-1',
+ role: 'admin',
};
const row = (over: Record<string, unknown>) => ({
diff --git a/web/src/lib/mcp/subscription-gate.test.ts b/web/src/lib/mcp/subscription-gate.test.ts
index f1eccd407..ad6c7c997 100644
--- a/web/src/lib/mcp/subscription-gate.test.ts
+++ b/web/src/lib/mcp/subscription-gate.test.ts
@@ -50,6 +50,7 @@ async function connect() {
email: null,
organizationId: 'org-1',
apiKeyId: 'key-1',
+ role: 'admin',
});
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
@@ -104,6 +105,7 @@ describe('the MCP tools on a read-only workspace', () => {
email: null,
organizationId: 'org-1',
apiKeyId: 'key-1',
+ role: 'admin',
});
// The handlers the SDK calls once a call's arguments are checked.
const registered = (
@@ -192,6 +194,7 @@ describe('the costly internal calls on a read-only workspace', () => {
email: null,
organizationId: 'org-1',
apiKeyId: 'agent-internal',
+ role: 'admin' as const,
};
const fetchMock = vi.fn(async () =>
Response.json({
diff --git a/web/src/lib/subscription-guard.ts b/web/src/lib/subscription-guard.ts
index 5a7560339..664dc0174 100644
--- a/web/src/lib/subscription-guard.ts
+++ b/web/src/lib/subscription-guard.ts
@@ -1,6 +1,7 @@
import { NextResponse } from 'next/server';
import { isCloud, isSubscriptionActive } from '@/config/plans';
import { createClient } from '@/lib/supabase/server';
+import { RoleRequiredError, roleRequiredResponse } from '@/lib/mcp/role-gate';
/**
* Ansvisor Cloud's read-only mode for the web app's own writes: while a
@@ -44,11 +45,13 @@ export function subscriptionInactiveResponse(): NextResponse {
/**
* A REST route's answer to a call that threw: 402 subscription_inactive when
- * it was refused (assertWritable, assertSubscriptionActive), else 500 with
- * the error's message.
+ * it was refused (assertWritable, assertSubscriptionActive), 403 when the
+ * key's user lacks the role for it (requireManager), else 500 with the
+ * error's message.
*/
export function failedCallResponse(err: unknown): NextResponse {
if (err instanceof SubscriptionInactiveError) return subscriptionInactiveResponse();
+ if (err instanceof RoleRequiredError) return roleRequiredResponse(err);
const message = err instanceof Error ? err.message : 'Failed';
return NextResponse.json({ error: message }, { status: 500 });
}