Google Analytics MCP Server
Provides tools for querying Google Analytics 4 data, including real-time data, custom reports, quick insights, and metadata discovery.
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Google Analytics MCP ServerShow me real-time active users"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Google Analytics MCP Server
A Model Context Protocol (MCP) server that provides seamless access to Google Analytics 4 data through standard MCP interfaces. This tool allows LLM applications to easily query and analyze Google Analytics data without directly dealing with the complexities of the Google Analytics Data API.
✨ Features
🔐 Dual Authentication: Support both Service Account and OAuth2 User Authorization
Real-time Data Access: Get real-time analytics data for current active users and activity
Custom Reports: Create comprehensive reports with custom dimensions and metrics
Quick Insights: Predefined analytics insights for common use cases
Metadata Discovery: Get available dimensions and metrics for your Google Analytics property
🔄 Auto Token Refresh: Automatically refreshes expired OAuth2 access tokens
Smart Error Handling: Detailed error messages with actionable solutions for permission issues
Standard MCP Interface: Works with any MCP-compatible client
Related MCP server: Google Analytics MCP Server
Installation
npm install @toolsdk.ai/google-analytics-mcpPrerequisites
Node.js >= 18.0.0
Google Analytics 4 property
Either:
Service Account credentials (default), OR
OAuth2 tokens from a user authorization flow
🔐 Authentication Modes
This MCP server supports two authentication modes, controlled by the GOOGLE_AUTH_MODE environment variable:
Mode | Value | Description |
Service Account |
| Use a GCP service account JSON key |
OAuth2 |
| Use user-authorized OAuth2 tokens |
Mode 1: Service Account (Default)
Use this mode for server-to-server authentication without user interaction.
Setup Steps
Create a Service Account in Google Cloud Console
Download the JSON key file
Grant access to your GA4 property:
Go to Google Analytics → Admin → Property Access Management
Add the service account email (e.g.,
xxx@project.iam.gserviceaccount.com) with Viewer access
Environment Variables
# Optional: defaults to 'service_account'
GOOGLE_AUTH_MODE=service_account
# Option 1: Direct JSON string
GOOGLE_CREDENTIALS='{"type":"service_account","project_id":"...","private_key":"...","client_email":"..."}'
# Option 2: Path to JSON file
GOOGLE_CREDENTIALS_PATH=/path/to/service-account.jsonClaude Desktop Configuration
{
"mcpServers": {
"google-analytics-mcp": {
"command": "npx",
"args": ["-y", "@toolsdk.ai/google-analytics-mcp"],
"env": {
"GOOGLE_AUTH_MODE": "service_account",
"GOOGLE_CREDENTIALS_PATH": "/path/to/service-account.json"
}
}
}
}Mode 2: OAuth2 User Authorization
Use this mode to access GA data on behalf of a user with their own permissions.
Advantages
✅ Access the user's own GA properties without service account setup
✅ No need to add service accounts to GA property permissions
✅ Works with the user's existing Google account permissions
⚠️ Important: This MCP server does NOT include the OAuth2 authorization flow itself. You need to implement the OAuth2 consent flow separately to obtain the tokens.
1. Implement OAuth2 Authorization Flow (Your Responsibility)
You need to implement the OAuth2 authorization flow using libraries like:
googleapis(Node.js)google-auth-library(Node.js)
Required OAuth2 scopes:
https://www.googleapis.com/auth/analytics.readonlyExample OAuth2 flow (simplified):
import { google } from 'googleapis';
const oauth2Client = new google.auth.OAuth2(
CLIENT_ID,
CLIENT_SECRET,
REDIRECT_URI
);
// Generate auth URL and redirect user
const authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline', // Important: to get refresh_token
scope: ['https://www.googleapis.com/auth/analytics.readonly']
});
// After user consent, exchange code for tokens
const { tokens } = await oauth2Client.getToken(code);
// Save tokens to tokens.json
fs.writeFileSync('tokens.json', JSON.stringify(tokens, null, 2));2. tokens.json Format
After completing the OAuth2 flow, save the tokens in a tokens.json file:
{
"access_token": "ya29.a0AWY7CknXXX...",
"refresh_token": "1//0eXXX...",
"scope": "https://www.googleapis.com/auth/analytics.readonly",
"token_type": "Bearer",
"expiry_date": 1234567890000
}Field | Description | Required |
| The OAuth2 access token | ✅ Yes |
| The refresh token (for auto-renewal) | ⚠️ Recommended |
| Authorized scopes | Optional |
| Token type (usually "Bearer") | Optional |
| Token expiration timestamp (ms) | ⚠️ Recommended |
3. Token Loading Priority
The MCP server loads OAuth2 tokens in the following order:
Direct JSON string via
GOOGLE_OAUTH2_TOKENSenvironment variablePath specified by
GOOGLE_OAUTH2_TOKEN_PATHenvironment variable{current working directory}/tokens.json{current working directory}/../tokens.json{src directory}/../../tokens.json
4. Environment Variables (OAuth2 Mode)
GOOGLE_AUTH_MODE=oauth2
# Option 1: Direct JSON string
GOOGLE_OAUTH2_TOKENS='{"access_token":"ya29...","refresh_token":"1//0e...","expiry_date":1234567890000}'
# Option 2: Path to tokens.json
GOOGLE_OAUTH2_TOKEN_PATH=/path/to/your/tokens.json
# Optional: For automatic token refresh
GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=your-client-secretClaude Desktop Configuration (OAuth2)
{
"mcpServers": {
"google-analytics-mcp": {
"command": "npx",
"args": ["-y", "@toolsdk.ai/google-analytics-mcp"],
"env": {
"GOOGLE_AUTH_MODE": "oauth2",
"GOOGLE_OAUTH2_TOKEN_PATH": "/path/to/your/tokens.json",
"GOOGLE_CLIENT_ID": "your-client-id (optional)",
"GOOGLE_CLIENT_SECRET": "your-client-secret (optional)"
}
}
}
}⚠️ Token Lifecycle Management (OAuth2 Mode)
Access Token Expiration
Google OAuth2 access tokens typically expire after 1 hour
The MCP server will automatically attempt to refresh tokens if
refresh_tokenis provided
Automatic Token Refresh
When configured with GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET, the server will:
Detect when the access token is expired
Use the
refresh_tokento obtain a newaccess_tokenAutomatically save the new tokens to
tokens.json
Refresh Token Considerations
⚠️ Important Notes about Refresh Tokens:
Refresh tokens can expire or be revoked:
If the user revokes access in their Google Account settings
If the refresh token is unused for 6 months (for non-verified apps)
If you've exceeded the limit of 100 refresh tokens per user per client
Getting a refresh token:
You only get a
refresh_tokenon the first authorizationUse
access_type: 'offline'in your auth URLUse
prompt: 'consent'to force re-consent and get a new refresh token
Recommended practices:
Always request
access_type: 'offline'during OAuth2 flowStore and protect the
refresh_tokensecurelyImplement re-authorization flow for when refresh tokens become invalid
Monitor for
invalid_granterrors which indicate the refresh token is no longer valid
Available Tools
analytics_report
Get comprehensive Google Analytics data with custom dimensions and metrics. Can create any type of report.
Parameters:
propertyId(string, required): Google Analytics property IDstartDate(string, required): Start date (YYYY-MM-DD)endDate(string, required): End date (YYYY-MM-DD)dimensions(array, optional): Dimensions to querymetrics(array, required): Metrics to querydimensionFilter(object, optional): Filter by dimension valuesmetricFilter(object, optional): Filter by metric valuesorderBy(object, optional): Sort results by dimension or metriclimit(number, optional): Limit number of results (default: 100)
realtime_data
Get real-time analytics data for current active users and activity.
Parameters:
propertyId(string, required): Google Analytics property IDdimensions(array, optional): Dimensions for real-time datametrics(array, optional): Real-time metrics (default: ['activeUsers'])limit(number, optional): Limit number of results (default: 50)
quick_insights
Get predefined analytics insights for common use cases.
Parameters:
propertyId(string, required): Google Analytics property IDstartDate(string, required): Start date (YYYY-MM-DD)endDate(string, required): End date (YYYY-MM-DD)reportType(string, required): Type of quick insight report (overview, top_pages, traffic_sources, etc.)limit(number, optional): Limit number of results (default: 20)
get_metadata
Get available dimensions and metrics for Google Analytics property.
Parameters:
propertyId(string, required): Google Analytics property IDtype(string, optional): Type of metadata to retrieve (dimensions, metrics, both)
search_metadata
Search for specific dimensions or metrics by name or category.
Parameters:
propertyId(string, required): Google Analytics property IDquery(string, required): Search term to find dimensions/metricstype(string, optional): Type of metadata to search (dimensions, metrics, both)category(string, optional): Filter by category
Error Handling
The server provides detailed error messages with actionable solutions based on the authentication mode:
Service Account Mode:
Permission errors will prompt you to add the service account email to GA property access
OAuth2 Mode:
Permission errors will suggest re-authorization
Token errors will indicate refresh or re-authorization needs
Environment Variables Summary
Variable | Mode | Description |
| Both |
|
| Service Account | JSON string of service account key |
| Service Account | Path to service account JSON file |
| OAuth2 | JSON string of OAuth2 tokens |
| OAuth2 | Path to tokens.json |
| OAuth2 | Client ID for token refresh |
| OAuth2 | Client secret for token refresh |
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
MIT
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Servers
- Alicense-qualityFmaintenanceEnables LLMs to interact with Google Analytics 4 data through the Google Analytics Data API, supporting standard reports, real-time data, and metadata retrieval.Last updated19MIT
- AlicenseBqualityDmaintenanceEnables LLM applications to query Google Analytics 4 data through standard MCP interfaces, supporting real-time data, custom reports, and metadata discovery.Last updated51521MIT
- Alicense-qualityBmaintenanceConnects MCP clients like Claude Desktop to Google Analytics 4 Data API, enabling natural language queries for reports, top pages, traffic sources, conversions, realtime users, and period comparisons.Last updatedMIT
- Alicense-qualityDmaintenanceEnables querying Google Analytics 4 data using natural language through MCP clients like Claude and Cursor, supporting 200+ dimensions and metrics for traffic, user behavior, and e-commerce analysis.Last updatedMIT
Related MCP Connectors
Analytical memory for AI agents: a real Postgres queried in plain English over MCP. One command.
Hosted Google Calendar MCP server for AI agents. No self-hosting or Google Cloud setup.
Read-only Yandex Metrika MCP. Query visits, sources, geo, devices and more in plain language.
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/kwp-lab/mcp-google-analytics-oauth2'
If you have feedback or need assistance with the MCP directory API, please join our Discord server