How to Connect Google Analytics MCP to Claude Code (2026 Setup Guide)
The Google Analytics MCP server lets you query your GA4 data in plain English directly inside Claude Code. Ask Claude "What were my top traffic sources last week?" or "Show me AI-referred sessions by landing page" — and get real answers from your live analytics data, no dashboard required.
This guide covers every step of the setup: installing the MCP, creating your own OAuth client to avoid the "This app is blocked" error, configuring authentication, editing the correct config file, and restarting Claude Code. It also covers re-authentication, common errors, and example queries you can run once everything is connected.
https://cdn.sanity.io/images/en9d2pb2/production/de333cabeb9c6e85dc37a7eb7723849d4b5c7748-1200x630.png
If you want automated AI traffic attribution without the manual setup, the AI traffic decoder does this out of the box. But if you want full control over your GA4 data via Claude Code, read on.
What Is the Google Analytics MCP?
MCP stands for Model Context Protocol — an open standard that lets AI assistants connect to external tools and data sources. The Google Analytics MCP server is an open-source package (published atanalytics-mcp on PyPI) that implements the MCP protocol for the GA4 Data API.
Once connected, Claude Code gains access to a set of GA4 tools it can call on your behalf:
| Tool | What It Does |
|---|---|
run_report | Runs a custom GA4 report with any dimensions, metrics, and date ranges |
run_realtime_report | Returns live active-user data from the GA4 Realtime API |
get_account_summaries | Lists all GA4 accounts and properties your credentials have access to |
get_property_details | Returns metadata about a specific GA4 property (timezone, currency, etc.) |
list_google_ads_links | Lists Google Ads accounts linked to a GA4 property |
You interact with these tools by talking to Claude in natural language. Claude decides which tool to call, constructs the API parameters, executes the query, and returns a formatted answer. You never write a line of API code.
Why This Is Worth Setting Up
GA4's UI is powerful but slow. Pulling a custom report — cross-referencing AI-referred traffic by landing page, device, and conversion event — takes 10–15 minutes of clicking through Explore. With the MCP connected, that same analysis takes 30 seconds. You type the question; Claude runs the query and interprets the result.
For teams already analyzing how to track AI referral traffic in GA4, the MCP removes the manual querying step entirely. Claude can segment chatgpt.com and perplexity.ai traffic, calculate conversion rates, pull revenue attribution, and diagnose funnel drop-offs — all in a single conversation.
You can also use it alongside the brand visibility tracker to correlate AI mention data with actual GA4 traffic movements in real time.
Prerequisites
Before starting, confirm you have the following:
| Requirement | How to Check | Install Link |
|---|---|---|
| Python 3.9+ | python3 --version | python.org |
| pipx | pipx --version | brew install pipx |
| Google Cloud CLI (gcloud) | gcloud --version | cloud.google.com/sdk |
| A Google Cloud project | gcloud config list project | console.cloud.google.com |
| Google Analytics Data API enabled | Cloud Console > APIs & Services > Enabled APIs | Enable via console |
| A GA4 property with data | GA4 Admin > Property Settings | — |
pip install — the package needs to be globally accessible. And do not rely on pipx run analytics-mcp in your Claude config. Claude Code's shell does not include Homebrew's bin directory in its PATH, so pipx run will fail with "command not found." Use pipx install instead, which creates a permanent binary at ~/.local/bin/analytics-mcp.
Step 1: Install analytics-mcp via pipx
Open your terminal and run:
pipx install analytics-mcp
After installation, confirm the binary exists:
which analytics-mcp
# Expected output: /Users/yourname/.local/bin/analytics-mcp
If which analytics-mcp returns nothing, run pipx ensurepath and restart your terminal. This adds ~/.local/bin to your PATH.
Note the full path to the binary — you will need it in Step 4 when editing the Claude config file. The path will be /Users/yourname/.local/bin/analytics-mcp where yourname is your macOS username.
Why not pipx run? When Claude Code launches the MCP process, it uses a restricted shell environment that does not include Homebrew's PATH. pipx run is a Homebrew-installed binary. Claude Code cannot find it. pipx install writes the binary to ~/.local/bin, which is accessible regardless of shell PATH configuration.
Step 2: Fix the "This App Is Blocked" OAuth Error
This is the most common failure point. When you rungcloud auth application-default login with the default gcloud OAuth client and request the analytics.readonly scope, Google blocks it with:
"This app is blocked. This app tried to access sensitive info in your Google Account."This happens because Google restricts the
analytics.readonly scope to OAuth clients that have been verified or are owned by the requesting developer. The default gcloud OAuth client has not been approved for this scope.
The fix: Create your own OAuth 2.0 Desktop App client ID in your Google Cloud project. Google trusts it because it is in your own project.
How to Create Your OAuth 2.0 Desktop Client
- User Type: External (even for personal use)
- App name: anything (e.g., "GA MCP Local")
- Add your own email as a test user
- Scopes: add
https://www.googleapis.com/auth/analytics.readonly - Back in Credentials, select Application type: Desktop app
- Name it (e.g., "Claude Code GA MCP")
- Click Create
- Click Download JSON — save the file somewhere accessible, e.g.,
~/Downloads/client_secret_*.json
You now have an OAuth client that is approved to request the
analytics.readonly scope for your account.
Step 3: Authenticate with Your OAuth Client
Run the following in your terminal, replacing the path with the actual location of your downloaded JSON file:
export CLOUDSDK_PYTHON=/opt/homebrew/bin/python3
gcloud auth application-default login \
--client-id-file="/Users/yourname/Downloads/client_secret_123456-abc.json" \
--scopes=https://www.googleapis.com/auth/analytics.readonly,https://www.googleapis.com/auth/cloud-platform
What each part does:
export CLOUDSDK_PYTHON=/opt/homebrew/bin/python3 — Ensures gcloud uses Homebrew's Python 3, not macOS's system Python (which can cause auth failures on macOS Sonoma and later)--client-id-file — Points gcloud to your own OAuth client instead of the default blocked client--scopes — Requests both the Analytics readonly scope and the cloud-platform scope (required for gcloud to function properly)After running this command, a browser window will open. Sign in with the Google account that has access to your GA4 property. Grant the requested permissions. The browser will show "You are now authenticated with the gcloud CLI."
Your credentials will be saved to:
/Users/yourname/.config/gcloud/application_default_credentials.json
Note this path — you will reference it in Step 4.
Step 4: Configure ~/.claude.json
This is the most important configuration detail that catches most users: the MCP server configuration goes in~/.claude.json, not in ~/.claude/settings.json.
The file ~/.claude/settings.json is Claude Code's UI settings file. It does not support the mcpServers key. If you put MCP config there, Claude Code will silently ignore it or log a "mcpServers not valid field" warning. The correct file is ~/.claude.json in your home directory.
Open ~/.claude.json in any editor. If the file does not exist, create it. Add or merge the following:
{
"mcpServers": {
"analytics-mcp": {
"type": "stdio",
"command": "/Users/yourname/.local/bin/analytics-mcp",
"args": [],
"env": {
"GOOGLE_APPLICATION_CREDENTIALS": "/Users/yourname/.config/gcloud/application_default_credentials.json"
}
}
}
}
Replace yourname with your actual macOS username in both paths.
If your ~/.claude.json already has other keys (like theme or model), add the mcpServers key alongside them:
{
"theme": "dark",
"model": "claude-sonnet-4-6",
"mcpServers": {
"analytics-mcp": {
"type": "stdio",
"command": "/Users/yourname/.local/bin/analytics-mcp",
"args": [],
"env": {
"GOOGLE_APPLICATION_CREDENTIALS": "/Users/yourname/.config/gcloud/application_default_credentials.json"
}
}
}
}
Config field reference:
| Field | Value | Notes |
|---|---|---|
type | "stdio" | MCP transport — analytics-mcp uses stdio |
command | Full path to analytics-mcp binary | Must be absolute path, not analytics-mcp |
args | [] | No additional arguments needed |
env.GOOGLE_APPLICATION_CREDENTIALS | Full path to credentials JSON | Must be the ADC file from Step 3 |
Save the file.
Step 5: Restart Claude Code
Quit Claude Code completely and relaunch it. MCP servers are loaded at startup — config changes are not picked up while Claude Code is running.
After restarting, you can verify the MCP is connected by asking Claude:
"What MCP tools do you have available?"Claude should list the GA4 tools:
run_report, run_realtime_report, get_account_summaries, get_property_details, and list_google_ads_links.
Alternatively, run:
"List all my Google Analytics accounts."Claude will call
get_account_summaries and return a list of your GA4 accounts and property IDs. If you see your property names, the setup is complete.
Step 6: Example Queries You Can Run
Here are 8 natural language queries you can ask Claude Code immediately after setup:
| Query | What Claude Returns |
|---|---|
| "Show me sessions by traffic source for the last 30 days" | Table: source/medium vs. sessions, sorted descending |
| "What's my conversion rate from chatgpt.com vs. organic search?" | Comparison: sessions, conversions, CVR per source |
| "Which landing pages get the most AI-referred traffic?" | Top pages filtered to chatgpt.com + perplexity.ai sources |
| "What were my top 10 pages by revenue last month?" | Pages ranked by purchase revenue, with transactions |
| "How many real-time users are on my site right now?" | Live count from the Realtime API |
| "Break down my sessions by device type and country for Q1 2026" | Cross-tab: device x country x sessions |
| "What's my bounce rate trend over the last 90 days?" | Weekly time series of bounce/exit rate |
| "Compare conversion rates by acquisition channel" | Channels ranked by CVR with session volume context |
Claude constructs the correct GA4 API call for each query, handles pagination, formats the results as a readable table, and can follow up with "why" questions — diagnosing drop-offs, identifying anomalies, or suggesting next steps.
For AI traffic analysis specifically, Claude can pull chatgpt.com, perplexity.ai, gemini.google.com, and claude.ai traffic side by side, with conversion rates and revenue — the same analysis covered in our guide on how to track AI referral traffic in GA4. You can also run this alongside the AI visibility checker to correlate AI mention frequency with traffic trends.
Re-Authentication: When Credentials Expire
Application Default Credentials expire approximately every hour. When they expire, Claude will return one of these errors on the next GA4 tool call:
503 Reauthentication RequiredRequest had invalid authentication credentialsToken has been expired or revokedTo renew, re-run the auth command from Step 3 in your terminal:
export CLOUDSDK_PYTHON=/opt/homebrew/bin/python3
gcloud auth application-default login \
--client-id-file="/Users/yourname/Downloads/client_secret_123456-abc.json" \
--scopes=https://www.googleapis.com/auth/analytics.readonly,https://www.googleapis.com/auth/cloud-platform
Sign in again in the browser. The credentials file at ~/.config/gcloud/application_default_credentials.json will be overwritten with fresh tokens.
You do not need to restart Claude Code. The MCP server reads the credentials file on each tool call. As soon as the file is refreshed, the next query will succeed.
Pro tip: Keep a shell alias ready. Add this to your~/.zshrc:
alias ga-auth='export CLOUDSDK_PYTHON=/opt/homebrew/bin/python3 && gcloud auth application-default login --client-id-file="/Users/yourname/Downloads/client_secret_123456-abc.json" --scopes=https://www.googleapis.com/auth/analytics.readonly,https://www.googleapis.com/auth/cloud-platform'
Then re-auth with ga-auth in one command.
Common Errors and Fixes
| Error | Cause | Fix |
|---|---|---|
"This app is blocked" | Default gcloud OAuth client is not approved for Analytics scopes | Create your own OAuth 2.0 Desktop App client in Google Cloud Console and use --client-id-file |
"No matches for glob" or "command not found: analytics-mcp" | MCP config points to wrong binary path, or package was installed with pip not pipx | Run pipx install analytics-mcp, then which analytics-mcp to get correct path, update ~/.claude.json |
503 Reauthentication Required | Application Default Credentials have expired (~1 hour TTL) | Re-run the gcloud auth application-default login command; no Claude restart needed |
"mcpServers" is not a valid field | MCP config was placed in ~/.claude/settings.json instead of ~/.claude.json | Move mcpServers block to ~/.claude.json (home directory root, not .claude/ subfolder) |
pipx: command not found | pipx is not installed | Run brew install pipx && pipx ensurepath, then restart terminal |
Error: google.auth.exceptions.DefaultCredentialsError | GOOGLE_APPLICATION_CREDENTIALS env var points to wrong file path | Verify the path in ~/.claude.json matches the actual location of application_default_credentials.json |
403 User does not have any Google Analytics account | Authenticated Google account does not have access to the GA4 property | Re-authenticate with the Google account that has Viewer or higher access to the GA4 property |
| MCP tools not appearing after restart | Config JSON is malformed (missing comma, unclosed bracket) | Validate JSON at jsonlint.com and fix syntax errors before restarting |
Available GA4 Tools in the MCP
Here is a full reference for what each tool does and when to use it:
| Tool Name | API Endpoint | Primary Use Cases | Supports Date Ranges |
|---|---|---|---|
run_report | GA4 Data API v1beta runReport | Sessions, users, revenue, conversions, custom events — any historical report | Yes — any date range |
run_realtime_report | GA4 Data API v1beta runRealtimeReport | Live active users, real-time events, current page views | No — always last 30 minutes |
get_account_summaries | GA4 Admin API listAccountSummaries | Discover all GA4 accounts and property IDs your credentials can access | No |
get_property_details | GA4 Admin API getProperty | Get timezone, currency, data retention settings for a specific property | No |
list_google_ads_links | GA4 Admin API listGoogleAdsLinks | List Google Ads accounts linked to a GA4 property for cross-channel analysis | No |
run_report tool is the workhorse. It supports all GA4 dimensions (source, medium, landing page, device category, country, page path, event name, etc.) and metrics (sessions, users, conversions, revenue, bounce rate, engagement rate, etc.). Claude constructs the correct dimension/metric combination based on your natural language request.
What You Can Analyze With GA MCP + Claude Code
Once the MCP is live, here are the high-value analyses you can run conversationally:
AI Traffic Segmentation
Ask Claude to pull sessions where source contains chatgpt.com, perplexity.ai, gemini.google.com, and claude.ai — broken down by landing page, device type, and conversion status. This gives you the AI traffic picture that the GA4 UI makes tedious to build manually. Pair with the answer engine optimization strategy to close the loop between AI mentions and GA4 traffic.
Revenue Attribution
Cross-reference first-touch source with purchase revenue to understand which channels deliver the highest-value customers — not just the most sessions. Ask Claude to rank channels by revenue-per-session and flag where paid traffic underperforms AI referral.
Funnel Diagnosis
Describe your funnel steps to Claude (e.g., "landing page > product page > add to cart > checkout > purchase") and ask it to pull drop-off rates at each stage by traffic source. Claude will identify where AI-referred users fall off compared to paid or organic, and can suggest hypotheses for why.
Audience Building
Use Claude to identify the behavioral characteristics of your highest-converting segments — time on site, pages per session, device type, entry page — and translate those into GA4 audience definitions you can export to Google Ads for retargeting.
Anomaly Investigation
When you see an unexplained traffic spike or revenue drop, ask Claude to cross-reference timing with source, landing page, and device dimensions. Claude can pinpoint whether the change was driven by a single traffic source, a specific page, or a device-type shift — faster than manual GA4 exploration.
Integrating GA MCP Into Your AI Analytics Workflow
The Google Analytics MCP is a query tool. It pulls data on demand. For ongoing monitoring — daily AI traffic trends, automated alerts when AI-referred revenue spikes, cross-platform attribution — you still need a dedicated solution.
The AI traffic decoder runs continuous monitoring across ChatGPT, Perplexity, Claude, Gemini, and all emerging AI platforms, with GA4 event-level integration, dark social attribution, and automated revenue calculations. It handles the attribution layers that the raw MCP cannot — specifically, the referrer-stripped sessions that arrive as direct traffic but originated from an AI recommendation.
For brand-level AI visibility — knowing not just when AI sends traffic, but whether AI platforms are mentioning your brand, citing your content, or recommending your competitors — the brand visibility tracker and AI visibility checker complete the picture.
Book a demo to see how Asva AI combines GA4 attribution with real-time AI mention monitoring into one unified dashboard.
Quick Setup Checklist
Use this to verify each step before testing:
pipx --version returns a version)analytics-mcp installed via pipx (which analytics-mcp returns a path)gcloud config list shows your project)analytics.readonly scopegcloud auth application-default login completed with --client-id-file and --scopes~/.config/gcloud/application_default_credentials.json exists~/.claude.json contains mcpServers block with correct binary path and credentials path~/.claude.json"List my GA4 accounts")settings.json vs ~/.claude.json), and the pipx PATH issue (fix: use absolute path in config, not command name).
Summary
The Google Analytics MCP server transforms Claude Code into a natural-language GA4 query interface. The setup involves five substantive steps: installing the package permanently via pipx, creating your own OAuth client to bypass the "This app is blocked" restriction, authenticating with the correct scopes, configuring~/.claude.json with the absolute binary path and credentials path, and restarting Claude Code.
Once running, you can query sessions, conversions, revenue, landing pages, AI-referred traffic, real-time users, and any other GA4 dimension/metric combination in plain English. Credentials expire hourly and are renewed with a single command — no restart required.
For the full picture of how to measure, attribute, and optimize AI-driven traffic — including the dark social and marketplace layers that GA4 cannot capture natively — explore the AI traffic decoder or book a demo with the Asva AI team.
See How Your Brand Shows Up in AI Search
Get a free AI visibility audit — see where you rank in ChatGPT, Perplexity, Gemini, and more.
Comments (0)
Leave a Comment
No comments yet. Be the first to comment!