Skip to main content
Glama
Google Analytics MCP Server

Google Analytics MCP Server

by surendranb

get_ga4_data

Read-onlyIdempotent

Retrieve GA4 data with built-in intelligence for better and safer results.

Instructions

Retrieve GA4 data with built-in intelligence for better and safer results.

Returns on success: {"data": [...], "metadata": {...}, "_skills_tip": "..."}. For multi-row pulls (a time series like ['date'], or any breakdown) the result also carries "totals": {metric: value} — GA4 server-side aggregates across all rows. Read the period figure from "totals"; do NOT sum the rows yourself. (Additive metrics sum; rate metrics are period-computed by GA4.) Returns on volume warning: {"warning": "...", "estimated_rows": N, "suggestions": [...]} Returns on error: {"error": "..."}

CRITICAL WORKFLOW — follow this sequence every time:

  1. DISCOVER FIELDS: NEVER guess dimension or metric names. Call search_schema, list_dimension_categories, or list_metric_categories FIRST to verify exact API names for this property. Guessing costs you a failed round-trip.

  2. DISCOVER PATTERN: For any domain-specific analysis, call search_skills('<topic>') BEFORE querying to get the proven methodology — correct dimensions, metrics, filters, and how to interpret the result. One extra call prevents multiple failures. Use for: traffic diagnosis, attribution, ecommerce, channel acquisition, content performance, geo/device segmentation, AI referrals, bot detection.

  3. RETRIEVE: Call get_ga4_data with the verified fields and the skill's pattern.

  4. TROUBLESHOOT: On schema error, invalid field, or filter parse error — do NOT retry by guessing. Your training may predate current GA4 (UA was sunset 2023-07-01). Call search_schema('<keyword>') to find the current name in THIS property, or search_skills('ua-to-ga4' | 'common-metric-names' | 'filter-structures') for the mapping.

FIELD NAMES — GA4 API names vs common wrong guesses:

  • 'screenPageViews' not 'uniquePageviews' or 'pageViews'

  • 'totalUsers' not 'users'

  • 'keyEvents' not 'conversions' or 'goalCompletionsAll'

  • 'sessionKeyEventRate' not 'sessionConversionRate' or 'conversionRate' (GA4 renamed conversions→key events, 2024)

  • 'userEngagementDuration' not 'timeOnPage' or 'avgTimeOnPage'

  • 'averageSessionDuration' not 'avgSessionDuration'

  • 'itemsViewed' not 'itemViews'

  • 'ecommercePurchases' not 'purchases'

  • 'sessionDefaultChannelGroup' not 'sessionDefaultChannelGrouping'

  • 'sessionSource'/'sessionMedium' not 'source'/'medium'

  • All names are camelCase — never snake_case (page_path → pagePath, event_name → eventName)

  • 'bounceRate' and 'newUsers' are correct as-is

DATE RANGES:

  • Format: 'YYYY-MM-DD' or relative strings: '7daysAgo', '30daysAgo', 'yesterday', 'today'

  • 'NdaysAgo' counts back from today, excluding today. 'yesterday' = last complete day.

  • Period comparison (YoY, WoW): run two separate queries with different date ranges, then compare the results. The API does not support multi-period in one call.

SCOPE RULES — incompatible combinations return a 400 error:

  • Session dims (sessionSource, sessionMedium, sessionCampaignName) → use with sessions, bounceRate, sessionKeyEventRate. NOT with eventCount.

  • Event dims (eventName) → use with eventCount. NOT with sessions.

  • User dims (firstUserSource, firstUserMedium) → use with totalUsers, newUsers. NOT sessions.

  • Safe with any metric: date, deviceCategory, country, city, pagePath, pageTitle.

FILTER STRUCTURE:

  • Simple: {"filter": {"fieldName": "sessionSource", "stringFilter": {"value": "google", "matchType": "CONTAINS"}}}

  • AND: {"andGroup": {"expressions": [{"filter": {...}}, {"filter": {...}}]}}

  • OR: {"orGroup": {"expressions": [{"filter": {...}}, {"filter": {...}}]}}

  • NOT: {"notExpression": {"filter": {...}}}

  • Wrong keys that break filters: and_filter→andGroup, or_filter→orGroup, not_filter→notExpression, filters→expressions, field→fieldName

