Google Analytics MCP Server
GA4 MCP server for AI agents to discover GA4 schema, run analytics queries, and get setup/troubleshooting guidance.
Query GA4 data with dimensions, metrics, date ranges, filters, row limits, volume estimates, and server-side totals.
Search and browse GA4 dimensions/metrics by keyword, category, or full property schema.
List GA4 properties (and, per README, accounts) with access context.
Run real-time reports for active users/events (README).
Load built-in analytical playbooks/skills for traffic, attribution, ecommerce, AI referrals, bot detection, and more.
Troubleshoot schema, filter, IAM/403, and setup errors.
Interactively fix missing property ID, credentials, or GA4 access without restart.
Check PyPI for server updates and upgrade instructions.
Provides access to Google Ads data within Google Analytics 4, allowing queries about campaign, ad group, and keyword performance.
Connects to Google Analytics 4 data, enabling natural language queries about website traffic, user behavior, and analytics with access to 200+ GA4 dimensions and metrics.
Uses Google Cloud for service account creation and API access to connect with Google Analytics data.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Google Analytics MCP Server show me last week's top 5 pages by pageviews"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Google Analytics 4 (GA4) MCP Server 📊
Model Context Protocol (MCP) server for Google Analytics 4: real-time query exploration, schema discovery, metric aggregation, and audience insights for AI agents.
🌐 Live Documentation & Web Portal: https://ga4mcp.com/
⚡ Quickstart
# 1-Line Universal Installer (Auto-configures Claude Desktop, Cursor, Claude Code, Antigravity, VS Code, Zed, Windsurf)
curl -fsSL "https://ga4.builditwithai.xyz/install" | bash
# Or run directly via your preferred runtime:
uvx google-analytics-mcp
uvx --from google-analytics-mcp ga4-mcp-server
python -m ga4_mcp
npx -y @surendranb/google-analytics-mcpRelated MCP server: Google Analytics MCP Server
🤖 Client Setup
A. Claude Code (CLI)
claude mcp add google-analytics -- uvx google-analytics-mcpB. Cursor & Google Antigravity (mcp.json)
{
"mcpServers": {
"google-analytics": {
"command": "uvx",
"args": ["google-analytics-mcp"]
}
}
}C. Claude Desktop (claude_desktop_config.json)
{
"mcpServers": {
"google-analytics": {
"command": "uvx",
"args": ["google-analytics-mcp"],
"env": {
"GA4_PROPERTY_ID": "your_ga4_property_id",
"GOOGLE_APPLICATION_CREDENTIALS": "/path/to/service_account.json"
}
}
}
}D. VS Code (Cline / Roo Code / Continue)
{
"mcpServers": {
"google-analytics": {
"command": "npx",
"args": ["-y", "@surendranb/google-analytics-mcp"]
}
}
}🛠️ Tools & Capabilities
Tool Name | Parameters | Description | Return Type |
|
| Runs multi-dimensional GA4 reports with automated metric totals and server-side aggregation. |
|
| (none) | Lists all accessible Google Analytics accounts and permission levels. |
|
|
| Lists all GA4 properties associated with an account. |
|
|
| Fetches complete dimension and metric schemas, custom definitions, and compatibility rules. |
|
|
| Queries real-time active users and event counts from the last 30 minutes. |
|
|
| Searches built-in GA4 analytical playbooks (e-commerce, channel attribution, bot filtering). |
|
|
| Dynamically loads procedural skills and analytical guides from GitHub. |
|
| (none) | Lists all available live GA4 analytical skills. |
|
🧠 Dynamic Skills & Guided Playbooks
This server ships with built-in analytical recipes that load dynamically from GitHub:
traffic-diagnosis: Step-by-step root cause analysis for sudden traffic drops.channel-acquisition: Best-practice channel grouping and attribution modeling.ecommerce-analysis: Revenue, item purchase rate, and conversion funnel analysis.ai-referral-analysis: Tracks and isolates referral traffic from ChatGPT, Claude, Perplexity, and Gemini.
🔒 Telemetry & Privacy
This package collects anonymous, non-PII diagnostic telemetry (command executions, latency, error codes) to improve tool reliability. No queries, user credentials, personal data, source code, or environment variables are ever collected or stored.
You can opt out anytime by setting either of the following environment variables:
export DO_NOT_TRACK=1
# or
export MCP_TELEMETRY_OPT_OUT=1📄 License
MIT License. See LICENSE for details.
Available Tools
12 toolscheck_for_updatesARead-onlyIdempotent
Check PyPI for newer versions of this MCP server and get upgrade instructions.
Inputs: no named parameters.
get_dimensions_by_categoryARead-onlyIdempotent
Return all dimensions in a specific category with their API names and descriptions.
Returns: {"dimension_api_name": "description", ...}
The category name must exactly match a value returned by list_dimension_categories. Use search_schema instead if you already have a keyword — it is faster and more targeted than browsing by category.
Args: category: Exact category name from list_dimension_categories (case-insensitive).
Inputs: category (required).
get_ga4_dataARead-onlyIdempotent
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:
DISCOVER FIELDS: NEVER guess dimension or metric names. Call
search_schema,list_dimension_categories, orlist_metric_categoriesFIRST to verify exact API names for this property. Guessing costs you a failed round-trip.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.RETRIEVE: Call get_ga4_data with the verified fields and the skill's pattern.
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, orsearch_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".
Inputs: limit, intent, metrics, dimensions, +6 more.
get_metrics_by_categoryARead-onlyIdempotent
Return all metrics in a specific category with their API names and descriptions.
Returns: {"metric_api_name": "description", ...}
The category name must exactly match a value returned by list_metric_categories. Use search_schema instead if you already have a keyword — it is faster and more targeted than browsing by category.
Args: category: Exact category name from list_metric_categories (case-insensitive).
Inputs: category (required).
get_property_schemaARead-onlyIdempotent
Returns the complete schema for the configured GA4 property, including all available dimensions and metrics (standard and custom). Warning: This can be a very large object (10k+ tokens). Use search_schema for most discovery tasks.
Inputs: no named parameters.
get_troubleshooting_guideARead-onlyIdempotent
Returns the troubleshooting/setup guide for a topic, served from inside the server (no network needed). Use whenever you hit a schema error, dimension_filter parse error, IAM / 403 authorization error, or a boot-time setup error.
Args: topic: One of "setup", "iam", or "schema".
Inputs: topic (required). Returns: result
list_dimension_categoriesARead-onlyIdempotent
List all dimension categories for this GA4 property, with a count of dimensions in each category.
Returns: {"dimension_categories": {"Category Name": count, ...}}
Use this as the first step in dimension exploration — browse categories, then call get_dimensions_by_category with the name that fits your analysis. Use search_schema instead if you already have a keyword to search for.
Inputs: no named parameters.
list_metric_categoriesARead-onlyIdempotent
List all metric categories for this GA4 property, with a count of metrics in each category.
Returns: {"metric_categories": {"Category Name": count, ...}}
Use this as the first step in metric exploration — browse categories, then call get_metrics_by_category with the name that fits your analysis. Use search_schema instead if you already have a keyword to search for.
Inputs: no named parameters.
list_propertiesBRead-onlyIdempotent
List all GA4 properties associated with an account.
Inputs: account_id.
search_schemaARead-onlyIdempotent
Search for a keyword across all dimensions and metrics for this property. Returns a ranked list of up to 10 matching fields scored by relevance.
Returns: {"top_results": {"DIMENSION: api_name": score, "METRIC: api_name": score, ...}}
Use this when you have a concept ("engagement", "revenue", "channel") and need exact API field names before calling get_ga4_data. Use list_dimension_categories or list_metric_categories instead if you want to browse all available fields without a specific keyword.
Args: keyword: One or more keywords to search for (e.g., "user", "campaign revenue").
Inputs: keyword (required).
search_skillsARead-onlyIdempotent
Fetch analytical recipes and how-to guides from the GA4 skills library.
Skills are domain-specific playbooks for common GA4 analysis patterns — exact dimensions, metrics, filters, and interpretation logic for each use case. Call this BEFORE querying get_ga4_data for any domain-specific analysis.
Available skills: setup, gcp-setup, service-account-setup, traffic-diagnosis, attribution-scope, channel-acquisition, content-performance, geo-device-segmentation, ecommerce-analysis, ai-referral-analysis, bot-traffic-detection, common-metric-names, filter-structures, custom-dimensions, compatible-combinations, ua-to-ga4, date-ranges, ga4-limitations.
Usage:
search_skills("") → returns full index of all skills
search_skills("setup") → returns the GCP service-account setup playbook
search_skills("ecommerce") → returns the ecommerce-analysis skill
search_skills("ua-to-ga4") → returns the UA→GA4 field name mapping
Args: query: A skill name (exact slug) or empty string to browse the full index.
Inputs: query (required). Returns: result
setup_ga4_accessARead-onlyIdempotent
Interactively fix a broken GA4 MCP setup (missing property ID, missing or expired credentials, or missing GA4 access) by asking the user for the needed input through the client, then re-initializing without a restart. Call this whenever a configuration or authentication error is reported.
Inputs: no named parameters. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 12 tools
Most tools are clearly distinct, but the schema-discovery cluster (search_schema, get_property_schema, list_dimension_categories, get_dimensions_by_category, list_metric_categories, get_metrics_by_category) creates six similar-feeling tools. What saves it is the explicit cross-referencing in descriptions that tells the agent when to prefer search_schema versus category browsing. setup_ga4_access and get_troubleshooting_guide('setup') also overlap slightly around setup errors.
All names are snake_case with clear verb prefixes (get_, list_, search_, check_, setup_) following a predictable verb_noun pattern. No camelCase/snake_case mixing at the tool level. Very consistent throughout.
12 tools is well within a reasonable scope for a data-analytics server and each maps to a distinct workflow phase (discovery, retrieval, troubleshooting, setup). The single meta-tool (check_for_updates) is slightly off-domain but harmless. A mild over-allocation to schema-browsing tools keeps it from a 5.
The surface covers the core workflow well: property listing, schema discovery, data retrieval, skills/recipes, troubleshooting, and interactive setup repair. Notable gaps include no explicit way to select/switch the active property (only list_properties) and no realtime or admin/configuration data beyond setup repair, but the analytics read path is complete.
Maintenance
Related MCP Connectors
Connect Google Analytics to ChatGPT. Query GA4 data in plain English and get instant insights.
Google Search Console, GA4, Bing Webmaster and PageSpeed MCP for Claude, ChatGPT, Cursor. Free.
GA4, Google Ads and Search Console in Claude. Read-only OAuth, multi-account for agencies.
Ask Claude, ChatGPT or any MCP client about your Google Analytics 4 and Search Console data, plus Bing Webmaster Tools when connected, for every site you manage, with one Google sign-in. Read only: traffic changes, why a page dropped, top queries and pages, quick-win queries, AI assistant referral traffic, URL indexing, sitemaps, custom GA4 reports and client reports. Built for site owners and agencies with many sites. Free for 1 site.
Related MCP Servers
- AlicenseAqualityCmaintenanceConnects MCP clients like Claude Desktop to Google Analytics 4 Data API, enabling natural language queries for reports, top pages, traffic sources, conversions, realtime users, and period comparisons.776 PyPIMIT
- AlicenseNot gradedqualityDmaintenanceEnables querying Google Analytics 4 data using natural language through MCP clients like Claude and Cursor, supporting 200+ dimensions and metrics for traffic, user behavior, and e-commerce analysis.MIT
- FlicenseAqualityDmaintenanceEnables natural language querying of Google Analytics 4, Google Search Console, Meta Ads, and Google Ads data through Claude.23-
- FlicenseAqualityDmaintenanceConnects Claude to Google Analytics 4 for querying website analytics via natural language, enabling traffic summaries, top pages, traffic sources, and user engagement.4-