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
- Go to the Google Cloud Console
- 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
- In the GCP Console, navigate to "APIs & Services" → "Library"
- Search for and enable "Google Analytics Data API" This is the correct API for GA4 data access
- Do NOT use "Google Analytics API" (legacy version for Universal Analytics)
Step 3: Create a Service Account
- Go to "APIs & Services" → "Credentials"
- Click "Create Credentials" → "Service Account"
- Enter a name (e.g., "ga4-mcp-server")
- Click "Create and Continue"
- Skip role assignment for now → Click "Done"
Step 4: Download Service Account Key
- Click on your newly created service account
- Go to the "Keys" tab
- Click "Add Key" → "Create New Key"
- Select "JSON" format → Click "Create"
- 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
- Open the downloaded JSON file and copy the
client_emailvalue
Format: [email protected] - Go to Google Analytics
- Select your GA4 property
- Click "Admin" (gear icon at bottom left)
- Under Property → Click "Property access management"
- Click "+" → "Add users"
- Paste the service account email
- Select "Viewer" role
- Uncheck "Notify new users by email"
- Click "Add"
Step 6: Get Your GA4 Property ID
- In Google Analytics, go to "Admin" → "Property details"
- 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
pip install google-analytics-mcp
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
- Convert your natural language to proper GA4 API calls
- Validate parameters (ensuring dimensions aren't empty, etc.)
- Execute the query against your GA4 data
- 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
- Test API Access: Run the credential test script
- Check Data Availability: Use the diagnostics script to see your data range
- 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
- Secure Credentials: Store your service account JSON file securely
- Limit Permissions: Use "Viewer" role (minimum required)
- Environment Variables: Consider using environment variables for sensitive data
- 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.