Add date range, event, and session analytics tools to MCP

This commit is contained in:
Mike Cao committed 2026-09-09 23:27:35 -07:00
1 parent 667d718047
commit e0e60cbcb1
8 files changed
+561 -1

No files matched your search

+7
View File
@@ -12,12 +12,17 @@ user/team permission checks as the web app.
| Tool | Purpose |
| --------------------- | ----------------------------------------------------------------------- |
| `list_websites` | Find the websites you can access (call first to get a `websiteId`). |
| `get_website_daterange` | Earliest and latest dates with recorded data. |
| `get_website_stats` | Pageviews, visitors, visits, bounce rate, duration + previous period. |
| `get_website_traffic` | Pageview/visit time series by minute, hour, day, month or year. |
| `get_website_metrics` | Top pages, referrers, channels, countries, browsers, devices, UTM, events. |
| `get_realtime` | Visitors active right now. |
| `get_events` | Individual tracked events (paginated). |
| `get_event_stats` | Custom event totals + previous period. |
| `get_event_series` | Custom event counts over time, grouped by event name. |
| `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_session` | One session with its activity timeline and properties. |
| `run_funnel` | Conversion funnel across page/event steps. |
| `run_journey` | Most common paths visitors take. |
@@ -109,6 +114,8 @@ For Cloud stdio, set `UMAMI_API_KEY` and omit `UMAMI_URL` and `UMAMI_API_TOKEN`:
- Where is traffic coming from?
- What signup events occurred yesterday?
- 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?
## Programmatic use
+193
View File
@@ -203,6 +203,70 @@ describe('createUmamiMcpServer', () => {
return { body: [{ name: url.searchParams.get('type'), value: 100 }] };
}
if (path === `/api/websites/${WEBSITE_ID}/daterange`) {
return {
body: { startDate: '2023-06-01T00:00:00.000Z', endDate: '2024-01-31T00:00:00.000Z' },
};
}
if (path === `/api/websites/${WEBSITE_ID}/events/stats`) {
return {
body: {
data: {
events: 30,
visitors: 12,
visits: 15,
uniqueEvents: 3,
comparison: { events: 20, visitors: 8, visits: 9, uniqueEvents: 2 },
},
},
};
}
if (path === `/api/websites/${WEBSITE_ID}/events/series`) {
return {
body: [
{ x: 'signup', t: '2024-01-01', y: 4 },
{ x: 'signup', t: '2024-01-02', y: 6 },
{ x: 'checkout', t: '2024-01-01', y: 1 },
],
};
}
if (path === `/api/websites/${WEBSITE_ID}/sessions/stats`) {
return {
body: {
pageviews: { value: 100 },
visitors: { value: 40 },
visits: { value: 50 },
countries: { value: 7 },
events: { value: 30 },
},
};
}
if (path === `/api/websites/${WEBSITE_ID}/event-data/properties`) {
return {
body: [
{ eventName: 'checkout', propertyName: 'plan', dataType: 1, total: 25 },
{ eventName: 'checkout', propertyName: 'amount', dataType: 2, total: 25 },
],
};
}
if (path === `/api/websites/${WEBSITE_ID}/event-data/stats`) {
return { body: { events: 25, properties: 2, records: 50 } };
}
if (path === `/api/websites/${WEBSITE_ID}/event-data/values`) {
return {
body: [
{ value: 'pro', total: 15 },
{ value: 'free', total: 10 },
],
};
}
if (path.startsWith('/api/websites/')) {
return {
status: 401,
@@ -233,12 +297,17 @@ describe('createUmamiMcpServer', () => {
expect(names).toEqual(
[
'list_websites',
'get_website_daterange',
'get_website_stats',
'get_website_traffic',
'get_website_metrics',
'get_realtime',
'get_events',
'get_event_stats',
'get_event_series',
'get_event_properties',
'get_sessions',
'get_session_stats',
'get_session',
'run_funnel',
'run_journey',
@@ -398,6 +467,130 @@ describe('createUmamiMcpServer', () => {
});
});
test('get_website_daterange returns the available data window', async () => {
const result = await harness.client.callTool({
name: 'get_website_daterange',
arguments: { websiteId: WEBSITE_ID },
});
expect(result.isError).toBeFalsy();
expect(result.structuredContent).toMatchObject({
startAt: '2023-06-01T00:00:00.000Z',
endAt: '2024-01-31T00:00:00.000Z',
hasData: true,
});
});
test('get_event_stats summarizes current and previous periods', async () => {
const result = await harness.client.callTool({
name: 'get_event_stats',
arguments: {
websiteId: WEBSITE_ID,
startAt: '2024-01-01',
endAt: '2024-01-08',
compare: 'yoy',
},
});
expect(result.isError).toBeFalsy();
expect(result.structuredContent).toMatchObject({
current: { events: 30, visitors: 12, visits: 15, uniqueEvents: 3 },
previous: { events: 20, visitors: 8 },
compare: 'yoy',
});
expect(harness.calls[0].url.searchParams.get('compare')).toBe('yoy');
});
test('get_event_series groups rows by event name', async () => {
const result = await harness.client.callTool({
name: 'get_event_series',
arguments: { websiteId: WEBSITE_ID, startAt: '2024-01-01', unit: 'day', limit: 5 },
});
expect(result.isError).toBeFalsy();
expect(result.structuredContent).toMatchObject({
unit: 'day',
events: [
{
name: 'signup',
total: 10,
series: [
{ date: '2024-01-01', value: 4 },
{ date: '2024-01-02', value: 6 },
],
},
{ name: 'checkout', total: 1 },
],
});
expect(harness.calls[0].url.searchParams.get('limit')).toBe('5');
});
test('get_session_stats unwraps value objects', async () => {
const result = await harness.client.callTool({
name: 'get_session_stats',
arguments: { websiteId: WEBSITE_ID, startAt: '2024-01-01', filters: { country: 'US' } },
});
expect(result.isError).toBeFalsy();
expect(result.structuredContent).toMatchObject({
visitors: 40,
visits: 50,
pageviews: 100,
events: 30,
countries: 7,
});
expect(harness.calls[0].url.searchParams.get('country')).toBe('US');
});
test('get_event_properties lists properties, then values for one property', async () => {
const listed = await harness.client.callTool({
name: 'get_event_properties',
arguments: { websiteId: WEBSITE_ID, startAt: '2024-01-01', eventName: 'checkout' },
});
expect(listed.isError).toBeFalsy();
expect(listed.structuredContent).toMatchObject({
eventName: 'checkout',
totals: { events: 25, properties: 2, records: 50 },
properties: [
{ eventName: 'checkout', propertyName: 'plan', dataType: 'string', count: 25 },
{ eventName: 'checkout', propertyName: 'amount', dataType: 'number', count: 25 },
],
});
expect(harness.calls.map(call => call.url.pathname).sort()).toEqual([
`/api/websites/${WEBSITE_ID}/event-data/properties`,
`/api/websites/${WEBSITE_ID}/event-data/stats`,
]);
expect(harness.calls[0].url.searchParams.get('event')).toBe('checkout');
harness.calls.length = 0;
const values = await harness.client.callTool({
name: 'get_event_properties',
arguments: {
websiteId: WEBSITE_ID,
startAt: '2024-01-01',
propertyName: 'plan',
eventName: 'checkout',
dataType: 'string',
},
});
expect(values.isError).toBeFalsy();
expect(values.structuredContent).toMatchObject({
propertyName: 'plan',
values: [
{ value: 'pro', count: 15 },
{ value: 'free', count: 10 },
],
});
expect(harness.calls).toHaveLength(1);
expect(harness.calls[0].url.pathname).toBe(`/api/websites/${WEBSITE_ID}/event-data/values`);
expect(harness.calls[0].url.searchParams.get('propertyName')).toBe('plan');
expect(harness.calls[0].url.searchParams.get('eventName')).toBe('checkout');
expect(harness.calls[0].url.searchParams.get('dataType')).toBe('1');
});
test('run_funnel sends structured criteria with GET', async () => {
const result = await harness.client.callTool({
name: 'run_funnel',
+2 -1
View File
@@ -11,7 +11,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. 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_events / get_sessions / get_session to inspect individual activity, and run_funnel / run_journey / run_retention / run_attribution / get_revenue for reports.
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.
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.`;
+28
View File
@@ -0,0 +1,28 @@
import { z } from 'zod';
import { toIso } from '../lib/dates';
import { defineTool } from '../lib/tool';
export const getWebsiteDateRange = defineTool({
name: 'get_website_daterange',
title: 'Get website data date range',
description:
'Returns the earliest and latest timestamps for which a website has recorded data. ' +
'Call this before querying an unfamiliar site or a period far in the past so you do not ask for dates ' +
'outside the available data (which returns zeros). Requires a websiteId from list_websites.',
inputSchema: z.object({
websiteId: z.string().uuid().describe('Website ID from list_websites.'),
}),
async handler(input, { client }) {
const result = (await client.getWebsiteDateRange({ websiteId: input.websiteId })) as {
startDate?: string | null;
endDate?: string | null;
};
return {
websiteId: input.websiteId,
startAt: toIso(result?.startDate),
endAt: toIso(result?.endDate),
hasData: Boolean(result?.startDate && result?.endDate),
};
},
});
+135
View File
@@ -0,0 +1,135 @@
import { z } from 'zod';
import { dateRangeInput, parseDateRange } from '../lib/dates';
import { filtersSchema, toFilterParams } from '../lib/filters';
import { defineTool } from '../lib/tool';
const DATA_TYPES: Record<number, string> = {
1: 'string',
2: 'number',
3: 'boolean',
4: 'date',
5: 'array',
};
const dataTypeInput = z
.enum(['string', 'number', 'boolean', 'date', 'array'])
.describe('Restrict to properties of this data type.');
function toDataTypeCode(value?: string) {
if (!value) {
return undefined;
}
const entry = Object.entries(DATA_TYPES).find(([, name]) => name === value);
return entry ? Number(entry[0]) : undefined;
}
interface PropertyRow {
eventName?: string;
propertyName?: string;
dataType?: number;
total?: number;
}
interface ValueRow {
value?: string;
total?: number;
}
interface StatsRow {
events?: number;
properties?: number;
records?: number;
}
export const getEventProperties = defineTool({
name: 'get_event_properties',
title: 'Get custom event properties and values',
description:
'Explores the custom data attached to tracked events (e.g. { plan: "pro", amount: 49 } sent with a "checkout" event). ' +
'Without "propertyName": lists every property name seen on custom events in the range, with its event name, data type and ' +
'how many times it was recorded, plus overall totals. ' +
'With "propertyName": returns the distinct values of that property ranked by frequency (top 100), optionally restricted to one ' +
'event name. Use this for questions like "which plans do people choose?" or "what search terms are used most?". ' +
'Requires a websiteId from list_websites.',
inputSchema: z.object({
websiteId: z.string().uuid().describe('Website ID from list_websites.'),
...dateRangeInput,
propertyName: z
.string()
.min(1)
.optional()
.describe('Property to get values for. Omit to list available properties first.'),
eventName: z
.string()
.min(1)
.optional()
.describe('Only consider this custom event name, e.g. "checkout".'),
dataType: dataTypeInput.optional(),
filters: filtersSchema.optional(),
}),
async handler(input, { client }) {
const range = parseDateRange(input);
const filters = toFilterParams(input.filters);
const common = {
websiteId: input.websiteId,
startAt: range.startAt,
endAt: range.endAt,
...filters,
};
const base = {
websiteId: input.websiteId,
range: {
startAt: new Date(range.startAt).toISOString(),
endAt: new Date(range.endAt).toISOString(),
},
};
if (input.propertyName) {
const rows = (await client.getEventDataValues({
...common,
propertyName: input.propertyName,
eventName: input.eventName,
dataType: toDataTypeCode(input.dataType),
})) as ValueRow[];
return {
...base,
propertyName: input.propertyName,
eventName: input.eventName ?? null,
values: (Array.isArray(rows) ? rows : []).map(row => ({
value: row.value ?? null,
count: Number(row.total ?? 0),
})),
};
}
const propertyParams = input.eventName ? { ...common, event: input.eventName } : common;
const [rows, stats] = await Promise.all([
client.getEventDataProperties(propertyParams) as Promise<PropertyRow[]>,
client.getEventDataStats(propertyParams) as Promise<StatsRow>,
]);
const wanted = toDataTypeCode(input.dataType);
const properties = (Array.isArray(rows) ? rows : [])
.filter(row => wanted === undefined || row.dataType === wanted)
.map(row => ({
eventName: row.eventName ?? null,
propertyName: row.propertyName ?? null,
dataType: DATA_TYPES[row.dataType ?? 0] ?? String(row.dataType ?? 'unknown'),
count: Number(row.total ?? 0),
}));
return {
...base,
eventName: input.eventName ?? null,
totals: {
events: Number(stats?.events ?? 0),
properties: Number(stats?.properties ?? 0),
records: Number(stats?.records ?? 0),
},
properties,
};
},
});
+131
View File
@@ -0,0 +1,131 @@
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';
interface EventTotals {
events?: number;
visitors?: number;
visits?: number;
uniqueEvents?: number;
}
function totals(row: EventTotals | undefined) {
return {
events: Number(row?.events ?? 0),
visitors: Number(row?.visitors ?? 0),
visits: Number(row?.visits ?? 0),
uniqueEvents: Number(row?.uniqueEvents ?? 0),
};
}
export const getEventStats = defineTool({
name: 'get_event_stats',
title: 'Get custom event stats',
description:
'Returns totals for custom events (not pageviews) over a time range: number of events fired, unique visitors and ' +
'visits that triggered them, and how many distinct event names were seen. Also returns the previous period ' +
'(or same period last year) for comparison. Use "event" in filters to scope to one event name. ' +
'For a per-event ranking use get_website_metrics with type "event"; for trends over time use get_event_series. ' +
'Requires a websiteId from list_websites.',
inputSchema: z.object({
websiteId: z.string().uuid().describe('Website ID from list_websites.'),
...dateRangeInput,
compare: z
.enum(['prev', 'yoy'])
.optional()
.describe(
'Comparison period: "prev" (previous period, default) or "yoy" (same period last year).',
),
filters: filtersSchema.optional(),
}),
async handler(input, { client }) {
const range = parseDateRange(input);
const result = (await client.getWebsiteEventStats({
websiteId: input.websiteId,
startAt: range.startAt,
endAt: range.endAt,
compare: input.compare,
...toFilterParams(input.filters),
})) as { data?: EventTotals & { comparison?: EventTotals } };
return {
websiteId: input.websiteId,
range: {
startAt: new Date(range.startAt).toISOString(),
endAt: new Date(range.endAt).toISOString(),
},
current: totals(result?.data),
previous: totals(result?.data?.comparison),
compare: input.compare ?? 'prev',
};
},
});
interface SeriesRow {
x: string;
t: string;
y: number;
}
export const getEventSeries = defineTool({
name: 'get_event_series',
title: 'Get custom events over time',
description:
'Returns a time series of custom event counts, grouped by event name and bucketed by hour, day, month or year. ' +
'Use this to see how often each event fires over time, spot spikes, or compare events against each other. ' +
'Only the top N event names by volume are included (default 20). Requires a websiteId from list_websites.',
inputSchema: z.object({
websiteId: z.string().uuid().describe('Website ID from list_websites.'),
...dateRangeInput,
unit: timeUnit.optional(),
timezone: timezone.optional(),
limit: z
.number()
.int()
.positive()
.max(MAX_METRIC_LIMIT)
.optional()
.describe(
`Maximum number of event names to include (default ${DEFAULT_METRIC_LIMIT}, max ${MAX_METRIC_LIMIT}).`,
),
filters: filtersSchema.optional(),
}),
async handler(input, { client }) {
const range = parseDateRange(input);
const rows = (await client.getWebsiteEventSeries({
websiteId: input.websiteId,
startAt: range.startAt,
endAt: range.endAt,
unit: input.unit,
timezone: input.timezone ?? 'UTC',
limit: clamp(input.limit, DEFAULT_METRIC_LIMIT, MAX_METRIC_LIMIT),
...toFilterParams(input.filters),
})) as SeriesRow[];
const byName = new Map<string, { date: string; value: number }[]>();
for (const row of Array.isArray(rows) ? rows : []) {
const name = row.x ?? '';
const points = byName.get(name) ?? [];
points.push({ date: row.t, value: Number(row.y ?? 0) });
byName.set(name, points);
}
return {
websiteId: input.websiteId,
range: {
startAt: new Date(range.startAt).toISOString(),
endAt: new Date(range.endAt).toISOString(),
},
unit: input.unit ?? 'day',
events: [...byName.entries()].map(([name, series]) => ({
name,
total: series.reduce((sum, point) => sum + point.value, 0),
series,
})),
};
},
});
+14
View File
@@ -1,9 +1,13 @@
import type { AnyToolDefinition } from '../lib/tool';
import { getWebsiteDateRange } from './daterange';
import { getEventProperties } from './event-properties';
import { getEventSeries, getEventStats } from './event-stats';
import { getEvents } from './events';
import { getWebsiteMetrics } from './metrics';
import { getRealtime } from './realtime';
import { getRevenue, runAttribution, runFunnel, runJourney, runRetention } from './reports';
import { getSession } from './session';
import { getSessionStats } from './session-stats';
import { getSessions } from './sessions';
import { getWebsiteStats } from './stats';
import { getWebsiteTraffic } from './traffic';
@@ -12,12 +16,17 @@ import { listWebsites } from './websites';
/** Core read-only analytics tools. */
export const coreTools: AnyToolDefinition[] = [
listWebsites,
getWebsiteDateRange,
getWebsiteStats,
getWebsiteTraffic,
getWebsiteMetrics,
getRealtime,
getEvents,
getEventStats,
getEventSeries,
getEventProperties,
getSessions,
getSessionStats,
getSession,
];
@@ -33,11 +42,16 @@ export const reportTools: AnyToolDefinition[] = [
export const allTools: AnyToolDefinition[] = [...coreTools, ...reportTools];
export {
getEventProperties,
getEventSeries,
getEventStats,
getEvents,
getRealtime,
getRevenue,
getSession,
getSessionStats,
getSessions,
getWebsiteDateRange,
getWebsiteMetrics,
getWebsiteStats,
getWebsiteTraffic,
+51
View File
@@ -0,0 +1,51 @@
import { z } from 'zod';
import { dateRangeInput, parseDateRange } from '../lib/dates';
import { filtersSchema, toFilterParams } from '../lib/filters';
import { defineTool } from '../lib/tool';
type StatValue = { value?: number } | number | undefined;
function unwrap(value: StatValue) {
if (typeof value === 'number') {
return value;
}
return Number(value?.value ?? 0);
}
export const getSessionStats = defineTool({
name: 'get_session_stats',
title: 'Get session stats',
description:
'Returns session-level totals for a website over a time range: unique visitors, visits (sessions), pageviews, ' +
'custom events and the number of distinct countries visitors came from. ' +
'Lighter than get_sessions when you only need counts, and works with filters (e.g. sessions from Chrome users in the US). ' +
'For bounce rate and visit duration use get_website_stats. Requires a websiteId from list_websites.',
inputSchema: z.object({
websiteId: z.string().uuid().describe('Website ID from list_websites.'),
...dateRangeInput,
filters: filtersSchema.optional(),
}),
async handler(input, { client }) {
const range = parseDateRange(input);
const result = (await client.getWebsiteSessionStats({
websiteId: input.websiteId,
startAt: range.startAt,
endAt: range.endAt,
...toFilterParams(input.filters),
})) as Record<string, StatValue>;
return {
websiteId: input.websiteId,
range: {
startAt: new Date(range.startAt).toISOString(),
endAt: new Date(range.endAt).toISOString(),
},
visitors: unwrap(result?.visitors),
visits: unwrap(result?.visits),
pageviews: unwrap(result?.pageviews),
events: unwrap(result?.events),
countries: unwrap(result?.countries),
};
},
});