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): render_chart tool + inline Recharts visualizations (#138)

Gökhan Geyikf7b9203b9c86
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/agent/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/agent/page.tsx
index 5ead12ac8..5de922ca3 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/agent/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/agent/page.tsx
@@ -3,6 +3,7 @@
import { useEffect, useRef, useState } from 'react';
import { useChat } from '@ai-sdk/react';
import { DefaultChatTransport, type UIMessage } from 'ai';
+import { AgentChart, type AgentChartSpec } from '@/components/agent/agent-chart';
import { useFeatureGate } from '@/hooks/use-feature-gate';
import { Link } from '@/i18n/navigation';
import { Button, buttonVariants } from '@/components/ui/button';
@@ -416,6 +417,9 @@ function MessageBubble({ message }: { message: UIMessage }) {
</Markdown>
);
}
+ if (part.type === 'tool-render_chart') {
+ return <ChartToolPart key={i} part={part} />;
+ }
if (part.type.startsWith('tool-')) {
return <ToolCallDisclosure key={i} part={part} />;
}
@@ -526,6 +530,46 @@ function safeStringify(value: unknown): string {
}
}
+/**
+ * Renderer for the `tool-render_chart` part. Once the tool reaches the
+ * `output-available` state, the input args (which the tool echoes back as
+ * its output) describe a chart spec we can hand to {@link AgentChart}.
+ *
+ * While the call is in flight we show a tiny spinner stub — same shape as
+ * the generic tool disclosure, just without the JSON expansion since
+ * there's no payload to inspect on a chart call.
+ */
+function ChartToolPart({ part }: { part: UIMessage['parts'][number] }) {
+ const toolPart = part as unknown as {
+ type: string;
+ state?: 'input-streaming' | 'input-available' | 'output-available' | 'output-error';
+ input?: AgentChartSpec;
+ output?: AgentChartSpec;
+ errorText?: string;
+ };
+
+ if (toolPart.state === 'output-error') {
+ return (
+ <div className="my-2 rounded-md border bg-destructive/10 text-destructive px-2 py-1 text-xs">
+ <span className="font-mono">render_chart</span>
+ {toolPart.errorText && <span className="ml-2">{toolPart.errorText}</span>}
+ </div>
+ );
+ }
+
+ const spec = toolPart.output ?? toolPart.input;
+ if (!spec || !Array.isArray(spec.data) || spec.data.length === 0) {
+ return (
+ <div className="my-2 inline-flex items-center gap-1.5 text-xs text-muted-foreground bg-muted rounded-md px-2 py-1">
+ <Loader2 className="h-3 w-3 animate-spin" />
+ <span className="font-mono">render_chart</span>
+ </div>
+ );
+ }
+
+ return <AgentChart spec={spec} />;
+}
+
function EmptyState() {
return (
<div className="flex h-full items-center justify-center">
diff --git a/web/src/components/agent/agent-chart.tsx b/web/src/components/agent/agent-chart.tsx
new file mode 100644
index 000000000..512b177ea
--- /dev/null
+++ b/web/src/components/agent/agent-chart.tsx
@@ -0,0 +1,198 @@
+'use client';
+
+import { useEffect, useRef, useState } from 'react';
+import {
+ Bar,
+ BarChart,
+ CartesianGrid,
+ Cell,
+ Legend,
+ Line,
+ LineChart,
+ Pie,
+ PieChart,
+ Tooltip,
+ XAxis,
+ YAxis,
+} from 'recharts';
+
+/**
+ * Spec returned by the `render_chart` agent tool. The schema in
+ * `web/src/lib/agent/tools.ts` validates the shape; this component
+ * trusts that contract and renders without re-validating.
+ *
+ * - line / bar charts use `xKey` + `series`
+ * - pie charts use `valueKey` + `labelKey`
+ */
+export interface AgentChartSpec {
+ type: 'line' | 'bar' | 'pie';
+ title?: string;
+ data: Array<Record<string, string | number>>;
+ xKey?: string;
+ series?: Array<{ key: string; label: string; color?: string }>;
+ valueKey?: string;
+ labelKey?: string;
+}
+
+// Palette pulled from globals.css (`--chart-1` … `--chart-5`). Wraps
+// around for charts with more than 5 series — fine in practice because
+// the agent rarely emits beyond that, and even if it does the wrap is
+// readable enough.
+const CHART_COLORS = [
+ 'var(--chart-2)',
+ 'var(--chart-3)',
+ 'var(--chart-1)',
+ 'var(--chart-4)',
+ 'var(--chart-5)',
+] as const;
+
+const CHART_HEIGHT = 260;
+
+/**
+ * Auto-sizing wrapper. ResponsiveContainer from recharts has known
+ * issues under React 19 (the dashboard `_charts.tsx` files all roll the
+ * same ResizeObserver replacement) so we mirror that pattern here.
+ */
+function ChartContainer({
+ height,
+ children,
+}: {
+ height: number;
+ children: (width: number) => React.ReactNode;
+}) {
+ const ref = useRef<HTMLDivElement>(null);
+ const [width, setWidth] = useState(0);
+
+ useEffect(() => {
+ const el = ref.current;
+ if (!el) return;
+ const update = () => setWidth(el.clientWidth);
+ update();
+ const ro = new ResizeObserver(update);
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, []);
+
+ return (
+ <div ref={ref} style={{ width: '100%', height }}>
+ {width > 0 && children(width)}
+ </div>
+ );
+}
+
+// All theme tokens in globals.css ship as full `oklch(...)` values, so
+// we reference them directly with `var(--…)`. Wrapping in `hsl(var(--…))`
+// produces invalid CSS and the browser falls back to default black,
+// which is unreadable in dark mode.
+const AXIS_TICK = { fill: 'var(--muted-foreground)', fontSize: 11 } as const;
+const TOOLTIP_STYLE = {
+ background: 'var(--card)',
+ border: '1px solid var(--border)',
+ borderRadius: '0.5rem',
+ fontSize: '0.75rem',
+ color: 'var(--foreground)',
+} as const;
+
+export function AgentChart({ spec }: { spec: AgentChartSpec }) {
+ return (
+ <div className="my-3 rounded-lg border bg-card p-4">
+ {spec.title && <p className="mb-3 text-xs font-medium text-foreground/80">{spec.title}</p>}
+ <ChartContainer height={CHART_HEIGHT}>{(width) => renderChart(spec, width)}</ChartContainer>
+ </div>
+ );
+}
+
+function renderChart(spec: AgentChartSpec, width: number) {
+ if (spec.type === 'pie') return renderPie(spec, width);
+ if (spec.type === 'bar') return renderBar(spec, width);
+ return renderLine(spec, width);
+}
+
+function renderLine(spec: AgentChartSpec, width: number) {
+ const xKey = spec.xKey ?? 'x';
+ const series = spec.series ?? [];
+ return (
+ <LineChart
+ width={width}
+ height={CHART_HEIGHT}
+ data={spec.data}
+ margin={{ top: 8, right: 16, bottom: 0, left: -8 }}
+ >
+ <CartesianGrid stroke="var(--border)" strokeDasharray="3 3" vertical={false} />
+ <XAxis dataKey={xKey} stroke="var(--border)" tick={AXIS_TICK} tickLine={false} />
+ <YAxis stroke="var(--border)" tick={AXIS_TICK} tickLine={false} axisLine={false} />
+ <Tooltip contentStyle={TOOLTIP_STYLE} cursor={{ stroke: 'var(--border)' }} />
+ {series.length > 1 && (
+ <Legend wrapperStyle={{ fontSize: 11, color: 'var(--muted-foreground)' }} />
+ )}
+ {series.map((s, i) => (
+ <Line
+ key={`${i}-${s.key}`}
+ type="monotone"
+ dataKey={s.key}
+ name={s.label}
+ stroke={s.color ?? CHART_COLORS[i % CHART_COLORS.length]}
+ strokeWidth={2}
+ dot={{ r: 3 }}
+ activeDot={{ r: 5 }}
+ />
+ ))}
+ </LineChart>
+ );
+}
+
+function renderBar(spec: AgentChartSpec, width: number) {
+ const xKey = spec.xKey ?? 'x';
+ const series = spec.series ?? [];
+ return (
+ <BarChart
+ width={width}
+ height={CHART_HEIGHT}
+ data={spec.data}
+ margin={{ top: 8, right: 16, bottom: 0, left: -8 }}
+ >
+ <CartesianGrid stroke="var(--border)" strokeDasharray="3 3" vertical={false} />
+ <XAxis dataKey={xKey} stroke="var(--border)" tick={AXIS_TICK} tickLine={false} />
+ <YAxis stroke="var(--border)" tick={AXIS_TICK} tickLine={false} axisLine={false} />
+ <Tooltip contentStyle={TOOLTIP_STYLE} cursor={{ fill: 'var(--muted)', opacity: 0.3 }} />
+ {series.length > 1 && (
+ <Legend wrapperStyle={{ fontSize: 11, color: 'var(--muted-foreground)' }} />
+ )}
+ {series.map((s, i) => (
+ <Bar
+ key={`${i}-${s.key}`}
+ dataKey={s.key}
+ name={s.label}
+ fill={s.color ?? CHART_COLORS[i % CHART_COLORS.length]}
+ radius={[4, 4, 0, 0]}
+ />
+ ))}
+ </BarChart>
+ );
+}
+
+function renderPie(spec: AgentChartSpec, width: number) {
+ const valueKey = spec.valueKey ?? 'value';
+ const labelKey = spec.labelKey ?? 'label';
+ const radius = Math.min(width, CHART_HEIGHT) / 2 - 24;
+ return (
+ <PieChart width={width} height={CHART_HEIGHT}>
+ <Tooltip contentStyle={TOOLTIP_STYLE} />
+ <Legend wrapperStyle={{ fontSize: 11, color: 'var(--muted-foreground)' }} />
+ <Pie
+ data={spec.data}
+ dataKey={valueKey}
+ nameKey={labelKey}
+ cx="50%"
+ cy="50%"
+ outerRadius={radius}
+ innerRadius={radius * 0.55}
+ paddingAngle={2}
+ >
+ {spec.data.map((_, i) => (
+ <Cell key={i} fill={CHART_COLORS[i % CHART_COLORS.length]} stroke="none" />
+ ))}
+ </Pie>
+ </PieChart>
+ );
+}
diff --git a/web/src/lib/actions/citations.ts b/web/src/lib/actions/citations.ts
index 840bab09c..de933d5c0 100644
--- a/web/src/lib/actions/citations.ts
+++ b/web/src/lib/actions/citations.ts
@@ -1,6 +1,7 @@
'use server';
import { createClient } from '@/lib/supabase/server';
+import { expandDateToEndOfDay } from '@/lib/dates';
import type { Citation } from '@/types';
import {
classifyDomain,
@@ -166,8 +167,9 @@ export async function getCitationsOverview(
.eq('brand_id', brandId);
const { from, to } = resolveDateRange(filters);
+ const expandedTo = expandDateToEndOfDay(to);
if (from) query = query.gte('created_at', from);
- if (to) query = query.lte('created_at', to);
+ if (expandedTo) query = query.lte('created_at', expandedTo);
if (filters.platforms && filters.platforms.length > 0) {
query = applyModelFilter(query, filters.platforms);
}
diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.ts
index 0c295703d..577af7d3b 100644
--- a/web/src/lib/actions/tracking.ts
+++ b/web/src/lib/actions/tracking.ts
@@ -1,6 +1,7 @@
'use server';
import { createClient } from '@/lib/supabase/server';
+import { expandDateToEndOfDay } from '@/lib/dates';
import type { PromptResult, AIPlatform, Sentiment, Citation, CompetitorMention } from '@/types';
/**
@@ -185,7 +186,8 @@ async function buildResultsQuery(
query = applyModelFilter(query, opts?.model);
if (opts?.region) query = query.eq('region', opts.region);
if (opts?.dateFrom) query = query.gte('created_at', opts.dateFrom);
- if (opts?.dateTo) query = query.lte('created_at', opts.dateTo);
+ const expandedDateTo = expandDateToEndOfDay(opts?.dateTo);
+ if (expandedDateTo) query = query.lte('created_at', expandedDateTo);
if (opts?.promptId) query = query.eq('prompt_id', opts.promptId);
if (opts?.topicId) {
@@ -443,7 +445,7 @@ export async function getInsightsSummary(
const { data: curData, error } = await supabase.rpc('insights_aggregates', {
...baseArgs,
p_date_from: opts?.dateFrom ?? null,
- p_date_to: opts?.dateTo ?? null,
+ p_date_to: expandDateToEndOfDay(opts?.dateTo) ?? null,
});
if (error) throw new Error(error.message);
@@ -508,7 +510,7 @@ export async function getInsightsSummary(
supabase.rpc('insights_aggregates', {
...baseArgs,
p_date_from: opts?.dateFrom ?? currentFrom.toISOString(),
- p_date_to: opts?.dateTo ?? null,
+ p_date_to: expandDateToEndOfDay(opts?.dateTo) ?? null,
}),
supabase.rpc('insights_aggregates', {
...baseArgs,
@@ -885,7 +887,7 @@ export async function getCompetitorComparison(
supabase.rpc('competitor_aggregates', {
...baseArgs,
p_date_from: opts?.dateFrom ?? null,
- p_date_to: opts?.dateTo ?? null,
+ p_date_to: expandDateToEndOfDay(opts?.dateTo) ?? null,
}),
]);
if (aggErr) throw new Error(aggErr.message);
@@ -917,7 +919,7 @@ export async function getCompetitorComparison(
supabase.rpc('competitor_aggregates', {
...baseArgs,
p_date_from: opts?.dateFrom ?? currentFrom.toISOString(),
- p_date_to: opts?.dateTo ?? null,
+ p_date_to: expandDateToEndOfDay(opts?.dateTo) ?? null,
}),
supabase.rpc('competitor_aggregates', {
...baseArgs,
@@ -1111,7 +1113,7 @@ export async function getShareOfVoiceData(
supabase.rpc('share_of_voice_aggregates', {
...baseArgs,
p_date_from: opts?.dateFrom ?? null,
- p_date_to: opts?.dateTo ?? null,
+ p_date_to: expandDateToEndOfDay(opts?.dateTo) ?? null,
}),
supabase.rpc('share_of_voice_aggregates', {
...baseArgs,
@@ -1224,7 +1226,8 @@ export async function getVisibilityTrend(
query = applyModelFilter(query, opts?.model);
if (opts?.region) query = query.eq('region', opts.region);
if (opts?.dateFrom) query = query.gte('created_at', opts.dateFrom);
- if (opts?.dateTo) query = query.lte('created_at', opts.dateTo);
+ const expandedDateTo = expandDateToEndOfDay(opts?.dateTo);
+ if (expandedDateTo) query = query.lte('created_at', expandedDateTo);
if (opts?.topicId) {
const { data: topicPrompts } = await supabase
diff --git a/web/src/lib/agent/system-prompt.ts b/web/src/lib/agent/system-prompt.ts
index ebdc4c870..aad81cfc6 100644
--- a/web/src/lib/agent/system-prompt.ts
+++ b/web/src/lib/agent/system-prompt.ts
@@ -40,6 +40,21 @@ You have these tools, all scoped to the authenticated user's organization:
- **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.
- **list_content_opportunities** — content gaps for a brand sorted by opportunity score. Use for "what should I write?" questions.
+- **render_chart** — render a chart inline in the chat (line / bar / pie). Call this *after* a data tool when the answer is meaningfully easier to read as a chart than as a sentence. See "Visualization" below.
+
+## Visualization (render_chart)
+
+Reach for \`render_chart\` when a chart would carry the answer better than prose:
+
+- **line** for "how has X changed over time?" — pair with \`get_visibility_trend\`. \`xKey\` is the date field; one or more series (visibility, mentions, citations).
+- **bar** for "compare X across N entities" — pair with \`get_competitor_comparison\` (brand vs competitors) or \`list_citations\` (source-type breakdown). \`xKey\` is the entity name; one series per metric.
+- **pie** for "what's the share of X?" — pair with \`get_competitor_comparison\`'s share of voice, or citation domain mix. \`valueKey\` + \`labelKey\`.
+
+Hard rules:
+
+- Always call the data tool first, then \`render_chart\`. Never call \`render_chart\` without real data in hand.
+- Pass the values straight from the data tool's response. Do not reformat numbers, invent missing rows, or "round to make the chart cleaner".
+- After the chart renders, write 1–2 sentences interpreting it: the slope, the leader, the surprise. Don't summarize a 12-point series row-by-row.
## Rules
diff --git a/web/src/lib/agent/tools.ts b/web/src/lib/agent/tools.ts
index 81eadcb5b..ea768cc7f 100644
--- a/web/src/lib/agent/tools.ts
+++ b/web/src/lib/agent/tools.ts
@@ -168,5 +168,51 @@ export function buildAgentTools(auth: McpAuthContext) {
limit: args.limit,
}),
}),
+
+ render_chart: tool({
+ description:
+ 'Render a chart inline in the chat. Call this AFTER you have the data from another tool (e.g. get_visibility_trend, get_competitor_comparison, list_citations) and you want to visualize it. Pick the chart type: "line" for time series (trends over dates), "bar" for cross-entity comparisons (brand vs competitors, source-type breakdown), "pie" for share-of-X distributions. Pass the data array straight from the previous tool result — never invent or reformat numbers. The tool just echoes the spec back; the UI renders the chart.',
+ inputSchema: z.object({
+ type: z
+ .enum(['line', 'bar', 'pie'])
+ .describe('line = time series, bar = cross-entity comparison, pie = share distribution'),
+ title: z
+ .string()
+ .max(120)
+ .optional()
+ .describe('Optional short title shown above the chart'),
+ data: z
+ .array(z.record(z.string(), z.union([z.string(), z.number()])))
+ .min(1)
+ .max(200)
+ .describe('Array of objects. Each row is one point/bar/slice. Max 200 rows.'),
+ xKey: z
+ .string()
+ .optional()
+ .describe(
+ 'For line / bar: the key on each row that holds the x-axis label (e.g. "date" or "competitor").',
+ ),
+ series: z
+ .array(
+ z.object({
+ key: z.string().describe('Key on each row that holds this series value.'),
+ label: z.string().describe('Human-readable name shown in legend / tooltip.'),
+ color: z.string().optional().describe('Optional hex / CSS color override.'),
+ }),
+ )
+ .max(5)
+ .optional()
+ .describe('For line / bar: one entry per measured series. Up to 5.'),
+ valueKey: z
+ .string()
+ .optional()
+ .describe('For pie: the key on each row that holds the numeric slice value.'),
+ labelKey: z
+ .string()
+ .optional()
+ .describe('For pie: the key on each row that holds the slice label.'),
+ }),
+ execute: async (args) => args,
+ }),
};
}
diff --git a/web/src/lib/dates.ts b/web/src/lib/dates.ts
new file mode 100644
index 000000000..cf4945647
--- /dev/null
+++ b/web/src/lib/dates.ts
@@ -0,0 +1,16 @@
+/**
+ * Treat a bare `YYYY-MM-DD` dateTo as end-of-day in UTC. Postgres parses
+ * a bare date string as 00:00:00 of that day, so `<= '2026-05-31'`
+ * silently excludes everything that happened on May 31 itself. Callers
+ * — date pickers, the in-product agent's tools, the MCP REST surface —
+ * pass bare dates routinely; this helper expands them to `23:59:59.999Z`
+ * so the rest of the day is included.
+ *
+ * Full ISO timestamps (`2026-05-31T15:30:00Z`) are passed through as-is
+ * so callers that want a strict upper bound still get one.
+ */
+export function expandDateToEndOfDay(d?: string | null): string | undefined {
+ if (!d) return undefined;
+ if (/^\d{4}-\d{2}-\d{2}$/.test(d)) return `${d}T23:59:59.999Z`;
+ return d;
+}
diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.ts
index 46ff7968d..18f5ed4cf 100644
--- a/web/src/lib/mcp/data.ts
+++ b/web/src/lib/mcp/data.ts
@@ -9,6 +9,7 @@ import {
type SourceCategory,
} from '@/lib/citations/classify';
import { classifyArticleType } from '@/lib/citations/article-type';
+import { expandDateToEndOfDay } from '@/lib/dates';
/**
* Pure data-fetch functions shared by the MCP route and the parallel REST
@@ -90,7 +91,8 @@ export async function getVisibilitySummaryFor(
.eq('brand_id', params.brandId);
if (params.dateFrom) query = query.gte('created_at', params.dateFrom);
- if (params.dateTo) query = query.lte('created_at', params.dateTo);
+ const expandedDateTo = expandDateToEndOfDay(params.dateTo);
+ if (expandedDateTo) query = query.lte('created_at', expandedDateTo);
if (params.region) query = query.eq('region', params.region);
if (params.model) {
const list = params.model
@@ -732,7 +734,7 @@ export async function getCompetitorComparisonFor(
p_models: p_models && p_models.length > 0 ? p_models : null,
p_region: params.region ?? null,
p_date_from: params.dateFrom ?? null,
- p_date_to: params.dateTo ?? null,
+ p_date_to: expandDateToEndOfDay(params.dateTo) ?? null,
p_prompt_id: null as string | null,
p_topic_id: params.topicId ?? null,
};
@@ -895,7 +897,8 @@ export async function listCitationsFor(
.eq('brand_id', params.brandId);
if (params.dateFrom) query = query.gte('created_at', params.dateFrom);
- if (params.dateTo) query = query.lte('created_at', params.dateTo);
+ const expandedDateTo = expandDateToEndOfDay(params.dateTo);
+ if (expandedDateTo) query = query.lte('created_at', expandedDateTo);
if (params.region) query = query.eq('region', params.region);
if (params.model) {
const list = params.model
@@ -1166,7 +1169,7 @@ export async function getVisibilityTrendFor(
p_models: p_models && p_models.length > 0 ? p_models : null,
p_region: params.region ?? null,
p_date_from: params.dateFrom ?? null,
- p_date_to: params.dateTo ?? null,
+ p_date_to: expandDateToEndOfDay(params.dateTo) ?? null,
p_topic_id: params.topicId ?? null,
p_granularity: granularity,
});