Args: dimensions: GA4 dimension names (verified via schema tools, e.g. ["date", "city"]). metrics: GA4 metric names (verified via schema tools, e.g. ["totalUsers", "sessions"]). date_range_start: Start date — 'YYYY-MM-DD' or '7daysAgo', '30daysAgo', 'yesterday'. date_range_end: End date — 'YYYY-MM-DD' or 'yesterday', 'today'. dimension_filter: Optional FilterExpression dict. camelCase and snake_case both accepted. limit: Max rows to return. Defaults to 1000. estimate_only: If True, returns only estimated row count without fetching data. proceed_with_large_dataset: Set True to bypass the 2500-row volume warning. enable_aggregation: If True, asks GA4 for server-side metric totals whenever a dimension splits the data across rows (e.g. a 7-day ['date'] pull), returned in a "totals" block so the model needn't sum rows. Default True. intent: Short plain-English description of what the user is trying to learn. E.g. "which channels drive most signups", "bot traffic audit for last month".

Tool call template

This tool declares no required parameters. Add optional parameters from the input schema as needed.

{
  "id": 1,
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "arguments": {},
    "name": "get_ga4_data"
  }
}

Input Schema

NameRequiredDescriptionDefault
limitNo
intentNo
metricsNo
dimensionsNo
estimate_onlyNo
date_range_endNoyesterday
date_range_startNo7daysAgo
dimension_filterNo
enable_aggregationNo
proceed_with_large_datasetNo

Schema Changelog

Changes observed during successful MCP inspections.

  1. Changed4 schema fields changedv2.11.9
    • removedInput schema / properties / dimension_filter / additionalProperties
      Removed value: -true
    • addedInput schema / properties / dimension_filter / anyOf
      Added value: +[
      +  {
      +    "additionalProperties": true,
      +    "type": "object"
      +  },
      +  {
      +    "type": "null"
      +  }
      +]
    • removedInput schema / properties / dimension_filter / type
      Removed value: -"object"
    • changedInput schema / properties / intent / default
      Previous value: -nullNew value: +""
  2. Addedv2.8.4
  3. Removedv2.8.3
  4. Changed1 schema field changedv2.7.0
    • addedInput schema / properties / intent
      Added value: +{
      +  "default": null,
      +  "title": "Intent",
      +  "type": "string"
      +}
  5. First observedv2.5.2

TDQS

A4.7/5.0
Behavior5/5

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

Annotations only say readOnly/idempotent/openWorld; the description adds substantial behavior beyond that — the exact success envelope, the separate volume-warning envelope with a 2500-row threshold and bypass flag, the error envelope, the server-side 'totals' aggregation and the instruction not to re-sum rows, plus scope rules that produce 400 errors. This is disclosure an agent cannot get from the annotations or schema.

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

Conciseness4/5

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

Well-structured with caps headers and numbered steps, but the response-shape block is front-loaded ahead of the critical workflow, and there is real duplication — the 'totals' behavior appears both in the return-shape section and again under enable_aggregation, and date-range formats are stated twice. The field-name mapping list is long but each line encodes a distinct, costly-to-guess correction, so it earns its space.

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

Completeness5/5

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

For a 10-parameter, zero-schema-coverage tool with no output schema, the definition covers everything an agent needs: return envelopes for success/warning/error, the discovery prerequisite, scope constraints that cause 400s, filter grammar, and correct field naming. Nothing material is left to inference before a first call.

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

Parameters5/5

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

Schema description coverage is 0%, so the description carries the full burden and does: it explains each of the 10 parameters with examples (dimensions/metrics as verified lists, date formats including 'NdaysAgo' semantics, filter dict structure with AND/OR/NOT shapes, limit default, estimate_only, the 2500-row meaning of proceed_with_large_dataset, and what enable_aggregation changes in the response). The only residue is that 'intent' is described loosely, but its purpose and an example are given.

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

Purpose4/5

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

States a specific verb and resource — 'Retrieve GA4 data' — and the surrounding workflow makes clear it is the terminal reporting/query tool, distinct from schema and skill discovery siblings. The opening clause 'with built-in intelligence for better and safer results' is filler that adds no discriminating information, but the rest of the definition removes any ambiguity about what is retrieved.

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

Usage Guidelines5/5

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

Gives an explicit, numbered when-to-use sequence: discover fields via search_schema/list_*_categories, discover methodology via search_skills, then call this tool, then troubleshoot via search_schema or search_skills('ua-to-ga4'). It also names concrete usage domains (traffic diagnosis, attribution, ecommerce, bot detection) and states a clear prohibition ('NEVER guess dimension or metric names') with the failure mode spelled out.

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