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 will help you set up a complete workflow to query your Google Analytics 4 data using natural language through AI assistants. By the end, you'll be able to ask questions like "Show me user trends over the past month" and get actual GA4 data.

playlist_add_check Prerequisites

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

Part 1: Google Cloud Platform Setup

Step 1: Create or Select a GCP Project

  1. Go to the Google Cloud Console
  2. Either create a new project or select an existing one:
    • New project: Click "New Project" → Enter project name → Click "Create"
    • Existing project: Select from the dropdown menu

Step 2: Enable the Correct APIs

Critical: Make sure you enable the right API to avoid common setup issues.
  1. In the GCP Console, navigate to "APIs & Services""Library"
  2. Search for and enable "Google Analytics Data API" This is the correct API for GA4 data access
  3. Do NOT use "Google Analytics API" (legacy version for Universal Analytics)

Step 3: Create a Service Account

  1. Go to "APIs & Services""Credentials"
  2. Click "Create Credentials""Service Account"
  3. Enter a name (e.g., "ga4-mcp-server")
  4. Click "Create and Continue"
  5. Skip role assignment for now → Click "Done"

Step 4: Download Service Account Key

  1. Click on your newly created service account
  2. Go to the "Keys" tab
  3. Click "Add Key""Create New Key"
  4. Select "JSON" format → Click "Create"
  5. Save the downloaded JSON file securely (you'll need its path later)

Part 2: Google Analytics 4 Configuration

Step 5: Add Service Account to GA4

  1. Open the downloaded JSON file and copy the client_email value
    Format: [email protected]
  2. Go to Google Analytics
  3. Select your GA4 property
  4. Click "Admin" (gear icon at bottom left)
  5. Under Property → Click "Property access management"
  6. Click "+""Add users"
  7. Paste the service account email
  8. Select "Viewer" role
  9. Uncheck "Notify new users by email"
  10. Click "Add"

Step 6: Get Your GA4 Property ID

  1. In Google Analytics, go to "Admin""Property details"
  2. Copy the Property ID (numeric format, e.g., 123456789)
    This is different from the "Measurement ID" (starts with G-)

Part 3: Install and Configure MCP Server

Step 7: Install the GA4 MCP Server

Install via pip (Recommended)
pip install google-analytics-mcp
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

Step 8: Test Your Setup

Create a test script to verify your credentials:

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

Step 9: Download the Workflow Scripts

You'll need these three main scripts for the complete workflow:

  • Schema Extraction Script — Gets all available GA4 metrics and dimensions
  • Request Execution Script — Executes queries against GA4
  • Request Validator — Validates and fixes common query issues

Step 10: Configure the Scripts

Update the configuration in each script with your actual paths:

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

Part 5: Using the Workflow

Step 11: Extract GA4 Schema

Run the schema extraction script to get all available metrics and dimensions:

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

Step 12: Generate Natural Language Queries

Use the intelligent prompt system to convert natural language to GA4 queries.
Example 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

Step 13: Execute and Validate Queries

  1. Convert your natural language to proper GA4 API calls
  2. Validate parameters (ensuring dimensions aren't empty, etc.)
  3. Execute the query against your GA4 data
  4. Return structured results

Part 6: Understanding the Results

Data Format

The workflow returns data in this structure:

{
  "data": [
    {
      "date": "20240730",
      "newUsers": "10"
    }
  ],
  "metadata": {
    "total_rows": 15,
    "returned_rows": 15,
    "applied_optimizations": ["Intelligent sorting applied"]
  }
}

Common Data Limitations

  • Data History: GA4 only returns data from when tracking started
  • Processing Delay: Recent data (last 24-48 hours) may not be complete
  • API Limits: Large queries may be automatically optimized or limited

Troubleshooting

Common Issues and Solutions

  • "No module named ga4_mcp_server"
    Solution: Ensure you're using the correct Python environment where the package is installed
  • "Dimensions list cannot be empty"
    Solution: The validator script automatically fixes this by adding a default dimension
  • "Permission denied" errors
    Solution: Verify the service account has "Viewer" access to your GA4 property
  • "API not enabled" errors
    Solution: Double-check you enabled "Google Analytics Data API" (not the legacy version)

Verification Steps

  1. Test API Access: Run the credential test script
  2. Check Data Availability: Use the diagnostics script to see your data range
  3. Validate Queries: Use the request validator before executing

Advanced Usage

Custom Dimensions and Metrics

  • Standard GA4 dimensions (date, country, device, etc.)
  • Custom dimensions you've configured
  • Standard metrics (users, sessions, revenue, etc.)
  • Custom metrics and conversion events

The workflow automatically discovers all available dimensions and metrics in your GA4 property.

Query Optimization

  • Automatic data volume warnings
  • Server-side aggregation when beneficial
  • Intelligent sorting for most relevant results
  • Limit controls to prevent overwhelming responses

Security Best Practices

  1. Secure Credentials: Store your service account JSON file securely
  2. Limit Permissions: Use "Viewer" role (minimum required)
  3. Environment Variables: Consider using environment variables for sensitive data
  4. Regular Rotation: Periodically rotate service account keys

Conclusion

You now have a complete workflow to query your Google Analytics 4 data using natural language! The system handles the complexity of GA4 API calls while providing an intuitive interface for data analysis.

  • Experiment with different query types
  • Integrate with your preferred AI tools
  • Set up automated reporting workflows
  • Explore advanced GA4 dimensions and metrics

For support and updates, refer to the original MCP server documentation and the Medium article that inspired this workflow.