Skip to main content
Glama
ZLeventer

Google Analytics MCP Server

ga4_run_report

Run custom GA4 reports by specifying any dimensions and metrics. Build reports beyond preset tools using flexible date ranges, filters, and sorting.

Instructions

Flexible GA4 Data API runReport. Pass any dimensions + metrics. Use for custom reports the preset tools don't cover.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
dimensionsYesGA4 dimension API names, e.g. ['sessionSource','sessionMedium','landingPage']
metricsYesGA4 metric API names, e.g. ['sessions','totalUsers','conversions']
start_dateNoStart date: YYYY-MM-DD, NdaysAgo, yesterday, or today28daysAgo
end_dateNoEnd date: YYYY-MM-DD, NdaysAgo, yesterday, or todayyesterday
property_idNoOverride GA4_PROPERTY_ID env var for this call
limitNoMax rows to return
dimension_filterNoOptional string filter: 'dimensionName=value' (exact) or 'dimensionName~regex'
order_byNoMetric or dimension to sort by, prefix with '-' for desc. Default: first metric desc

Implementation Reference

  • The main handler function `runReport` that executes the GA4 Data API runReport with provided dimensions, metrics, date range, filter, and order. Calls `getClient().runReport()` and formats the result.
    export async function runReport(args: z.infer<z.ZodObject<typeof runReportSchema>>) {
      const [res] = await getClient().runReport({
        property: getProperty(args.property_id),
        dateRanges: toDateRange(args.start_date, args.end_date),
        dimensions: args.dimensions.map((name) => ({ name })),
        metrics: args.metrics.map((name) => ({ name })),
        dimensionFilter: parseFilter(args.dimension_filter),
        orderBys: parseOrderBy(args.order_by, args.metrics[0]),
        limit: args.limit as unknown as number,
      });
      return formatReport(res);
    }
  • Zod schema `runReportSchema` defining the input validation: dimensions array, metrics array, date range, optional dimension_filter, optional order_by.
    export const runReportSchema = {
      dimensions: z.array(z.string()).describe("GA4 dimension API names, e.g. ['sessionSource','sessionMedium','landingPage']"),
      metrics: z.array(z.string()).describe("GA4 metric API names, e.g. ['sessions','totalUsers','conversions']"),
      ...dateRange,
      dimension_filter: z.string().optional().describe("Optional string filter: 'dimensionName=value' (exact) or 'dimensionName~regex'"),
      order_by: z.string().optional().describe("Metric or dimension to sort by, prefix with '-' for desc. Default: first metric desc"),
    };
  • src/index.ts:46-53 (registration)
    Tool registration for 'ga4_run_report' using `server.tool()` with the schema and a handler that delegates to `runReport()`.
    server.tool(
      "ga4_run_report",
      "Flexible GA4 Data API runReport. Pass any dimensions + metrics. Use for custom reports the preset tools don't cover.",
      runReportSchema,
      async (args) => {
        try { return ok(await runReport(args)); } catch (e) { return err(e); }
      }
    );
  • Helper function `formatReport` that transforms the API response into a cleaned array of rows with dimension/metric headers.
    function formatReport(res: any) {
      const rows = (res.rows ?? []).map((r: any) => {
        const out: Record<string, string | number> = {};
        (res.dimensionHeaders ?? []).forEach((h: any, i: number) => {
          out[h.name] = r.dimensionValues?.[i]?.value ?? "";
        });
        (res.metricHeaders ?? []).forEach((h: any, i: number) => {
          const v = r.metricValues?.[i]?.value ?? "0";
          const n = Number(v);
          out[h.name] = Number.isFinite(n) ? n : v;
        });
        return out;
      });
      return { rowCount: res.rowCount ?? rows.length, rows };
    }
  • Helper functions `parseFilter` and `parseOrderBy` used by the handler to parse the optional dimension filter and ordering.
    function parseFilter(f?: string) {
      if (!f) return undefined;
      const exact = f.match(/^([^=~]+)=(.+)$/);
      if (exact) return { filter: { fieldName: exact[1].trim(), stringFilter: { value: exact[2].trim() } } };
      const re = f.match(/^([^~]+)~(.+)$/);
      if (re) return { filter: { fieldName: re[1].trim(), stringFilter: { matchType: "FULL_REGEXP" as const, value: re[2].trim() } } };
      return undefined;
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are present, so the description must fully disclose behavioral traits. It only states 'Flexible GA4 Data API runReport' and 'Pass any dimensions + metrics', lacking details on rate limits, data freshness, or whether the operation is read-only. The minimal description does not adequately cover behavioral aspects.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two sentences, front-loading the key purpose ('Flexible GA4 Data API runReport') and immediately stating usage context. Every sentence is necessary and concise, with no extraneous words.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of 8 parameters, no output schema, and no annotations, the description is too minimal. It does not explain return format, error handling, or limitations (e.g., maximum rows). For a flexible API tool, the agent needs more context to use it correctly.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 100% description coverage for all 8 parameters. The description adds no new semantic value beyond the schema's existing parameter descriptions, such as the examples and default values. Baseline score of 3 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool is for flexible GA4 Data API runReport, specifying it handles arbitrary dimensions and metrics. It explicitly distinguishes from sibling preset tools by stating 'Use for custom reports the preset tools don't cover.'

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear guidance on when to use this tool ('custom reports the preset tools don't cover'), implying it should not be used when preset tools suffice. However, it does not explicitly list or exclude alternative sibling tools.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/ZLeventer/google-analytics-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server