Analytics
Google Analytics 4 MCP Workflow Setup Tutorial
Google Analytics 4 MCP Workflow Setup Tutorial
A comprehensive guide to connect Google Analytics 4 data to AI tools using Model Context Protocol (MCP).

Overview

This tutorial walks you through setting up a workflow to query your Google Analytics 4 (GA4) data through AI assistants using Model Context Protocol (MCP). By the end, asking questions like “Show me user trends over the past month” will provide real GA4 data results.

Prerequisites

  • Google Analytics 4 property with data collection active
  • Google Cloud Platform account
  • Python 3.8+ installed
  • Basic command line proficiency

Part 1: Google Cloud Platform Setup

1. Create or Select a GCP Project

2. Enable the Correct APIs

Critical: Enable "Google Analytics Data API" (for GA4)
  • In GCP Console, go to APIs & ServicesLibrary
  • Enable Google Analytics Data API
  • Do NOT use "Google Analytics API" (legacy)

3. Create a Service Account

  • APIs & Services → Credentials
  • Create Credentials → Service Account
  • Name the account (e.g., ga4-mcp-server)
  • Click “Create and Continue”, skip role assignment, then click “Done”

4. Download Service Account Key

  • Select your new service account
  • Go to "Keys" tab, then "Add Key" → "Create New Key"
  • Choose "JSON" format and download the key
  • Keep the JSON file secure (you'll need its path)

Part 2: Google Analytics 4 Configuration

5. Add Service Account to GA4

  1. Copy the client_email from your JSON key file
  2. Go to Google Analytics → select GA4 property
  3. Click Admin (gear icon) → Property Access Management
  4. Click "+" → Add users → paste service account email
  5. Select Viewer role → uncheck email notification → Add

6. Get Your GA4 Property ID

  1. In GA4 Admin → Property details, copy your Property ID (numeric only)
  2. Note: This is different from the Measurement ID (starts with G-)

Part 3: Install and Configure MCP Server

7. Install the GA4 MCP Server

Option A: Install via pip (Recommended)
pip install google-analytics-mcp
Option B: Install from source
git clone https://github.com/surendranb/google-analytics-mcp.git
cd google-analytics-mcp
python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt

8. Test Your Setup

import os
from google.analytics.data_v1beta import BetaAnalyticsDataClient

# Set credentials path
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/path/to/your/service-account-key.json"

# Test connection
try:
    client = BetaAnalyticsDataClient()
    print("✅ GA4 credentials working!")
except Exception as e:
    print(f"❌ Error: {e}")

Part 4: Workflow Scripts Setup

9. Download the Workflow Scripts

  • Schema Extraction Script
  • Request Execution Script
  • Request Validator Script

10. Configure the Scripts

mcp_config = {
    "mcpServers": {
        "ga4-analytics": {
            "command": "ga4-mcp-server",
            "env": {
                "GOOGLE_APPLICATION_CREDENTIALS": "/path/to/your/service-account-key.json",
                "GA4_PROPERTY_ID": "your-property-id"
            }
        }
    }
}

Part 5: Using the Workflow

11. Extract GA4 Schema

# This gets all available tools, metrics categories, dimension categories,
# and parameter information
schema_data = get_complete_ga4_schema()

12. Generate Natural Language Queries

  • "Show me user growth over the past month"
  • "What are my top traffic sources by country?"
  • "Compare bounce rates between mobile and desktop"
  • "Display daily page views for the last two weeks"

13. Execute and Validate Queries

  1. Convert your natural language query to GA4 API calls
  2. Validate parameters (e.g., check non-empty dimensions)
  3. Execute against your GA4 data
  4. Return structured results

Part 6: Understanding the Results

Data Format Example

{
  "data": [
    { "date": "20240730", "newUsers": "10" }
  ],
  "metadata": {
    "total_rows": 15,
    "returned_rows": 15,
    "applied_optimizations": ["Intelligent sorting applied"]
  }
}
Common Data Limitations:
  • Only includes data collected since GA4 tracking started
  • Recent data (24-48 hours) may be incomplete
  • Large queries may be automatically optimized

Troubleshooting

Issue Solution
"No module named ga4_mcp_server" Ensure you're in the correct Python environment with the required package installed
"Dimensions list cannot be empty" The request validator will auto-fix this by adding a default dimension
"Permission denied" errors Make sure the service account has "Viewer" role access to your GA4 property
"API not enabled" errors Double-check "Google Analytics Data API" is enabled

Verification Steps

  • Test API access with the credential test script
  • Run a diagnostic script to confirm your data range
  • Validate queries using the request validator before execution

Advanced Usage

Custom Dimensions & Metrics

  • All standard GA4 dimensions (date, country, device, etc.)
  • Custom dimensions and metrics
  • Custom conversion events

Query Optimization

  • Automatic data volume warnings and controls
  • Server-side aggregation for efficient queries
  • Intelligent sorting for relevance

Security Best Practices

  1. Store your service account JSON file securely
  2. Use the minimum "Viewer" access required
  3. Prefer environment variables for sensitive data
  4. Rotate service account keys regularly

Conclusion

You now have a robust workflow for querying Google Analytics 4 with natural language using AI and MCP. The system simplifies GA4 API usage, empowering intuitive analytics and reporting.

Next steps:
  • Try different query styles
  • Integrate with your favorite AI tools
  • Set up automated reports
  • Explore advanced GA4 features
For support and advanced details, review the original MCP server documentation and the inspiring Medium article.
Frevana Logo
Created with Frevana.com
© 2025 Frevana