Building a Google Analytics MCP Server in Python: Unlock AI-Powered Analytics Automation


Imagine having an AI agent that can instantly pull your website's traffic data, analyze user behavior patterns, and generate insights on command.
No more switching between dashboards, no more manual data exports, and no more waiting for reports.
This isn't science fiction—it's what happens when you combine Google Analytics with the Model Context Protocol (MCP) using Python.
Today, we'll build a powerful MCP server that transforms your analytics data into an AI-accessible resource.
And I swear … I will never use Google Analytics dashboard again.
What is Model Context Protocol and Why Should You Care?
The Model Context Protocol represents a paradigm shift in how AI systems access and interact with external data sources.
Think of MCP as a universal connector that allows AI models to extend its context using your business systems, databases, and APIs.
Instead of manually copying and pasting data between applications, MCP creates a direct bridge between your AI agents such as Claude Desktop and your data.
For analytics professionals and developers, this means unprecedented automation capabilities.
Your AI tools can now query Google Analytics data, generate reports, identify trends, and even suggest optimizations—all through natural language commands. The traditional barriers between human insight and machine processing dissolve completely.
Architecture Overview: How the Components Work Together
Our Google Analytics MCP server follows a clean, modular architecture that separates concerns and maximizes maintainability.
Infrastructure setup
The authentication flow to access Google Analytics API uses Google Cloud service accounts.
Service accounts eliminate the need for OAuth flows and ensure your MCP server can operate autonomously. This design supports both development environments and production deployments seamlessly.
Google Cloud setup involves several critical steps that determine your server's success.
So, create a Google Cloud project and enable the Google Analytics Data API through the Cloud Console. Then, generate a service account with Analytics Data API Viewer permissions and finally download the JSON key file.
Project Dependencies
For dependencies manage, we use uv
. The uv
package manager provides fast dependency resolution and virtual environment management.
[project]
name = "ga-mcp-py"
version = "0.1.0"
description = "Google Analytics MCP (Model Context Protocol) Python implementation"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"google-api-python-client",
"oauth2client",
"mcp[cli]",
"python-dotenv"
]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["."]
include = [
"main.py",
"README.md",
"pyproject.toml"
]
Next step is to install the dependencies.
uv sync
Environment variables
Create a .env
file in your project root containing your service account file path and GA4 property ID.
Remember to never commit sensitive credentials to version control—use environment variables and secure key management practices.
GOOGLE_APPLICATION_CREDENTIALS=google_analytics_api_svc_acct.json
GA4_PROPERTY_ID=your-ga4-property-id
Application Implementation - Google Analytics client
First step is to initialize a Google Analytics client using service account authentication (file generated and downloaded before), ensuring secure and reliable API access.
The Google Analytics client initialization handles authentication complexity transparently.
# Constants
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
# Global analytics service
analytics_service = None
# Load environment variables from .env file
load_dotenv()
def init_ga4_client():
"""Initialize Google Analytics 4 client using service account."""
global analytics_service
# Get service account file path from environment variable
service_account_file = os.getenv('GOOGLE_APPLICATION_CREDENTIALS')
if not service_account_file:
raise ValueError("GOOGLE_APPLICATION_CREDENTIALS environment variable is required")
if not os.path.exists(service_account_file):
raise FileNotFoundError(f"Service account file not found: {service_account_file}")
# Get property ID from environment variable
property_id = os.getenv('GA4_PROPERTY_ID')
if not property_id:
raise ValueError("GA4_PROPERTY_ID environment variable is required")
# Authenticate using service account credentials
credentials = service_account.Credentials.from_service_account_file(
service_account_file, scopes=SCOPES)
# Build the Google Analytics Data API client (for GA4)
analytics_service = build('analyticsdata', 'v1beta', credentials=credentials)
Application Implementation - FastMCP server
Next step is initialize the FastMCP. It handles the MCP protocol implementation, tool registration, and communication with AI systems.
# imports
from mcp.server.fastmcp import FastMCP
# Initialize FastMCP server
mcp = FastMCP("google-analytics-mcp")
Next step is to register the tools. Each tool function corresponds to a specific analytics capability, from basic reporting to advanced real-time data access.
@mcp.tool()
async def query_analytics(start_date: str, end_date: str, metrics: List[str],
dimensions: List[str], filters: Optional[Dict] = None) -> str:
"""Query Google Analytics data with custom metrics, dimensions, and filters."""
try:
property_id = os.getenv('GA4_PROPERTY_ID')
request_body = {
'dateRanges': [{'startDate': start_date, 'endDate': end_date}],
'metrics': [{'name': metric} for metric in metrics],
'dimensions': [{'name': dimension} for dimension in dimensions]
}
if filters:
request_body['dimensionFilter'] = filters
response = analytics_service.properties().runReport(
property=f'properties/{property_id}',
body=request_body
).execute()
result = format_analytics_response(response)
return json.dumps(result, indent=2)
except Exception as e:
return json.dumps({"error": str(e)}, indent=2)
In practice, I’ve registered a couple of tools for this MCP Server.
This MCP server provides the following tools:
query_analytics: Query Google Analytics data with custom metrics, dimensions, and filters
get_realtime_data: Get real-time Google Analytics data
get_traffic_sources: Get traffic source analysis data
get_user_demographics: Get user demographics data
get_page_performance: Get page performance metrics
get_conversion_data: Get conversion and event data
get_custom_report: Get custom analytics report with flexible parameters
You can check the codebase here: https://github.com/juancolamendy/mcp-tutorials/tree/main/ga_mcp_py
Integrate with Claude Desktop
Claude Desktop integration requires specific configuration syntax and path management.
The configuration file must specify the correct Python environment and project paths.
Environment variable inheritance ensures your MCP server accesses the correct credentials and property settings.
Open the file ~/Library/Application\ Support/Claude/claude_desktop_config.json
and edit it with the following settings. Change the path
, GOOGLE_APPLICATION_CREDENTIALS
and GA4_PROPERTY_ID
according to your own scenario.
{
"mcpServers": {
"google-analytics": {
"command": "uv",
"args": [
"--directory",
"<path>/ga_mcp_py",
"run",
"main.py"
],
"env": {
"GOOGLE_APPLICATION_CREDENTIALS": "<path>/svc_acct.json",
"GA4_PROPERTY_ID": "12346789"
}
}
}
}
Let’s see my own integration.
I have a website under the domain scribamax.com
. I have Google Analytics running for this website with real-time data. I grabbed the property id and use it as my environment variable for this MCP server running locally.
So, let's analyze the traffic metrics on the last 90 days.
So, let’s send a request to Claude (my agent) that will use the Google Analytics tools to get real-time data to analyze.
The output is so good, that I swear I will never use Google Analytics dashboard again, that I found kind of confusing to me sometimes.
Query: "Use the google-analytics mcp server to give me a full breakdown of my traffic metrics for the last 90 days".
Just … Amazing !!!
Incredible. No questions !!!
Real-World Use Cases and Business Applications
Marketing analytics automation transforms how teams monitor and optimize campaigns.
AI systems and agents can now track campaign performance, identify trending content, and suggest budget reallocations automatically. This automation level reduces manual reporting overhead while improving decision-making speed.
E-commerce optimization benefits significantly from AI-powered analytics integration. Product page performance, conversion funnel analysis, and customer segmentation become automated insights. AI systems can identify drop-off points, recommend product placement changes, and predict seasonal trends.
Content strategy development leverages page performance and user engagement data for informed decision-making. AI analysis of top-performing content, audience demographics, and traffic sources guides content calendar planning. This data-driven approach replaces intuition-based content decisions with measurable optimization strategies.
Customer support teams can use real-time analytics to understand user behavior patterns during support interactions. Peak usage identification, geographic distribution analysis, and device-specific issues become immediately actionable insights. This contextual information improves support quality and reduces resolution times.
Conclusion
Building a Google Analytics MCP server in Python represents a fundamental shift toward AI-powered business intelligence.
This integration eliminates manual data access barriers while enabling sophisticated automated analysis capabilities.
The combination of Python's analytical ecosystem with MCP's AI integration creates unprecedented automation potential.
Your MCP server transforms static analytics dashboards into dynamic, AI-accessible intelligence systems. Natural language queries replace complex interface navigation, while automated insights replace manual report generation.
As AI systems and agents become more sophisticated, your analytics infrastructure becomes increasingly valuable as a competitive advantage. Organizations that integrate analytics data with AI workflows will outpace those relying on traditional manual processes. Your Google Analytics MCP server positions you at the forefront of this analytics automation revolution.
Start building your analytics automation infrastructure today and unlock the full potential of AI-powered business intelligence.
Github Repository: https://github.com/juancolamendy/mcp-tutorials/tree/main/ga_mcp_py
PS: If you like this article, share it with others ♻️
Would help a lot ❤️
And feel free to follow me for more content like this.
Subscribe to my newsletter
Read articles from Juan Carlos Olamendy directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Juan Carlos Olamendy
Juan Carlos Olamendy
🤖 Talk about AI/ML · AI-preneur 🛠️ Build AI tools 🚀 Share my journey 𓀙 🔗 http://pixela.io