Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

feat(mcp): validate time_zone, add fields pruning, lower row caps, fix docs tool list

Bill Yang58b9cd5199a3
diff --git a/docs/content/docs/(docs)/mcp/index.mdx b/docs/content/docs/(docs)/mcp/index.mdx
index 6700f8ee6..2e4dcda2d 100644
--- a/docs/content/docs/(docs)/mcp/index.mdx
+++ b/docs/content/docs/(docs)/mcp/index.mdx
@@ -130,6 +130,9 @@ Any other MCP client that supports Streamable HTTP works with the generic config
| `get_web_vitals` | Core Web Vitals percentiles (LCP, CLS, INP, FCP, TTFB) |
| `get_retention` | User retention cohort table |
| `get_journeys` | Most common page-to-page navigation paths |
+| `get_annotations` | Notes pinned to dates on the traffic chart (launches, deploys, campaigns, outages) |
+| `list_segments` | Saved segments: named, reusable filter sets for a site or the whole organization |
+| `apply_segment` | Overview KPIs for visitors matching a saved segment, with its filters for reuse |
### Sites
@@ -186,7 +189,7 @@ Any other MCP client that supports Streamable HTTP works with the generic config
| `get_query_schema` | The ClickHouse schema and rules for `run_query` |
| `run_query` | Read-only ClickHouse SQL against the site-scoped `scoped_events` table |
-Analytics tools accept optional time inputs (`start_date`/`end_date` with an IANA `time_zone`, or `past_minutes`) and the same filters as the dashboard. Omitting time inputs queries all time.
+Analytics tools accept optional time inputs (`start_date`/`end_date` with an IANA `time_zone`, or `past_minutes`) and the same filters as the dashboard. Omitting time inputs queries all time; an unrecognized `time_zone` is rejected before the call is made. `get_sessions`, `get_events`, and `get_users` accept an optional `fields` list to return only the named row columns, which keeps large result sets small.
## Permissions and roles
diff --git a/server/src/mcp/inputs.ts b/server/src/mcp/inputs.ts
index ee00e986c..166a29d7a 100644
--- a/server/src/mcp/inputs.ts
+++ b/server/src/mcp/inputs.ts
@@ -69,6 +69,24 @@ export const siteIdInput = z
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
+/** True for any IANA zone the runtime accepts, including aliases like Etc/UTC or US/Pacific. */
+export function isValidTimeZone(timeZone: string): boolean {
+ try {
+ new Intl.DateTimeFormat("en-US", { timeZone });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+// Validated here so a bad zone comes back as a fixable argument error instead
+// of an opaque REST 400 after the round trip.
+export const timeZoneInput = z
+ .string()
+ .refine(isValidTimeZone, { message: "Use a valid IANA time zone such as UTC or America/New_York" })
+ .optional()
+ .describe("IANA time zone used to interpret dates and buckets, e.g. America/New_York. Defaults to UTC.");
+
export const timeInputs = {
start_date: z
.string()
@@ -82,10 +100,7 @@ export const timeInputs = {
.regex(dateRegex, "Use YYYY-MM-DD")
.optional()
.describe("End date (YYYY-MM-DD, inclusive, interpreted in time_zone)."),
- time_zone: z
- .string()
- .optional()
- .describe("IANA time zone used to interpret dates and buckets, e.g. America/New_York. Defaults to UTC."),
+ time_zone: timeZoneInput,
past_minutes: z
.number()
.int()
@@ -157,6 +172,14 @@ export function toFiltersQuery(filters: FilterArgs): Record<string, string | und
return { filters: filters && filters.length > 0 ? JSON.stringify(filters) : undefined };
}
+export const fieldsInput = z
+ .array(z.string().min(1))
+ .min(1)
+ .optional()
+ .describe(
+ "Only return these row fields (top-level keys), e.g. [\"session_id\",\"entry_page\",\"referrer\"]. Omit for full rows. Use to keep responses small."
+ );
+
export const organizationIdInput = z.string().min(1).describe("Organization ID from list_sites");
export const memberRoleInput = z
diff --git a/server/src/mcp/mcp.test.ts b/server/src/mcp/mcp.test.ts
index 7a8819710..aa57f2966 100644
--- a/server/src/mcp/mcp.test.ts
+++ b/server/src/mcp/mcp.test.ts
@@ -507,6 +507,41 @@ describe("mcp endpoint", () => {
expect(row.entry_page).toBe("/pricing desrever");
});
+ it("get_sessions prunes rows to the requested fields", async () => {
+ const result = await callTool(app, "get_sessions", { site_id: 5, fields: ["user_id", "entry_page", "not_a_column"] });
+
+ expect(result.isError).toBeFalsy();
+ const row = result.structuredContent.data[0];
+ expect(Object.keys(row).sort()).toEqual(["entry_page", "user_id"]);
+ expect(row.ip).toBeUndefined();
+ });
+
+ it("rejects an unrecognized time_zone before hitting the API", async () => {
+ captured.url = undefined;
+ const result = await callTool(app, "get_overview", {
+ site_id: 5,
+ start_date: "2026-08-01",
+ end_date: "2026-08-31",
+ time_zone: "Mars/Olympus_Mons",
+ });
+
+ expect(result.isError).toBe(true);
+ expect(result.content[0].text).toContain("IANA time zone");
+ expect(captured.url).toBeUndefined();
+ });
+
+ it("accepts IANA aliases as time_zone", async () => {
+ const result = await callTool(app, "get_overview", {
+ site_id: 5,
+ start_date: "2026-08-01",
+ end_date: "2026-08-31",
+ time_zone: "Etc/UTC",
+ });
+
+ expect(result.isError).toBeFalsy();
+ expect(captured.query?.time_zone).toBe("Etc/UTC");
+ });
+
it("create_goal maps goal_type onto the REST body", async () => {
const result = await callTool(app, "create_goal", {
site_id: 5,
diff --git a/server/src/mcp/tools/analytics.ts b/server/src/mcp/tools/analytics.ts
index 1ec947bcb..cc951b1dd 100644
--- a/server/src/mcp/tools/analytics.ts
+++ b/server/src/mcp/tools/analytics.ts
@@ -150,7 +150,7 @@ export function registerAnalyticsTools(server: McpServer, api: RybbitApiClient,
inputSchema: {
site_id: siteIdInput,
dimension: z.enum(FILTER_PARAMETERS).describe("The dimension to break down by, e.g. pathname, referrer, country, channel"),
- limit: z.number().int().min(1).max(500).default(25).describe("Rows to return"),
+ limit: z.number().int().min(1).max(100).default(25).describe("Rows to return (max 100; use page for more)"),
page: z.number().int().min(1).optional().describe("1-based page for paging past the first `limit` rows"),
...timeInputs,
filters: filtersInput,
@@ -261,7 +261,7 @@ export function registerAnalyticsTools(server: McpServer, api: RybbitApiClient,
inputSchema: {
site_id: siteIdInput,
steps: z.number().int().min(2).max(10).default(3).describe("Journey length in pages"),
- limit: z.number().int().min(1).max(500).default(25).describe("Number of journeys to return"),
+ limit: z.number().int().min(1).max(100).default(25).describe("Number of journeys to return (max 100)"),
...timeInputs,
filters: filtersInput,
},
diff --git a/server/src/mcp/tools/annotations.ts b/server/src/mcp/tools/annotations.ts
index 4da37e519..de1126d2c 100644
--- a/server/src/mcp/tools/annotations.ts
+++ b/server/src/mcp/tools/annotations.ts
@@ -1,7 +1,7 @@
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import { RybbitApiClient } from "../apiClient.js";
-import { siteIdInput } from "../inputs.js";
+import { siteIdInput, timeZoneInput } from "../inputs.js";
import { looseRows, ok, readOnly, type ScopeCheck, type ToolGuard } from "./shared.js";
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
@@ -33,10 +33,7 @@ export function registerAnnotationTools(
.regex(dateRegex, "Use YYYY-MM-DD")
.optional()
.describe("Only annotations on or before this date (YYYY-MM-DD, in time_zone). Omit for all."),
- time_zone: z
- .string()
- .optional()
- .describe("IANA timezone the date bounds are read in (default UTC), e.g. America/Los_Angeles."),
+ time_zone: timeZoneInput,
},
outputSchema: annotationsOutput,
annotations: readOnly,
diff --git a/server/src/mcp/tools/rawData.ts b/server/src/mcp/tools/rawData.ts
index 0cc1ce11f..5096ca714 100644
--- a/server/src/mcp/tools/rawData.ts
+++ b/server/src/mcp/tools/rawData.ts
@@ -2,8 +2,8 @@ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import { EVENT_SCHEMA } from "../../api/analytics/utils/eventSchema.js";
import { RybbitApiClient } from "../apiClient.js";
-import { filtersInput, organizationIdInput, siteIdInput, timeInputs } from "../inputs.js";
-import { looseRow, looseRows, ok, readOnly, siteQuery, type ScopeCheck, type ToolGuard } from "./shared.js";
+import { fieldsInput, filtersInput, organizationIdInput, siteIdInput, timeInputs } from "../inputs.js";
+import { looseRow, looseRows, ok, pickRowFields, readOnly, siteQuery, type ScopeCheck, type ToolGuard } from "./shared.js";
const sessionsOutput = z.object({ data: looseRows.optional() }).passthrough();
@@ -45,14 +45,21 @@ export function registerRawDataTools(server: McpServer, api: RybbitApiClient, gu
limit: z.number().int().min(1).max(100).default(20),
page: z.number().int().min(1).default(1),
user_id: z.string().optional().describe("Only sessions for this user (device fingerprint id or identified user id)"),
+ fields: fieldsInput,
...timeInputs,
filters: filtersInput,
},
outputSchema: sessionsOutput,
annotations: readOnly,
},
- guard(async ({ site_id, limit, page, user_id, ...rest }) =>
- ok(await api.call("GET", `/sites/${site_id}/sessions`, { query: { limit, page, user_id, ...siteQuery(rest) } }))
+ guard(async ({ site_id, limit, page, user_id, fields, ...rest }) =>
+ ok(
+ pickRowFields(
+ await api.call("GET", `/sites/${site_id}/sessions`, { query: { limit, page, user_id, ...siteQuery(rest) } }),
+ "data",
+ fields
+ )
+ )
)
);
@@ -90,14 +97,21 @@ export function registerRawDataTools(server: McpServer, api: RybbitApiClient, gu
inputSchema: {
site_id: siteIdInput,
page_size: z.number().int().min(1).max(100).default(20),
+ fields: fieldsInput,
...timeInputs,
filters: filtersInput,
},
outputSchema: eventsOutput,
annotations: readOnly,
},
- guard(async ({ site_id, page_size, ...rest }) =>
- ok(await api.call("GET", `/sites/${site_id}/events`, { query: { page_size, ...siteQuery(rest) } }))
+ guard(async ({ site_id, page_size, fields, ...rest }) =>
+ ok(
+ pickRowFields(
+ await api.call("GET", `/sites/${site_id}/events`, { query: { page_size, ...siteQuery(rest) } }),
+ "data",
+ fields
+ )
+ )
)
);
diff --git a/server/src/mcp/tools/shared.ts b/server/src/mcp/tools/shared.ts
index ae333b9c4..52226e03f 100644
--- a/server/src/mcp/tools/shared.ts
+++ b/server/src/mcp/tools/shared.ts
@@ -102,6 +102,30 @@ export const writeTool = { readOnlyHint: false, destructiveHint: false, idempote
export const idempotentWrite = { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false };
export const destructiveTool = { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false };
+/**
+ * Prune each row in `response[key]` to the requested top-level fields. Rows
+ * are wide (sessions and users carry 30+ columns) and every field costs the
+ * client tokens twice, as text and as structuredContent. Unknown field names
+ * are ignored so a stale name never fails the call.
+ */
+export function pickRowFields<T>(response: T, key: string, fields: string[] | undefined): T {
+ if (!fields || !response || typeof response !== "object") {
+ return response;
+ }
+ const rows = (response as Record<string, unknown>)[key];
+ if (!Array.isArray(rows)) {
+ return response;
+ }
+ const wanted = new Set(fields);
+ const pruned = rows.map(row => {
+ if (!row || typeof row !== "object" || Array.isArray(row)) {
+ return row;
+ }
+ return Object.fromEntries(Object.entries(row).filter(([name]) => wanted.has(name)));
+ });
+ return { ...response, [key]: pruned };
+}
+
export function siteQuery(args: TimeArgs & { filters?: FilterArgs }) {
return { ...toTimeQuery(args), ...toFiltersQuery(args.filters) };
}
diff --git a/server/src/mcp/tools/users.ts b/server/src/mcp/tools/users.ts
index 476b89dd7..79a706de1 100644
--- a/server/src/mcp/tools/users.ts
+++ b/server/src/mcp/tools/users.ts
@@ -1,13 +1,14 @@
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import { RybbitApiClient } from "../apiClient.js";
-import { filtersInput, siteIdInput, timeInputs, traitsInput } from "../inputs.js";
+import { fieldsInput, filtersInput, siteIdInput, timeInputs, traitsInput } from "../inputs.js";
import {
destructiveTool,
idempotentWrite,
looseRow,
looseRows,
ok,
+ pickRowFields,
readOnly,
siteQuery,
successOutput,
@@ -45,17 +46,22 @@ export function registerUserTools(server: McpServer, api: RybbitApiClient, guard
identified_only: z.boolean().default(false).describe("Only users identified via identify()"),
search: z.string().optional(),
search_field: z.enum(["username", "name", "email", "user_id"]).optional().describe("Trait/id field the search matches against"),
+ fields: fieldsInput,
...timeInputs,
filters: filtersInput,
},
outputSchema: usersOutput,
annotations: readOnly,
},
- guard(async ({ site_id, page, page_size, sort_by, sort_order, identified_only, search, search_field, ...rest }) =>
+ guard(async ({ site_id, page, page_size, sort_by, sort_order, identified_only, search, search_field, fields, ...rest }) =>
ok(
- await api.call("GET", `/sites/${site_id}/users`, {
- query: { page, page_size, sort_by, sort_order, identified_only, search, search_field, ...siteQuery(rest) },
- })
+ pickRowFields(
+ await api.call("GET", `/sites/${site_id}/users`, {
+ query: { page, page_size, sort_by, sort_order, identified_only, search, search_field, ...siteQuery(rest) },
+ }),
+ "data",
+ fields
+ )
)
)
);