Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(agent): add source_filter to list_citations (owned/competitor/external) (#311)

Gökhan Geyik40197cf218f7
diff --git a/web/src/app/api/mcp/citations/route.ts b/web/src/app/api/mcp/citations/route.ts
index a95633959..d88b0117a 100644
--- a/web/src/app/api/mcp/citations/route.ts
+++ b/web/src/app/api/mcp/citations/route.ts
@@ -1,13 +1,18 @@
import { NextResponse } from 'next/server';
import { authenticateMcpRequest } from '@/lib/mcp-auth';
-import { listCitationsFor } from '@/lib/mcp/data';
+import {
+ listCitationsFor,
+ CITATION_SOURCE_FILTERS,
+ type CitationSourceFilter,
+} from '@/lib/mcp/data';
/**
* GET /api/mcp/citations
*
* Parallel REST surface for the `list_citations` MCP tool — same data-layer
* function, same ownership guarantee. Query params mirror the MCP tool's args:
- * brand_id (required), date_from, date_to, model, region, topic_id, limit.
+ * brand_id (required), date_from, date_to, model, region, topic_id, limit,
+ * source_filter (all | owned | competitor | external).
*/
export async function GET(req: Request) {
const auth = await authenticateMcpRequest(req);
@@ -32,6 +37,17 @@ export async function GET(req: Request) {
limit = parsed;
}
+ const sourceFilterParam = url.searchParams.get('source_filter');
+ if (
+ sourceFilterParam !== null &&
+ !CITATION_SOURCE_FILTERS.includes(sourceFilterParam as CitationSourceFilter)
+ ) {
+ return NextResponse.json(
+ { error: `source_filter must be one of: ${CITATION_SOURCE_FILTERS.join(', ')}` },
+ { status: 400 },
+ );
+ }
+
try {
const result = await listCitationsFor(auth, {
brandId,
@@ -41,6 +57,7 @@ export async function GET(req: Request) {
region: url.searchParams.get('region') ?? undefined,
topicId: url.searchParams.get('topic_id') ?? undefined,
limit,
+ sourceFilter: (sourceFilterParam as CitationSourceFilter) ?? undefined,
});
if (!result) {
return NextResponse.json({ error: 'Brand not found' }, { status: 404 });
diff --git a/web/src/lib/agent/system-prompt.ts b/web/src/lib/agent/system-prompt.ts
index 2bac2e330..e9bfaabf9 100644
--- a/web/src/lib/agent/system-prompt.ts
+++ b/web/src/lib/agent/system-prompt.ts
@@ -36,7 +36,7 @@ You have these tools, all scoped to the authenticated user's organization:
- **get_visibility_summary** — point-in-time snapshot of avg visibility, mentions, citations for a brand over an optional window.
- **get_visibility_trend** — time-series of visibility / mentions / citations over a date range, bucketed by day or week. Also includes avg competitor score per bucket. Use this for "how has it changed?" questions and to suggest charts.
- **get_competitor_comparison** — competitor benchmark + share of voice for a brand. Returns the brand and every tracked competitor with avg visibility, mentions, citations, appearance count, plus overall SoV and per-platform SoV.
-- **list_citations** — URLs and domains AI engines cite alongside the brand, classified by source type (news / review / owned / social / forum / competitor / you). Returns totals, source-type breakdown, and top cited domains + URLs.
+- **list_citations** — URLs and domains AI engines cite alongside the brand, classified by source type (news / review / owned / social / forum / competitor / you). Returns totals, source-type breakdown, and top cited domains + URLs. When the user asks specifically about *their own* cited URLs ("which of our URLs did AI cite?"), pass \`source_filter: "owned"\`; use \`"competitor"\` for competitor domains and \`"external"\` for everything else.
- **list_topics** — topics on a brand with prompt count each. Use for coverage audits.
- **list_prompts** — prompts being tracked for a brand. Use when the user asks what is being tracked or wants to drill into a specific topic.
- **get_prompt_performance** — aggregates performance (average visibility, total mentions, citations, appearances, and competitor score) grouped by prompt over a date range. Use to answer questions like "what is the best-performing prompt today?" or "which prompts dropped this week?".
diff --git a/web/src/lib/agent/tools.ts b/web/src/lib/agent/tools.ts
index 4c4eadb20..a297fb63e 100644
--- a/web/src/lib/agent/tools.ts
+++ b/web/src/lib/agent/tools.ts
@@ -104,7 +104,7 @@ export function buildAgentTools(auth: McpAuthContext) {
list_citations: tool({
description:
- 'URLs and domains AI engines cite alongside a brand, classified by source type (news / review / owned / social / forum / competitor / you). Returns totals, source_type_breakdown, top_domains, top_urls.',
+ 'URLs and domains AI engines cite alongside a brand, classified by source type (news / review / owned / social / forum / competitor / you). Returns totals, source_type_breakdown, top_domains, top_urls. Pass source_filter: "owned" to isolate the brand\'s own cited URLs (e.g. "which of OUR URLs did AI cite?"), "competitor" for competitor domains, "external" for everything else.',
inputSchema: z.object({
brand_id: z.string().uuid(),
date_from: z.string().optional(),
@@ -113,6 +113,12 @@ export function buildAgentTools(auth: McpAuthContext) {
region: z.string().optional(),
topic_id: z.string().uuid().optional(),
limit: z.number().int().min(1).max(200).optional(),
+ source_filter: z
+ .enum(['all', 'owned', 'competitor', 'external'])
+ .optional()
+ .describe(
+ 'Scope by source: "owned" = brand\'s own domains, "competitor" = tracked competitors, "external" = neither, "all" = no filter (default).',
+ ),
}),
execute: async (args) =>
listCitationsFor(auth, {
@@ -123,6 +129,7 @@ export function buildAgentTools(auth: McpAuthContext) {
region: args.region,
topicId: args.topic_id,
limit: args.limit,
+ sourceFilter: args.source_filter,
}),
}),
diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.ts
index 912309243..7657a9afe 100644
--- a/web/src/lib/mcp/data.ts
+++ b/web/src/lib/mcp/data.ts
@@ -1043,6 +1043,36 @@ export async function getCompetitorComparisonFor(
// ── Citations ────────────────────────────────────────────────────────────────
+/**
+ * Scope a citations query by the source category each URL is classified into
+ * (#297). `owned` = the brand's own domains (`you`), `competitor` = a tracked
+ * competitor domain, `external` = everything else (editorial / forum / social /
+ * review / institutional / other), `all` = no filter (default, current output).
+ */
+export type CitationSourceFilter = 'all' | 'owned' | 'competitor' | 'external';
+
+export const CITATION_SOURCE_FILTERS: CitationSourceFilter[] = [
+ 'all',
+ 'owned',
+ 'competitor',
+ 'external',
+];
+
+/** Does a classified category pass the requested source filter? */
+function citationCategoryMatches(category: SourceCategory, filter: CitationSourceFilter): boolean {
+ switch (filter) {
+ case 'owned':
+ return category === 'you';
+ case 'competitor':
+ return category === 'competitor';
+ case 'external':
+ return category !== 'you' && category !== 'competitor';
+ case 'all':
+ default:
+ return true;
+ }
+}
+
export interface ListCitationsParams {
brandId: string;
dateFrom?: string;
@@ -1053,6 +1083,8 @@ export interface ListCitationsParams {
topicId?: string;
/** Cap on the top_domains / top_urls arrays. Default 50, max 200. */
limit?: number;
+ /** Restrict to owned / competitor / external citations. Default `all`. */
+ sourceFilter?: CitationSourceFilter;
}
export interface CitationsOverviewOutput {
@@ -1199,18 +1231,26 @@ export async function listCitationsFor(
const urlMap = new Map<string, UrlAgg>();
let totalCitations = 0;
let resultsWithCitations = 0;
+ const sourceFilter = params.sourceFilter ?? 'all';
+ const hasSourceFilter = sourceFilter !== 'all';
for (const result of results) {
const citations = Array.isArray(result.citations) ? result.citations : [];
if (citations.length === 0) continue;
- resultsWithCitations += 1;
const modelKey = result.model_used || result.platform || '';
+ // #297 — when a source_filter is set, a result only counts toward
+ // results_with_citations if it contributes at least one matching citation.
+ // With `all` (the default) we never call the matcher, so the aggregation is
+ // byte-identical to the pre-#297 output.
+ let matchedInResult = false;
for (const cite of citations) {
const host = extractHostname(cite.url);
if (!host) continue;
const category = classifyDomain(host, classifyCtx);
+ if (hasSourceFilter && !citationCategoryMatches(category, sourceFilter)) continue;
+ matchedInResult = true;
totalCitations += 1;
const existingDomain = domainMap.get(host) ?? {
@@ -1260,6 +1300,9 @@ export async function listCitationsFor(
if (!existingUrl.title && cite.title) existingUrl.title = cite.title;
urlMap.set(normalizedUrl, existingUrl);
}
+ // `all`: count every result that had citations (original behavior).
+ // Filtered: only results that contributed a matching citation.
+ if (!hasSourceFilter || matchedInResult) resultsWithCitations += 1;
}
const totalResults = results.length;
diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.ts
index c24fdba29..8ae73c0ef 100644
--- a/web/src/lib/mcp/server.ts
+++ b/web/src/lib/mcp/server.ts
@@ -460,6 +460,12 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
.max(200)
.optional()
.describe('Row cap on top_domains / top_urls (default 50, max 200).'),
+ source_filter: z
+ .enum(['all', 'owned', 'competitor', 'external'])
+ .optional()
+ .describe(
+ 'Scope by source category: "owned" = the brand\'s own domains only, "competitor" = tracked competitor domains only, "external" = everything else (editorial / forum / social / review / etc.), "all" = no filter (default). Use "owned" to answer "which of OUR URLs did AI cite?".',
+ ),
},
},
async (args) => {
@@ -471,6 +477,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
region: args.region,
topicId: args.topic_id,
limit: args.limit,
+ sourceFilter: args.source_filter,
});
if (!result) {
return {