Skip to content

armgit / umami

Public Imported from GitHub
0

Umami is a privacy-first web and product analytics platform. Traffic, campaigns, behavior, conversions, and revenue in one place. No cookies, no surveillance, self-hosted or in the cloud.

Add MCP tools for funnels, goals, segments, annotations, and performance metrics

Mike Cao97ba22623cbe
diff --git a/packages/mcp/README.md b/packages/mcp/README.md
index 7036ca251..53048c65f 100644
--- a/packages/mcp/README.md
+++ b/packages/mcp/README.md
@@ -23,12 +23,17 @@ user/team permission checks as the web app.
| `get_event_properties` | Custom event property names, or the values of one property. |
| `get_sessions` | Visitor sessions (paginated). |
| `get_session_stats` | Session-level totals: visitors, visits, pageviews, events, countries. |
+| `get_annotations` | Dated notes on the timeline (launches, campaigns) to explain changes. |
+| `list_segments` | Saved segments and cohorts; pass IDs via `filters.segment` / `.cohort`. |
| `get_session` | One session with its activity timeline and properties. |
-| `run_funnel` | Conversion funnel across page/event steps. |
+| `list_funnels` | Saved funnels with their steps (get a `funnelId` for `run_funnel`). |
+| `run_funnel` | Conversion funnel from a saved `funnelId` or ad-hoc page/event steps. |
+| `get_goals` | Saved goals with conversions, visitors and rate for a range. |
| `run_journey` | Most common paths visitors take. |
| `run_retention` | Cohort retention table. |
| `run_attribution` | First/last-click attribution for a conversion. |
| `get_revenue` | Revenue totals, series and breakdowns. |
+| `get_performance` | Core Web Vitals (LCP, INP, CLS, FCP, TTFB) percentiles, trend, breakdown. |
All tools are read-only. Dates are ISO 8601; results are paginated with a hard cap on page size.
@@ -116,6 +121,10 @@ For Cloud stdio, set `UMAMI_API_KEY` and omit `UMAMI_URL` and `UMAMI_API_TOKEN`:
- Show sessions for user abc123.
- Which pricing plans did people select in the checkout event last month?
- How many signup events fired each day this week?
+- Run my checkout funnel for last month.
+- How are we doing against our goals this quarter?
+- Which pages have the worst LCP on mobile?
+- What happened on the day traffic spiked?
## Programmatic use
diff --git a/packages/mcp/src/lib/filters.ts b/packages/mcp/src/lib/filters.ts
index 423d322a5..e8fe129d9 100644
--- a/packages/mcp/src/lib/filters.ts
+++ b/packages/mcp/src/lib/filters.ts
@@ -29,7 +29,12 @@ export const filtersSchema = z
utmCampaign: filterValue.optional(),
utmContent: filterValue.optional(),
utmTerm: filterValue.optional(),
- segment: z.string().uuid().optional().describe('Saved segment ID to apply.'),
+ segment: z
+ .string()
+ .uuid()
+ .optional()
+ .describe('Saved segment ID to apply (see list_segments).'),
+ cohort: z.string().uuid().optional().describe('Saved cohort ID to apply (see list_segments).'),
match: z
.enum(['all', 'any'])
.optional()
diff --git a/packages/mcp/src/server.test.ts b/packages/mcp/src/server.test.ts
index d24649e25..cb0a4292b 100644
--- a/packages/mcp/src/server.test.ts
+++ b/packages/mcp/src/server.test.ts
@@ -7,6 +7,8 @@ import { createUmamiMcpServer } from './server';
const WEBSITE_ID = '6f2a7e0e-2b0f-4b3f-9f0a-1234567890ab';
const SESSION_ID = '0b3b6c2e-1f4a-4d0c-9a5e-abcdefabcdef';
+const FUNNEL_ID = '1a2b3c4d-0000-4000-8000-000000000001';
+const GOAL_ID = '1a2b3c4d-0000-4000-8000-000000000002';
type Handler = (url: URL, init?: RequestInit) => { status?: number; body: unknown };
@@ -267,6 +269,137 @@ describe('createUmamiMcpServer', () => {
};
}
+ if (path === `/api/websites/${WEBSITE_ID}/funnels`) {
+ return {
+ body: {
+ data: [
+ {
+ id: FUNNEL_ID,
+ name: 'Checkout',
+ description: '',
+ parameters: {
+ window: 30,
+ steps: [
+ { type: 'path', value: '/cart' },
+ { type: 'event', value: 'purchase' },
+ ],
+ },
+ createdAt: '2024-01-01T00:00:00.000Z',
+ },
+ ],
+ count: 1,
+ page: 1,
+ pageSize: 20,
+ },
+ };
+ }
+
+ if (path === `/api/websites/${WEBSITE_ID}/funnels/${FUNNEL_ID}/stats`) {
+ return {
+ body: [
+ {
+ type: 'path',
+ value: '/cart',
+ visitors: 50,
+ previous: 0,
+ dropped: 0,
+ dropoff: 0,
+ remaining: 1,
+ },
+ {
+ type: 'event',
+ value: 'purchase',
+ visitors: 5,
+ previous: 50,
+ dropped: 45,
+ dropoff: 0.9,
+ remaining: 0.1,
+ },
+ ],
+ };
+ }
+
+ if (path === `/api/websites/${WEBSITE_ID}/goals`) {
+ return {
+ body: {
+ data: [
+ {
+ id: GOAL_ID,
+ name: 'Signups',
+ description: '',
+ parameters: { type: 'event', value: 'signup' },
+ createdAt: null,
+ },
+ ],
+ count: 1,
+ page: 1,
+ pageSize: 20,
+ },
+ };
+ }
+
+ if (path === `/api/websites/${WEBSITE_ID}/goals/${GOAL_ID}/stats`) {
+ return { body: { num: 8, total: 40 } };
+ }
+
+ if (path === `/api/websites/${WEBSITE_ID}/segments`) {
+ const type = url.searchParams.get('type');
+ return {
+ body: {
+ data: [
+ {
+ id: `seg-${type}`,
+ name: `My ${type}`,
+ type,
+ parameters: { filters: [] },
+ createdAt: null,
+ },
+ ],
+ count: 1,
+ },
+ };
+ }
+
+ if (path === `/api/websites/${WEBSITE_ID}/annotations`) {
+ return {
+ body: {
+ data: [
+ {
+ id: 'a1',
+ date: '2024-01-05T00:00:00.000Z',
+ allDay: true,
+ note: 'Launched v2',
+ createdAt: null,
+ },
+ ],
+ count: 1,
+ page: 1,
+ pageSize: 20,
+ },
+ };
+ }
+
+ if (path === `/api/websites/${WEBSITE_ID}/performance/stats`) {
+ return {
+ body: {
+ lcp: { p50: 1200, p75: 2100, p95: 4000 },
+ inp: { p50: 80, p75: 150, p95: 400 },
+ cls: { p50: 0.01, p75: 0.05, p95: 0.2 },
+ fcp: { p50: 900, p75: 1500, p95: 3000 },
+ ttfb: { p50: 200, p75: 400, p95: 900 },
+ count: 500,
+ },
+ };
+ }
+
+ if (path === `/api/websites/${WEBSITE_ID}/performance/chart`) {
+ return { body: { chart: [{ t: '2024-01-01', p50: 1100, p75: 2000, p95: 3900 }] } };
+ }
+
+ if (path === `/api/websites/${WEBSITE_ID}/performance/metrics`) {
+ return { body: [{ name: '/slow', p50: 3000, p75: 4500, p95: 8000, count: 40 }] };
+ }
+
if (path.startsWith('/api/websites/')) {
return {
status: 401,
@@ -309,7 +442,12 @@ describe('createUmamiMcpServer', () => {
'get_sessions',
'get_session_stats',
'get_session',
+ 'list_funnels',
'run_funnel',
+ 'get_goals',
+ 'get_annotations',
+ 'list_segments',
+ 'get_performance',
'run_journey',
'run_retention',
'run_attribution',
@@ -591,6 +729,184 @@ describe('createUmamiMcpServer', () => {
expect(harness.calls[0].url.searchParams.get('dataType')).toBe('1');
});
+ test('list_funnels and run_funnel with a saved funnelId', async () => {
+ const listed = await harness.client.callTool({
+ name: 'list_funnels',
+ arguments: { websiteId: WEBSITE_ID },
+ });
+
+ expect(listed.isError).toBeFalsy();
+ expect(listed.structuredContent).toMatchObject({
+ funnels: [
+ {
+ id: FUNNEL_ID,
+ name: 'Checkout',
+ windowMinutes: 30,
+ steps: [
+ { step: 1, type: 'path', value: '/cart' },
+ { step: 2, type: 'event', value: 'purchase' },
+ ],
+ },
+ ],
+ count: 1,
+ });
+
+ harness.calls.length = 0;
+
+ const ran = await harness.client.callTool({
+ name: 'run_funnel',
+ arguments: { websiteId: WEBSITE_ID, startAt: '2024-01-01', funnelId: FUNNEL_ID },
+ });
+
+ expect(ran.isError).toBeFalsy();
+ expect(ran.structuredContent).toMatchObject({
+ funnelId: FUNNEL_ID,
+ steps: [
+ { step: 1, value: '/cart', visitors: 50 },
+ { step: 2, value: 'purchase', visitors: 5, dropoffRate: 0.9 },
+ ],
+ });
+ expect(harness.calls[0].url.pathname).toBe(
+ `/api/websites/${WEBSITE_ID}/funnels/${FUNNEL_ID}/stats`,
+ );
+
+ const both = await harness.client.callTool({
+ name: 'run_funnel',
+ arguments: {
+ websiteId: WEBSITE_ID,
+ startAt: '2024-01-01',
+ funnelId: FUNNEL_ID,
+ steps: [
+ { type: 'path', value: '/' },
+ { type: 'event', value: 'signup' },
+ ],
+ },
+ });
+
+ expect(both.isError).toBe(true);
+
+ const neither = await harness.client.callTool({
+ name: 'run_funnel',
+ arguments: { websiteId: WEBSITE_ID, startAt: '2024-01-01' },
+ });
+
+ expect(neither.isError).toBe(true);
+ });
+
+ test('get_goals lists goals and computes results when a range is given', async () => {
+ const listed = await harness.client.callTool({
+ name: 'get_goals',
+ arguments: { websiteId: WEBSITE_ID },
+ });
+
+ expect(listed.isError).toBeFalsy();
+ expect(listed.structuredContent).toMatchObject({
+ goals: [{ id: GOAL_ID, name: 'Signups', type: 'event', value: 'signup' }],
+ });
+ expect(
+ (listed.structuredContent as { goals: Record<string, unknown>[] }).goals[0].results,
+ ).toBeUndefined();
+ expect(harness.calls).toHaveLength(1);
+
+ harness.calls.length = 0;
+
+ const withStats = await harness.client.callTool({
+ name: 'get_goals',
+ arguments: { websiteId: WEBSITE_ID, startAt: '2024-01-01', endAt: '2024-02-01' },
+ });
+
+ expect(withStats.isError).toBeFalsy();
+ expect(withStats.structuredContent).toMatchObject({
+ goals: [{ id: GOAL_ID, results: { conversions: 8, visitors: 40, conversionRate: 20 } }],
+ });
+ expect(harness.calls.map(call => call.url.pathname)).toEqual([
+ `/api/websites/${WEBSITE_ID}/goals`,
+ `/api/websites/${WEBSITE_ID}/goals/${GOAL_ID}/stats`,
+ ]);
+ });
+
+ test('list_segments fetches segments and cohorts', async () => {
+ const result = await harness.client.callTool({
+ name: 'list_segments',
+ arguments: { websiteId: WEBSITE_ID },
+ });
+
+ expect(result.isError).toBeFalsy();
+ expect(result.structuredContent).toMatchObject({
+ segments: [
+ { id: 'seg-segment', type: 'segment' },
+ { id: 'seg-cohort', type: 'cohort' },
+ ],
+ });
+ expect(harness.calls.map(call => call.url.searchParams.get('type')).sort()).toEqual([
+ 'cohort',
+ 'segment',
+ ]);
+ });
+
+ test('get_annotations passes the range and paginates', async () => {
+ const result = await harness.client.callTool({
+ name: 'get_annotations',
+ arguments: {
+ websiteId: WEBSITE_ID,
+ startAt: '2024-01-01',
+ endAt: '2024-02-01',
+ search: 'v2',
+ },
+ });
+
+ expect(result.isError).toBeFalsy();
+ expect(result.structuredContent).toMatchObject({
+ annotations: [
+ { id: 'a1', date: '2024-01-05T00:00:00.000Z', note: 'Launched v2', allDay: true },
+ ],
+ count: 1,
+ hasMore: false,
+ });
+
+ const url = harness.calls[0].url;
+
+ expect(url.searchParams.get('startAt')).toBe(String(Date.parse('2024-01-01')));
+ expect(url.searchParams.get('search')).toBe('v2');
+ });
+
+ test('get_performance returns vitals, and series + breakdown on request', async () => {
+ const summary = await harness.client.callTool({
+ name: 'get_performance',
+ arguments: { websiteId: WEBSITE_ID, startAt: '2024-01-01' },
+ });
+
+ expect(summary.isError).toBeFalsy();
+ expect(summary.structuredContent).toMatchObject({
+ measurements: 500,
+ vitals: { lcp: { p75: 2100 }, cls: { p75: 0.05 } },
+ });
+ expect(summary.structuredContent).not.toHaveProperty('series');
+ expect(harness.calls).toHaveLength(1);
+
+ harness.calls.length = 0;
+
+ const detailed = await harness.client.callTool({
+ name: 'get_performance',
+ arguments: { websiteId: WEBSITE_ID, startAt: '2024-01-01', breakdown: 'path', limit: 10 },
+ });
+
+ expect(detailed.isError).toBeFalsy();
+ expect(detailed.structuredContent).toMatchObject({
+ series: { metric: 'lcp', points: [{ date: '2024-01-01', p75: 2000 }] },
+ breakdown: {
+ metric: 'lcp',
+ type: 'path',
+ rows: [{ name: '/slow', p75: 4500, measurements: 40 }],
+ },
+ });
+ expect(harness.calls.map(call => call.url.pathname).sort()).toEqual([
+ `/api/websites/${WEBSITE_ID}/performance/chart`,
+ `/api/websites/${WEBSITE_ID}/performance/metrics`,
+ `/api/websites/${WEBSITE_ID}/performance/stats`,
+ ]);
+ });
+
test('run_funnel sends structured criteria with GET', async () => {
const result = await harness.client.callTool({
name: 'run_funnel',
diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.ts
index e4985e467..629bc470f 100644
--- a/packages/mcp/src/server.ts
+++ b/packages/mcp/src/server.ts
@@ -12,7 +12,8 @@ export const SERVER_INSTRUCTIONS = `Umami is a privacy-focused web analytics pla
Workflow:
1. Call list_websites to find the websiteId for the site the user is asking about (match by name or domain).
2. If unsure what dates have data, call get_website_daterange first.
-3. Use get_website_stats for totals, get_website_traffic for trends over time, get_website_metrics for rankings (top pages, referrers, countries, browsers, campaigns, events), get_realtime for current visitors, get_event_stats / get_event_series for custom event totals and trends, get_event_properties to explore the custom data sent with events, get_session_stats for session counts, get_events / get_sessions / get_session to inspect individual activity, and run_funnel / run_journey / run_retention / run_attribution / get_revenue for reports.
+3. Use get_website_stats for totals, get_website_traffic for trends over time, get_website_metrics for rankings (top pages, referrers, countries, browsers, campaigns, events), get_realtime for current visitors, get_event_stats / get_event_series for custom event totals and trends, get_event_properties to explore the custom data sent with events, get_session_stats for session counts, get_events / get_sessions / get_session to inspect individual activity, get_annotations to explain spikes with the team's dated notes, get_performance for Core Web Vitals, and run_funnel / run_journey / run_retention / run_attribution / get_revenue / get_goals for reports.
+4. Saved definitions: list_funnels finds funnelIds for run_funnel, get_goals reports saved goals, and list_segments finds segment/cohort IDs to pass in filters.
Dates are ISO 8601 strings; endAt defaults to now. Results are paginated where noted — request another page rather than a huge pageSize. All tools are read-only.`;
diff --git a/packages/mcp/src/tools/annotations.ts b/packages/mcp/src/tools/annotations.ts
new file mode 100644
index 000000000..ec60e9f1b
--- /dev/null
+++ b/packages/mcp/src/tools/annotations.ts
@@ -0,0 +1,69 @@
+import { z } from 'zod';
+import { isoTimestamp, parseDateRange, toIso } from '../lib/dates';
+import { clamp, DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE, pageInfo } from '../lib/limits';
+import { defineTool } from '../lib/tool';
+
+interface AnnotationRow {
+ id?: string;
+ date?: string | null;
+ allDay?: boolean;
+ note?: string;
+ createdAt?: string | null;
+}
+
+export const getAnnotations = defineTool({
+ name: 'get_annotations',
+ title: 'Get annotations',
+ description:
+ 'Lists the dated notes a team has added to a website\'s timeline, such as "launched v2", "ran newsletter campaign" ' +
+ 'or "outage". Use these to explain spikes or dips you see in get_website_traffic. Optionally restrict to a date ' +
+ 'range or search the note text. Results are paginated. Requires a websiteId from list_websites.',
+ inputSchema: z.object({
+ websiteId: z.string().uuid().describe('Website ID from list_websites.'),
+ startAt: isoTimestamp.optional().describe('Only annotations on or after this date.'),
+ endAt: isoTimestamp
+ .optional()
+ .describe('Only annotations on or before this date. Defaults to now when startAt is set.'),
+ search: z.string().optional().describe('Free-text search of the note.'),
+ page: z.number().int().positive().optional().describe('Page number, starting at 1.'),
+ pageSize: z
+ .number()
+ .int()
+ .positive()
+ .max(MAX_PAGE_SIZE)
+ .optional()
+ .describe(`Results per page (default ${DEFAULT_PAGE_SIZE}, max ${MAX_PAGE_SIZE}).`),
+ }),
+ async handler(input, { client }) {
+ const range = input.startAt
+ ? parseDateRange({ startAt: input.startAt, endAt: input.endAt })
+ : null;
+ const result = (await client.getWebsiteAnnotations({
+ websiteId: input.websiteId,
+ ...(range ? { startAt: range.startAt, endAt: range.endAt } : {}),
+ search: input.search,
+ page: input.page ?? 1,
+ pageSize: clamp(input.pageSize, DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE),
+ })) as { data?: AnnotationRow[]; count?: number; page?: number; pageSize?: number };
+
+ return {
+ websiteId: input.websiteId,
+ ...(range
+ ? {
+ range: {
+ startAt: new Date(range.startAt).toISOString(),
+ endAt: new Date(range.endAt).toISOString(),
+ },
+ }
+ : {}),
+ annotations: (result?.data ?? []).map(row => ({
+ id: row.id,
+ date: toIso(row.date),
+ allDay: row.allDay ?? true,
+ note: row.note ?? '',
+ createdAt: toIso(row.createdAt),
+ })),
+ ...pageInfo(result ?? {}),
+ };
+ },
+});
diff --git a/packages/mcp/src/tools/funnels.ts b/packages/mcp/src/tools/funnels.ts
new file mode 100644
index 000000000..c321d15ba
--- /dev/null
+++ b/packages/mcp/src/tools/funnels.ts
@@ -0,0 +1,61 @@
+import { z } from 'zod';
+import { toIso } from '../lib/dates';
+import { clamp, DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE, pageInfo } from '../lib/limits';
+import { defineTool } from '../lib/tool';
+
+interface FunnelRow {
+ id?: string;
+ name?: string;
+ description?: string;
+ parameters?: {
+ window?: number;
+ steps?: { type?: string; value?: string }[];
+ } | null;
+ createdAt?: string | null;
+}
+
+export const listFunnels = defineTool({
+ name: 'list_funnels',
+ title: 'List saved funnels',
+ description:
+ "Lists the funnel reports saved for a website, including each funnel's ordered steps and time window. " +
+ 'When the user refers to a funnel by name ("the checkout funnel"), call this to find its funnelId, then pass ' +
+ 'that funnelId to run_funnel to get the conversion numbers. Requires a websiteId from list_websites.',
+ inputSchema: z.object({
+ websiteId: z.string().uuid().describe('Website ID from list_websites.'),
+ search: z.string().optional().describe('Filter funnels by name or description.'),
+ page: z.number().int().positive().optional().describe('Page number, starting at 1.'),
+ pageSize: z
+ .number()
+ .int()
+ .positive()
+ .max(MAX_PAGE_SIZE)
+ .optional()
+ .describe(`Results per page (default ${DEFAULT_PAGE_SIZE}, max ${MAX_PAGE_SIZE}).`),
+ }),
+ async handler(input, { client }) {
+ const result = (await client.getWebsiteFunnels({
+ websiteId: input.websiteId,
+ search: input.search,
+ page: input.page ?? 1,
+ pageSize: clamp(input.pageSize, DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE),
+ })) as { data?: FunnelRow[]; count?: number; page?: number; pageSize?: number };
+
+ return {
+ websiteId: input.websiteId,
+ funnels: (result?.data ?? []).map(row => ({
+ id: row.id,
+ name: row.name,
+ description: row.description || null,
+ windowMinutes: row.parameters?.window ?? null,
+ steps: (row.parameters?.steps ?? []).map((step, index) => ({
+ step: index + 1,
+ type: step.type,
+ value: step.value,
+ })),
+ createdAt: toIso(row.createdAt),
+ })),
+ ...pageInfo(result ?? {}),
+ };
+ },
+});
diff --git a/packages/mcp/src/tools/goals.ts b/packages/mcp/src/tools/goals.ts
new file mode 100644
index 000000000..505cdca1a
--- /dev/null
+++ b/packages/mcp/src/tools/goals.ts
@@ -0,0 +1,110 @@
+import { z } from 'zod';
+import { isoTimestamp, parseDateRange, toIso } from '../lib/dates';
+import { filtersSchema, toFilterParams } from '../lib/filters';
+import { clamp, DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE, pageInfo } from '../lib/limits';
+import { defineTool } from '../lib/tool';
+
+interface GoalRow {
+ id?: string;
+ name?: string;
+ description?: string;
+ parameters?: { type?: string; value?: string } | null;
+ createdAt?: string | null;
+}
+
+interface GoalStats {
+ num?: number;
+ total?: number;
+}
+
+export const getGoals = defineTool({
+ name: 'get_goals',
+ title: 'Get saved goals',
+ description:
+ 'Lists the goals saved for a website (a goal is a target page path or custom event, e.g. "visit /thank-you" or ' +
+ '"fire signup"). Pass startAt (and optionally endAt) to also compute each goal\'s results in that range: how many ' +
+ 'visitors converted, the total visitors, and the conversion rate. Use "goalId" to check a single goal. ' +
+ 'Use this for "how are we doing against our goals?" questions. Requires a websiteId from list_websites.',
+ inputSchema: z.object({
+ websiteId: z.string().uuid().describe('Website ID from list_websites.'),
+ goalId: z.string().uuid().optional().describe('Only return this goal.'),
+ startAt: isoTimestamp
+ .optional()
+ .describe('Start of the range for goal results. Omit to only list goals.'),
+ endAt: isoTimestamp.optional().describe('End of the range (inclusive). Defaults to now.'),
+ search: z.string().optional().describe('Filter goals by name or description.'),
+ page: z.number().int().positive().optional().describe('Page number, starting at 1.'),
+ pageSize: z
+ .number()
+ .int()
+ .positive()
+ .max(MAX_PAGE_SIZE)
+ .optional()
+ .describe(`Results per page (default ${DEFAULT_PAGE_SIZE}, max ${MAX_PAGE_SIZE}).`),
+ filters: filtersSchema.optional(),
+ }),
+ async handler(input, { client }) {
+ const result = (await client.getWebsiteGoals({
+ websiteId: input.websiteId,
+ search: input.search,
+ page: input.page ?? 1,
+ pageSize: clamp(input.pageSize, DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE),
+ })) as { data?: GoalRow[]; count?: number; page?: number; pageSize?: number };
+
+ const rows = (result?.data ?? []).filter(row => !input.goalId || row.id === input.goalId);
+ const range = input.startAt
+ ? parseDateRange({ startAt: input.startAt, endAt: input.endAt })
+ : null;
+ const filters = toFilterParams(input.filters);
+
+ const goals = await Promise.all(
+ rows.map(async row => {
+ const goal = {
+ id: row.id,
+ name: row.name,
+ description: row.description || null,
+ type: row.parameters?.type ?? null,
+ value: row.parameters?.value ?? null,
+ createdAt: toIso(row.createdAt),
+ };
+
+ if (!range || !row.id) {
+ return goal;
+ }
+
+ const stats = (await client.getWebsiteSavedGoalStats({
+ websiteId: input.websiteId,
+ goalId: row.id,
+ startAt: range.startAt,
+ endAt: range.endAt,
+ ...filters,
+ })) as GoalStats;
+ const conversions = Number(stats?.num ?? 0);
+ const visitors = Number(stats?.total ?? 0);
+
+ return {
+ ...goal,
+ results: {
+ conversions,
+ visitors,
+ conversionRate: visitors ? Math.round((conversions / visitors) * 1000) / 10 : 0,
+ },
+ };
+ }),
+ );
+
+ return {
+ websiteId: input.websiteId,
+ ...(range
+ ? {
+ range: {
+ startAt: new Date(range.startAt).toISOString(),
+ endAt: new Date(range.endAt).toISOString(),
+ },
+ }
+ : {}),
+ goals,
+ ...pageInfo(result ?? {}),
+ };
+ },
+});
diff --git a/packages/mcp/src/tools/index.ts b/packages/mcp/src/tools/index.ts
index cac2cfa94..cebf58a0c 100644
--- a/packages/mcp/src/tools/index.ts
+++ b/packages/mcp/src/tools/index.ts
@@ -1,11 +1,16 @@
import type { AnyToolDefinition } from '../lib/tool';
+import { getAnnotations } from './annotations';
import { getWebsiteDateRange } from './daterange';
import { getEventProperties } from './event-properties';
import { getEventSeries, getEventStats } from './event-stats';
import { getEvents } from './events';
+import { listFunnels } from './funnels';
+import { getGoals } from './goals';
import { getWebsiteMetrics } from './metrics';
+import { getPerformance } from './performance';
import { getRealtime } from './realtime';
import { getRevenue, runAttribution, runFunnel, runJourney, runRetention } from './reports';
+import { listSegments } from './segments';
import { getSession } from './session';
import { getSessionStats } from './session-stats';
import { getSessions } from './sessions';
@@ -28,24 +33,32 @@ export const coreTools: AnyToolDefinition[] = [
getSessions,
getSessionStats,
getSession,
+ getAnnotations,
+ listSegments,
];
/** Higher-level report tools. */
export const reportTools: AnyToolDefinition[] = [
+ listFunnels,
runFunnel,
+ getGoals,
runJourney,
runRetention,
runAttribution,
getRevenue,
+ getPerformance,
];
export const allTools: AnyToolDefinition[] = [...coreTools, ...reportTools];
export {
+ getAnnotations,
getEventProperties,
getEventSeries,
getEventStats,
getEvents,
+ getGoals,
+ getPerformance,
getRealtime,
getRevenue,
getSession,
@@ -55,6 +68,8 @@ export {
getWebsiteMetrics,
getWebsiteStats,
getWebsiteTraffic,
+ listFunnels,
+ listSegments,
listWebsites,
runAttribution,
runFunnel,
diff --git a/packages/mcp/src/tools/performance.ts b/packages/mcp/src/tools/performance.ts
new file mode 100644
index 000000000..a8c9e877b
--- /dev/null
+++ b/packages/mcp/src/tools/performance.ts
@@ -0,0 +1,136 @@
+import { z } from 'zod';
+import { dateRangeInput, parseDateRange, timeUnit, timezone } from '../lib/dates';
+import { filtersSchema, toFilterParams } from '../lib/filters';
+import { clamp, DEFAULT_METRIC_LIMIT, MAX_METRIC_LIMIT } from '../lib/limits';
+import { defineTool } from '../lib/tool';
+
+const METRICS = ['lcp', 'inp', 'cls', 'fcp', 'ttfb'] as const;
+
+const metricInput = z
+ .enum(METRICS)
+ .describe(
+ 'Web vital: "lcp" Largest Contentful Paint (ms), "inp" Interaction to Next Paint (ms), "cls" Cumulative Layout Shift (unitless score), "fcp" First Contentful Paint (ms), "ttfb" Time to First Byte (ms).',
+ );
+
+interface Percentiles {
+ p50?: number;
+ p75?: number;
+ p95?: number;
+}
+
+interface Summary extends Partial<Record<(typeof METRICS)[number], Percentiles>> {
+ count?: number;
+}
+
+interface ChartRow extends Percentiles {
+ t: string;
+}
+
+interface MetricRow extends Percentiles {
+ name?: string;
+ count?: number;
+}
+
+function percentiles(value: Percentiles | undefined) {
+ return {
+ p50: Number(value?.p50 ?? 0),
+ p75: Number(value?.p75 ?? 0),
+ p95: Number(value?.p95 ?? 0),
+ };
+}
+
+export const getPerformance = defineTool({
+ name: 'get_performance',
+ title: 'Get web vitals performance',
+ description:
+ 'Returns Core Web Vitals collected from real visitors over a time range: p50/p75/p95 for LCP, INP, CLS, FCP and TTFB ' +
+ 'plus the number of measurements. Google treats p75 as the score to judge by (good LCP ≤ 2500ms, INP ≤ 200ms, CLS ≤ 0.1). ' +
+ 'Set "metric" to also get that metric as a time series, and "breakdown" to rank pages, devices or browsers by that metric ' +
+ 'to find what is slow. Requires a websiteId from list_websites.',
+ inputSchema: z.object({
+ websiteId: z.string().uuid().describe('Website ID from list_websites.'),
+ ...dateRangeInput,
+ metric: metricInput
+ .optional()
+ .describe(
+ 'Metric for the time series and breakdown. Defaults to "lcp" when breakdown is set.',
+ ),
+ breakdown: z
+ .enum(['path', 'title', 'device', 'browser'])
+ .optional()
+ .describe('Rank this dimension by the chosen metric (slowest first by p75).'),
+ limit: z
+ .number()
+ .int()
+ .positive()
+ .max(MAX_METRIC_LIMIT)
+ .optional()
+ .describe(
+ `Rows in the breakdown (default ${DEFAULT_METRIC_LIMIT}, max ${MAX_METRIC_LIMIT}).`,
+ ),
+ unit: timeUnit.optional(),
+ timezone: timezone.optional(),
+ filters: filtersSchema.optional(),
+ }),
+ async handler(input, { client }) {
+ const range = parseDateRange(input);
+ const common = {
+ websiteId: input.websiteId,
+ startAt: range.startAt,
+ endAt: range.endAt,
+ timezone: input.timezone ?? 'UTC',
+ unit: input.unit ?? 'day',
+ ...toFilterParams(input.filters),
+ };
+ const metric = input.metric ?? (input.breakdown ? 'lcp' : undefined);
+
+ const [summary, chart, breakdown] = await Promise.all([
+ client.getWebsitePerformanceStats(common) as Promise<Summary>,
+ metric
+ ? (client.getWebsitePerformanceChart({ ...common, metric }) as Promise<{
+ chart?: ChartRow[];
+ }>)
+ : Promise.resolve(null),
+ input.breakdown
+ ? (client.getWebsitePerformanceMetrics({
+ ...common,
+ metric,
+ type: input.breakdown,
+ limit: clamp(input.limit, DEFAULT_METRIC_LIMIT, MAX_METRIC_LIMIT),
+ }) as Promise<MetricRow[]>)
+ : Promise.resolve(null),
+ ]);
+
+ return {
+ websiteId: input.websiteId,
+ range: {
+ startAt: new Date(range.startAt).toISOString(),
+ endAt: new Date(range.endAt).toISOString(),
+ },
+ measurements: Number(summary?.count ?? 0),
+ vitals: Object.fromEntries(METRICS.map(name => [name, percentiles(summary?.[name])])),
+ ...(metric && chart
+ ? {
+ series: {
+ metric,
+ unit: input.unit ?? 'day',
+ points: (chart.chart ?? []).map(row => ({ date: row.t, ...percentiles(row) })),
+ },
+ }
+ : {}),
+ ...(input.breakdown && breakdown
+ ? {
+ breakdown: {
+ metric,
+ type: input.breakdown,
+ rows: (Array.isArray(breakdown) ? breakdown : []).map(row => ({
+ name: row.name ?? '',
+ measurements: Number(row.count ?? 0),
+ ...percentiles(row),
+ })),
+ },
+ }
+ : {}),
+ };
+ },
+});
diff --git a/packages/mcp/src/tools/reports.ts b/packages/mcp/src/tools/reports.ts
index 3d060d82f..d55584f4f 100644
--- a/packages/mcp/src/tools/reports.ts
+++ b/packages/mcp/src/tools/reports.ts
@@ -18,50 +18,74 @@ export const runFunnel = defineTool({
description:
'Calculates how many visitors progressed through an ordered sequence of 2–8 steps (page paths or custom events) ' +
'within a time window, and where they dropped off. Use this for conversion questions such as ' +
- '"how many visitors who viewed /pricing went on to sign up?". Requires a websiteId from list_websites.',
- inputSchema: z.object({
- websiteId,
- ...dateRangeInput,
- steps: z
- .array(
- z.object({
- type: z
- .enum(['path', 'event'])
- .describe('"path" for a page path, "event" for a custom event name.'),
- value: z
- .string()
- .min(1)
- .describe(
- 'The page path (e.g. "/pricing") or event name (e.g. "signup"). Use * as a wildcard.',
- ),
- }),
- )
- .min(2)
- .max(8)
- .describe('Ordered funnel steps.'),
- windowMinutes: z
- .number()
- .int()
- .positive()
- .max(60 * 24 * 30)
- .optional()
- .describe('Maximum minutes allowed between the first and each following step (default 60).'),
- filters: filtersSchema.optional(),
- }),
+ '"how many visitors who viewed /pricing went on to sign up?". Either pass "funnelId" for a funnel saved in Umami ' +
+ '(find it with list_funnels) or define ad-hoc "steps". Requires a websiteId from list_websites.',
+ inputSchema: z
+ .object({
+ websiteId,
+ ...dateRangeInput,
+ funnelId: z
+ .string()
+ .uuid()
+ .optional()
+ .describe('ID of a saved funnel from list_funnels. Its steps and window are used.'),
+ steps: z
+ .array(
+ z.object({
+ type: z
+ .enum(['path', 'event'])
+ .describe('"path" for a page path, "event" for a custom event name.'),
+ value: z
+ .string()
+ .min(1)
+ .describe(
+ 'The page path (e.g. "/pricing") or event name (e.g. "signup"). Use * as a wildcard.',
+ ),
+ }),
+ )
+ .min(2)
+ .max(8)
+ .optional()
+ .describe('Ordered funnel steps. Required unless funnelId is given.'),
+ windowMinutes: z
+ .number()
+ .int()
+ .positive()
+ .max(60 * 24 * 30)
+ .optional()
+ .describe(
+ 'Maximum minutes allowed between the first and each following step (default 60). Ignored with funnelId.',
+ ),
+ filters: filtersSchema.optional(),
+ })
+ .refine(input => Boolean(input.funnelId) !== Boolean(input.steps), {
+ message: 'Provide either funnelId or steps, not both.',
+ path: ['steps'],
+ }),
async handler(input, { client }) {
const range = parseDateRange(input);
- const result = await client.getWebsiteFunnelStats({
- websiteId: input.websiteId,
- ...range,
- ...toFilterParams(input.filters),
- window: input.windowMinutes ?? 60,
- steps: JSON.stringify(input.steps),
- });
+ const filters = toFilterParams(input.filters);
+ const result = input.funnelId
+ ? await client.getWebsiteSavedFunnelStats({
+ websiteId: input.websiteId,
+ funnelId: input.funnelId,
+ ...range,
+ ...filters,
+ })
+ : await client.getWebsiteFunnelStats({
+ websiteId: input.websiteId,
+ ...range,
+ ...filters,
+ window: input.windowMinutes ?? 60,
+ steps: JSON.stringify(input.steps),
+ });
return {
websiteId: input.websiteId,
range: isoRange(range),
- windowMinutes: input.windowMinutes ?? 60,
+ ...(input.funnelId
+ ? { funnelId: input.funnelId }
+ : { windowMinutes: input.windowMinutes ?? 60 }),
steps: (Array.isArray(result) ? result : []).map((step, index) => ({
step: index + 1,
type: step.type,
diff --git a/packages/mcp/src/tools/segments.ts b/packages/mcp/src/tools/segments.ts
new file mode 100644
index 000000000..f3d4523d8
--- /dev/null
+++ b/packages/mcp/src/tools/segments.ts
@@ -0,0 +1,53 @@
+import { z } from 'zod';
+import { toIso } from '../lib/dates';
+import { defineTool } from '../lib/tool';
+
+interface SegmentRow {
+ id?: string;
+ name?: string;
+ type?: string;
+ parameters?: unknown;
+ createdAt?: string | null;
+}
+
+export const listSegments = defineTool({
+ name: 'list_segments',
+ title: 'List saved segments and cohorts',
+ description:
+ 'Lists the saved segments (filter presets such as "mobile visitors from the US") and cohorts (groups of visitors who ' +
+ 'performed an action) defined for a website, with their IDs and definitions. Pass the ID as filters.segment or ' +
+ 'filters.cohort in other tools to scope results to that audience. Requires a websiteId from list_websites.',
+ inputSchema: z.object({
+ websiteId: z.string().uuid().describe('Website ID from list_websites.'),
+ type: z
+ .enum(['segment', 'cohort'])
+ .optional()
+ .describe('Which kind to list. Defaults to both.'),
+ search: z.string().optional().describe('Filter by name.'),
+ }),
+ async handler(input, { client }) {
+ const types = input.type ? [input.type] : (['segment', 'cohort'] as const);
+ const results = await Promise.all(
+ types.map(async type => {
+ const result = (await client.getWebsiteSegments({
+ websiteId: input.websiteId,
+ type,
+ search: input.search,
+ })) as { data?: SegmentRow[] };
+
+ return (result?.data ?? []).map(row => ({
+ id: row.id,
+ name: row.name,
+ type: row.type ?? type,
+ definition: row.parameters ?? null,
+ createdAt: toIso(row.createdAt),
+ }));
+ }),
+ );
+
+ return {
+ websiteId: input.websiteId,
+ segments: results.flat(),
+ };
+ },
+});
diff --git a/src/lib/mcp/dispatch.test.ts b/src/lib/mcp/dispatch.test.ts
index 64c1e4697..a5a392b5e 100644
--- a/src/lib/mcp/dispatch.test.ts
+++ b/src/lib/mcp/dispatch.test.ts
@@ -15,4 +15,23 @@ describe('MCP dispatch table', () => {
expect(matchDispatchRoute('GET', '/api/admin/users')).toBeNull();
expect(matchDispatchRoute('DELETE', '/api/websites/abc')).toBeNull();
});
+
+ test('exposes saved definitions and performance as GET only', () => {
+ expect(matchDispatchRoute('GET', '/api/websites/abc/funnels/def/stats')?.params).toEqual({
+ websiteId: 'abc',
+ funnelId: 'def',
+ });
+ expect(matchDispatchRoute('GET', '/api/websites/abc/goals/def/stats')?.params).toEqual({
+ websiteId: 'abc',
+ goalId: 'def',
+ });
+
+ for (const path of ['goals', 'funnels', 'segments', 'annotations', 'performance/stats']) {
+ expect(matchDispatchRoute('GET', `/api/websites/abc/${path}`)).not.toBeNull();
+ expect(matchDispatchRoute('POST', `/api/websites/abc/${path}`)).toBeNull();
+ }
+
+ expect(matchDispatchRoute('GET', '/api/websites/abc/goals/def')).toBeNull();
+ expect(matchDispatchRoute('DELETE', '/api/websites/abc/segments/def')).toBeNull();
+ });
});
diff --git a/src/lib/mcp/dispatch.ts b/src/lib/mcp/dispatch.ts
index 1375a7056..54b1bbb51 100644
--- a/src/lib/mcp/dispatch.ts
+++ b/src/lib/mcp/dispatch.ts
@@ -133,6 +133,51 @@ export const MCP_DISPATCH_ROUTES: readonly DispatchRoute[] = [
path: '/api/websites/{websiteId}/funnels/stats',
load: () => import('@/app/api/websites/[websiteId]/funnels/stats/route'),
},
+ {
+ method: 'GET',
+ path: '/api/websites/{websiteId}/funnels',
+ load: () => import('@/app/api/websites/[websiteId]/funnels/route'),
+ },
+ {
+ method: 'GET',
+ path: '/api/websites/{websiteId}/funnels/{funnelId}/stats',
+ load: () => import('@/app/api/websites/[websiteId]/funnels/[funnelId]/stats/route'),
+ },
+ {
+ method: 'GET',
+ path: '/api/websites/{websiteId}/goals',
+ load: () => import('@/app/api/websites/[websiteId]/goals/route'),
+ },
+ {
+ method: 'GET',
+ path: '/api/websites/{websiteId}/goals/{goalId}/stats',
+ load: () => import('@/app/api/websites/[websiteId]/goals/[goalId]/stats/route'),
+ },
+ {
+ method: 'GET',
+ path: '/api/websites/{websiteId}/segments',
+ load: () => import('@/app/api/websites/[websiteId]/segments/route'),
+ },
+ {
+ method: 'GET',
+ path: '/api/websites/{websiteId}/annotations',
+ load: () => import('@/app/api/websites/[websiteId]/annotations/route'),
+ },
+ {
+ method: 'GET',
+ path: '/api/websites/{websiteId}/performance/stats',
+ load: () => import('@/app/api/websites/[websiteId]/performance/stats/route'),
+ },
+ {
+ method: 'GET',
+ path: '/api/websites/{websiteId}/performance/chart',
+ load: () => import('@/app/api/websites/[websiteId]/performance/chart/route'),
+ },
+ {
+ method: 'GET',
+ path: '/api/websites/{websiteId}/performance/metrics',
+ load: () => import('@/app/api/websites/[websiteId]/performance/metrics/route'),
+ },
{
method: 'GET',
path: '/api/websites/{websiteId}/journeys',