{
  "source_file": "0930",
  "source_platform": "Hashnode",
  "author": "Juan Carlos Olamendy",
  "title_listed": "Building a Google Analytics MCP Server in Python: Unlock AI-Powered Analytics Automation",
  "keywords": "",
  "domain": "大模型算法",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://juancolamendy.hashnode.dev/building-a-google-analytics-mcp-server-in-python-unlock-ai-powered-analytics-automation",
  "publish_date": "2025-06-23",
  "corpus_stage": "",
  "notes": "",
  "id": "4503191561db",
  "collected_at": "2026-10-02T14:10:50",
  "title": "Building a Google Analytics MCP Server in Python: Unlock AI-Powered Analytics Automation",
  "body_markdown": "Building a Google Analytics MCP Server in Python: Unlock AI-Powered Analytics Automation\nPublished\nJune 23, 2025\n•\n7\nmin read\n•\nView as Markdown\nJ\nJuan Carlos Olamendy\nSenior AI Engineer | Building & Telling Stories about AI/ML Systems | Software Engineer\nImagine having an AI agent that can instantly pull your website's traffic data, analyze user behavior patterns, and generate insights on command.\nNo more switching between dashboards, no more manual data exports, and no more waiting for reports.\nThis isn't science fiction—it's what happens when you combine Google Analytics with the Model Context Protocol (MCP) using Python.\nToday, we'll build a powerful MCP server that transforms your analytics data into an AI-accessible resource.\nAnd I swear … I will never use Google Analytics dashboard again.\nWhat is Model Context Protocol and Why Should You Care?\nThe Model Context Protocol represents a paradigm shift in how AI systems access and interact with external data sources.\nThink of MCP as a universal connector that allows AI models to extend its context using your business systems, databases, and APIs.\nInstead of manually copying and pasting data between applications, MCP creates a direct bridge between your AI agents such as Claude Desktop and your data.\nFor analytics professionals and developers, this means unprecedented automation capabilities.\nYour 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.\nArchitecture Overview: How the Components Work Together\nOur Google Analytics MCP server follows a clean, modular architecture that separates concerns and maximizes maintainability.\nInfrastructure setup\nThe authentication flow to access Google Analytics API uses Google Cloud service accounts.\nService 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.\nGoogle Cloud setup involves several critical steps that determine your server's success.\nSo, 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.\nProject Dependencies\nFor dependencies manage, we use\nuv\n.\nThe\nuv\npackage manager provides fast dependency resolution and virtual environment management.\n[project]\nname\n=\n\"ga-mcp-py\"\nversion\n=\n\"0.1.0\"\ndescription\n=\n\"Google Analytics MCP (Model Context Protocol) Python implementation\"\nreadme\n=\n\"README.md\"\nrequires-python\n=\n\">=3.12\"\ndependencies\n= [\n\"google-api-python-client\"\n,\n\"oauth2client\"\n,\n\"mcp[cli]\"\n,\n\"python-dotenv\"\n]\n[build-system]\nrequires\n= [\n\"hatchling\"\n]\nbuild-backend\n=\n\"hatchling.build\"\n[tool.hatch.build.targets.wheel]\npackages\n= [\n\".\"\n]\ninclude\n= [\n\"main.py\"\n,\n\"README.md\"\n,\n\"pyproject.toml\"\n]\nNext step is to install the dependencies.\nuv sync\nEnvironment variables\nCreate a\n.env\nfile in your project root containing your service account file path and GA4 property ID.\nRemember to never commit sensitive credentials to version control—use environment variables and secure key management practices.\nGOOGLE_APPLICATION_CREDENTIALS=google_analytics_api_svc_acct.json\nGA4_PROPERTY_ID=your-ga4-property-id\nApplication Implementation - Google Analytics client\nFirst step is to initialize a Google Analytics client using service account authentication (file generated and downloaded before), ensuring secure and reliable API access.\nThe Google Analytics client initialization handles authentication complexity transparently.\n# Constants\nSCOPES = [\n'https://www.googleapis.com/auth/analytics.readonly'\n]\n# Global analytics service\nanalytics_service =\nNone\n# Load environment variables from .env file\nload_dotenv()\ndef\ninit_ga4_client\n():\n\"\"\"Initialize Google Analytics 4 client using service account.\"\"\"\nglobal\nanalytics_service\n# Get service account file path from environment variable\nservice_account_file = os.getenv(\n'GOOGLE_APPLICATION_CREDENTIALS'\n)\nif\nnot\nservice_account_file:\nraise\nValueError(\n\"GOOGLE_APPLICATION_CREDENTIALS environment variable is required\"\n)\nif\nnot\nos.path.exists(service_account_file):\nraise\nFileNotFoundError(\nf\"Service account file not found:\n{service_account_file}\n\"\n)\n# Get property ID from environment variable\nproperty_id = os.getenv(\n'GA4_PROPERTY_ID'\n)\nif\nnot\nproperty_id:\nraise\nValueError(\n\"GA4_PROPERTY_ID environment variable is required\"\n)\n# Authenticate using service account credentials\ncredentials = service_account.Credentials.from_service_account_file(\n        service_account_file, scopes=SCOPES)\n# Build the Google Analytics Data API client (for GA4)\nanalytics_service = build(\n'analyticsdata'\n,\n'v1beta'\n, credentials=credentials)\nApplication Implementation - FastMCP server\nNext step is initialize the FastMCP. It handles the MCP protocol implementation, tool registration, and communication with AI systems.\n# imports\nfrom\nmcp.server.fastmcp\nimport\nFastMCP\n# Initialize FastMCP server\nmcp = FastMCP(\n\"google-analytics-mcp\"\n)\nNext step is to register the tools. Each tool function corresponds to a specific analytics capability, from basic reporting to advanced real-time data access.\n@mcp.tool()\nasync\ndef\nquery_analytics\n(\nstart_date: str, end_date: str, metrics: List[str], \n                         dimensions: List[str], filters: Optional[Dict] = None\n) -> str:\n\"\"\"Query Google Analytics data with custom metrics, dimensions, and filters.\"\"\"\ntry\n:\n        property_id = os.getenv(\n'GA4_PROPERTY_ID'\n)\n\n        request_body = {\n'dateRanges'\n: [{\n'startDate'\n: start_date,\n'endDate'\n: end_date}],\n'metrics'\n: [{\n'name'\n: metric}\nfor\nmetric\nin\nmetrics],\n'dimensions'\n: [{\n'name'\n: dimension}\nfor\ndimension\nin\ndimensions]\n        }\nif\nfilters:\n            request_body[\n'dimensionFilter'\n] = filters\n\n        response = analytics_service.properties().runReport(\n            property=\nf'properties/\n{property_id}\n'\n,\n            body=request_body\n        ).execute()\n\n        result = format_analytics_response(response)\nreturn\njson.dumps(result, indent=\n2\n)\nexcept\nException\nas\ne:\nreturn\njson.dumps({\n\"error\"\n: str(e)}, indent=\n2\n)\nIn practice, I’ve registered a couple of tools for this MCP Server.\nThis MCP server provides the following tools:\nquery_analytics\n: Query Google Analytics data with custom metrics, dimensions, and filters\nget_realtime_data\n: Get real-time Google Analytics data\nget_traffic_sources\n: Get traffic source analysis data\nget_user_demographics\n: Get user demographics data\nget_page_performance\n: Get page performance metrics\nget_conversion_data\n: Get conversion and event data\nget_custom_report\n: Get custom analytics report with flexible parameters\nYou can check the codebase here:\nhttps://github.com/juancolamendy/mcp-tutorials/tree/main/ga_mcp_py\nIntegrate with Claude Desktop\nClaude Desktop integration requires specific configuration syntax and path management.\nThe configuration file must specify the correct Python environment and project paths.\nEnvironment variable inheritance ensures your MCP server accesses the correct credentials and property settings.\nOpen the file\n~/Library/Application\\ Support/Claude/claude_desktop_config.json\nand edit it with the following settings. Change the\npath\n,\nGOOGLE_APPLICATION_CREDENTIALS\nand\nGA4_PROPERTY_ID\naccording to your own scenario.\n{\n\"mcpServers\"\n: {\n\"google-analytics\"\n: {\n\"command\"\n:\n\"uv\"\n,\n\"args\"\n: [\n\"--directory\"\n,\n\"<path>/ga_mcp_py\"\n,\n\"run\"\n,\n\"main.py\"\n],\n\"env\"\n: {\n\"GOOGLE_APPLICATION_CREDENTIALS\"\n:\n\"<path>/svc_acct.json\"\n,\n\"GA4_PROPERTY_ID\"\n:\n\"12346789\"\n}\n        }\n    }\n}\nLet’s see my own integration.\nI have a website under the domain\nscribamax.com\n. 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.\nSo, let's analyze the traffic metrics on the last 90 days.\nSo, let’s send a request to Claude (my agent) that will use the Google Analytics tools to get real-time data to analyze.\nThe output is so good, that I swear I will never use Google Analytics dashboard again, that I found kind of confusing to me sometimes.\nQuery: \"Use the google-analytics mcp server to give me a full breakdown of my traffic metrics for the last 90 days\".\nJust … Amazing !!!\nIncredible. No questions !!!\nReal-World Use Cases and Business Applications\nMarketing analytics automation transforms how teams monitor and optimize campaigns.\nAI 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.\nE-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.\nContent 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.\nCustomer 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.\nConclusion\nBuilding a Google Analytics MCP server in Python represents a fundamental shift toward AI-powered business intelligence.\nThis integration eliminates manual data access barriers while enabling sophisticated automated analysis capabilities.\nThe combination of Python's analytical ecosystem with MCP's AI integration creates unprecedented automation potential.\nYour 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.\nAs 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.\nStart building your analytics automation infrastructure today and unlock the full potential of AI-powered business intelligence.\nGithub Repository:\nhttps://github.com/juancolamendy/mcp-tutorials/tree/main/ga_mcp_py\nPS:\nIf you like this article, share it with others ♻️\nWould help a lot ❤️\nAnd feel free to follow me for more content like this.\n#\nmcp\n#\nmcp-server\n#\nmcp-client\n#\nagentic-ai\n#\nagents",
  "metadata": {
    "title": "Building a Google Analytics MCP Server in Python: Unlock AI-Powered Analytics Automation",
    "description": "Imagine having an AI agent that can instantly pull your website's traffic data, analyze user behavior patterns, and generate insights on command.\nNo more switching between dashboards, no more manual data exports, and no more waiting for reports.\nThis...",
    "keywords": null,
    "author": null,
    "og:title": "Building a Google Analytics MCP Server in Python: Unlock AI-Powered Analytics Automation",
    "og:description": "Imagine having an AI agent that can instantly pull your website's traffic data, analyze user behavior patterns, and generate insights on command.\nNo more switching between dashboards, no more manual data exports, and no more waiting for reports.\nThis...",
    "og:url": "https://juancolamendy.hashnode.dev/building-a-google-analytics-mcp-server-in-python-unlock-ai-powered-analytics-automation",
    "og:site_name": "Juan C Olamendy",
    "og:image": "https://cdn.hashnode.com/res/hashnode/image/upload/v1750693375498/fd7b3134-df35-4754-8226-faf65cc66336.png",
    "og:image:width": "1200",
    "og:image:height": "630",
    "og:type": "article",
    "twitter:card": "summary_large_image",
    "twitter:creator": "https://twitter.com/juancolamendy",
    "twitter:title": "Building a Google Analytics MCP Server in Python: Unlock AI-Powered Analytics Automation",
    "twitter:description": "Imagine having an AI agent that can instantly pull your website's traffic data, analyze user behavior patterns, and generate insights on command.\nNo more switching between dashboards, no more manual data exports, and no more waiting for reports.\nThis...",
    "twitter:image": "https://cdn.hashnode.com/res/hashnode/image/upload/v1750693375498/fd7b3134-df35-4754-8226-faf65cc66336.png",
    "article:published_time": "2025-06-23T15:53:06.884Z",
    "article:author": "https://juancolamendy.hashnode.dev/@juancolamendy"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": ""
  },
  "code_blocks": [
    {
      "file": "attachments/4503191561db/code/body-000.txt",
      "chars": 479,
      "language": "text"
    },
    {
      "file": "attachments/4503191561db/code/body-001.txt",
      "chars": 8,
      "language": "text"
    },
    {
      "file": "attachments/4503191561db/code/body-002.txt",
      "chars": 103,
      "language": "text"
    },
    {
      "file": "attachments/4503191561db/code/body-003.txt",
      "chars": 1222,
      "language": "text"
    },
    {
      "file": "attachments/4503191561db/code/body-004.txt",
      "chars": 116,
      "language": "text"
    },
    {
      "file": "attachments/4503191561db/code/body-005.txt",
      "chars": 994,
      "language": "text"
    },
    {
      "file": "attachments/4503191561db/code/body-006.txt",
      "chars": 407,
      "language": "text"
    }
  ],
  "images": [
    {
      "status": "ok",
      "url": "https://cdn.hashnode.com/res/hashnode/image/upload/v1750693375498/fd7b3134-df35-4754-8226-faf65cc66336.png",
      "bytes": 2019294,
      "reused": true,
      "local_path": "attachments/4503191561db/images/000.png",
      "src": "https://cdn.hashnode.com/res/hashnode/image/upload/v1750693375498/fd7b3134-df35-4754-8226-faf65cc66336.png",
      "alt": "Building a Google Analytics MCP Server in Python: Unlock AI-Powered Analytics Automation",
      "downloaded": true
    },
    {
      "status": "ok",
      "url": "https://cdn.hashnode.com/res/hashnode/image/upload/v1750692858995/6e1f8915-e4cc-4a1d-9725-29cde96f2ac0.png",
      "bytes": 140208,
      "reused": true,
      "local_path": "attachments/4503191561db/images/002.png",
      "src": "https://cdn.hashnode.com/res/hashnode/image/upload/v1750692858995/6e1f8915-e4cc-4a1d-9725-29cde96f2ac0.png",
      "alt": "",
      "downloaded": true
    },
    {
      "status": "ok",
      "url": "https://cdn.hashnode.com/res/hashnode/image/upload/v1750693732370/119d62c0-9c1d-451c-aba5-e87b6a8a97cb.png",
      "bytes": 154783,
      "reused": true,
      "local_path": "attachments/4503191561db/images/003.png",
      "src": "https://cdn.hashnode.com/res/hashnode/image/upload/v1750693732370/119d62c0-9c1d-451c-aba5-e87b6a8a97cb.png",
      "alt": "",
      "downloaded": true
    },
    {
      "status": "ok",
      "url": "https://cdn.hashnode.com/res/hashnode/image/upload/v1750693821444/b1d8611c-06d2-488e-896a-cca7e569b9c8.png",
      "bytes": 193590,
      "reused": true,
      "local_path": "attachments/4503191561db/images/004.png",
      "src": "https://cdn.hashnode.com/res/hashnode/image/upload/v1750693821444/b1d8611c-06d2-488e-896a-cca7e569b9c8.png",
      "alt": "",
      "downloaded": true
    }
  ],
  "audio": [],
  "videos": [],
  "links": [
    {
      "href": "https://juancolamendy.hashnode.dev/building-a-google-analytics-mcp-server-in-python-unlock-ai-powered-analytics-automation.md",
      "label": "View as Markdown",
      "type": "a"
    },
    {
      "href": "https://hashnode.com/@juancolamendy",
      "label": "J",
      "type": "a"
    },
    {
      "href": "https://twitter.com/juancolamendy",
      "label": "",
      "type": "a"
    },
    {
      "href": "https://www.linkedin.com/in/juancolamendy/",
      "label": "",
      "type": "a"
    },
    {
      "href": "https://github.com/juancolamendy/mcp-tutorials/tree/main/ga_mcp_py",
      "label": "https://github.com/juancolamendy/mcp-tutorials/tree/main/ga_mcp_py",
      "type": "a"
    },
    {
      "href": "https://www.scribamax.com/",
      "label": "scribamax.com",
      "type": "a"
    },
    {
      "href": "https://juancolamendy.hashnode.dev/tag/mcp",
      "label": "# mcp",
      "type": "a"
    },
    {
      "href": "https://juancolamendy.hashnode.dev/tag/mcp-server",
      "label": "# mcp-server",
      "type": "a"
    },
    {
      "href": "https://juancolamendy.hashnode.dev/tag/mcp-client",
      "label": "# mcp-client",
      "type": "a"
    },
    {
      "href": "https://juancolamendy.hashnode.dev/tag/agentic-ai",
      "label": "# agentic-ai",
      "type": "a"
    },
    {
      "href": "https://juancolamendy.hashnode.dev/tag/agents",
      "label": "# agents",
      "type": "a"
    }
  ],
  "retry_at": "2026-10-03T08:06:17",
  "repair_version": 2,
  "repaired_at": "2026-10-14T10:50:37Z",
  "source_url": "https://juancolamendy.hashnode.dev/building-a-google-analytics-mcp-server-in-python-unlock-ai-powered-analytics-automation",
  "papers": [],
  "actual_video_files": [],
  "body_chars": 11148,
  "expected_body_images": 4,
  "discovery_status": "ok",
  "delivery_status": "ok",
  "missing_reason": "",
  "raw_html": "attachments/4503191561db/pages/source.html",
  "local_html": "attachments/4503191561db/pages/article.html",
  "body_base_path": "attachments/4503191561db/pages/",
  "body_markdown_path": "attachments/4503191561db/pages/article.md"
}