Connect Google Analytics to Claude: Setup Custom Data & Key Events
A complete engineering guide to connecting Google Analytics 4 to Claude using an MCP server. Learn how to execute reports, manage key events, and handle GA4 API quirks.
If you need to give your AI agents read and write access to your web analytics, connecting Google Analytics 4 (GA4) to Claude is a massive capability multiplier. By routing natural language requests through a Model Context Protocol (MCP) server, your agents can run customized traffic reports, audit custom dimensions, and programmatically provision key events. If your team uses ChatGPT, check out our guide on connecting Google Analytics to ChatGPT or explore our broader architectural overview on connecting Google Analytics to AI Agents.
Building an integration layer for Google Analytics is an extensive engineering commitment. You are forced to deal with Google's fragmented API structure, strict property-level token quotas, and complex data models. Every time you want the model to execute a new type of query, you have to hand-code new tool definitions, redeploy your infrastructure, and maintain the OAuth token lifecycle. You can either build and maintain this infrastructure yourself, or use a managed integration platform like Truto to dynamically generate a secure, authenticated MCP server URL.
This guide breaks down exactly how to use Truto to generate a managed MCP server for Google Analytics, connect it natively to Claude, and execute complex data reporting and configuration workflows using natural language.
The Engineering Reality of Google Analytics APIs
A custom MCP server is a self-hosted integration layer that translates Claude's JSON-RPC tool calls into REST API requests. While the open MCP standard dictates how the model discovers and invokes tools, it does not solve the underlying complexity of the third-party API. The reality of integrating Google Analytics 4 is exceptionally challenging.
If you decide to build a custom MCP server for Google Analytics, you own the entire API lifecycle. Here are the specific hurdles you will face:
Fragmented API Surfaces Google Analytics does not use a single unified API. Managing configuration (accounts, properties, key events, custom dimensions, data streams) is handled by the Google Analytics Admin API v1. Running reports and extracting data is handled by the Google Analytics Data API v1. These two surfaces have entirely different design patterns. Your custom MCP server has to orchestrate authentication, schema mapping, and error handling across both distinct environments.
Complex Dimension and Metric Compatibility The GA4 Data API requires exact precision. You cannot simply request any dimension with any metric. Certain combinations are fundamentally incompatible (e.g., trying to combine item-level ecommerce dimensions with session-level acquisition metrics). If an LLM hallucinates an invalid dimension/metric combination, the Data API will reject the request outright. You have to build mechanisms to expose compatibility endpoints to the LLM so it can validate its reporting schemas before it attempts to run a report.
Strict Token-Based Quotas GA4 does not use simple "requests per minute" rate limiting. It relies on a highly restrictive token bucket system per property. A single complex report query can consume a massive chunk of your hourly or daily token quota. When an LLM iterates through paginated data or attempts to run multiple concurrent queries, it is very easy to hit these limits, resulting in hard HTTP 429 errors that require careful backoff handling.
Instead of building this infrastructure from scratch, you can use Truto. Truto normalizes the underlying OAuth lifecycles, exposes both the Admin and Data APIs as a unified set of MCP tools, and standardizes pagination patterns. If Google Analytics returns a 429 error, Truto passes it through with standardized headers so your agent can implement precise retries.
How to Generate a Google Analytics MCP Server with Truto
Truto dynamically generates MCP tools based on the active resources and documentation records defined for an integration. Tools are not cached or pre-built. When Claude connects, Truto evaluates the integrated Google Analytics account, checks the applied filters, and builds the JSON Schema definitions on the fly.
You can generate an MCP server URL using either the Truto Dashboard or the API.
Method 1: Via the Truto UI
If you want to quickly generate an endpoint for local testing with Claude Desktop, the dashboard is the fastest route:
- Navigate to the Integrated Accounts section in your Truto dashboard.
- Select your connected Google Analytics account.
- Click the MCP Servers tab.
- Click Create MCP Server.
- Select your desired configuration (e.g., Name, Allowed Methods, Tags, Expiry).
- Click Generate and copy the provided MCP server URL.
Method 2: Via the Truto API
For production workflows, you can programmatically generate MCP servers. The API validates that the integration has tools available, generates a secure token, hashes it for storage, and returns a ready-to-use URL.
Make a POST request to /integrated-account/:id/mcp:
curl -X POST https://api.truto.one/integrated-account/<ACCOUNT_ID>/mcp \
-H "Authorization: Bearer <YOUR_TRUTO_API_KEY>" \
-H "Content-Type: application/json" \
-d '{
"name": "Claude GA4 Analytics Server",
"config": {
"methods": ["read", "write", "custom"]
},
"expires_at": "2025-12-31T23:59:59Z"
}'The response returns the URL needed to connect Claude:
{
"id": "mcp_8a7b6c5d",
"name": "Claude GA4 Analytics Server",
"config": {
"methods": ["read", "write", "custom"]
},
"expires_at": "2025-12-31T23:59:59.000Z",
"url": "https://api.truto.one/mcp/t_1234567890abcdef"
}This URL is fully self-contained. It encodes the tenant routing, the target Google Analytics account, and the specific tool filters you applied.
Connecting the MCP Server to Claude
Once you have the Truto MCP URL, connecting it to Claude requires zero additional coding. The client connects to the endpoint and initiates a JSON-RPC 2.0 handshake, retrieving all available Google Analytics tools.
Method 1: Via the Claude UI
If you are using Claude Desktop or an enterprise workspace that supports custom connectors via the UI:
- Open Claude and navigate to Settings -> Integrations.
- Click Add MCP Server or Add custom connector.
- Name the connector (e.g., "Google Analytics").
- Paste the Truto MCP URL (
https://api.truto.one/mcp/...). - Click Add.
Claude will immediately ping the endpoint, discover the reporting and configuration tools, and make them available in your chat context.
Method 2: Via Manual Configuration File
If you are configuring Claude Desktop locally for development, you can add the server directly to your claude_desktop_config.json file using a Server-Sent Events (SSE) transport adapter.
Open your configuration file (typically located at ~/Library/Application Support/Claude/claude_desktop_config.json on macOS or %APPDATA%\Claude\claude_desktop_config.json on Windows) and add the following:
{
"mcpServers": {
"google-analytics-truto": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-sse",
"https://api.truto.one/mcp/t_1234567890abcdef"
]
}
}
}Restart Claude Desktop. The application will initialize the connection and load the GA4 tools dynamically.
Security and Access Control
Giving an LLM direct access to your Google Analytics properties requires strict security parameters. An MCP server should operate under the principle of least privilege. Truto provides several mechanisms to lock down what Claude can and cannot do:
- Method Filtering: By defining
"methods": ["read"]during server creation, you completely strip away the model's ability to create, update, or delete accounts, properties, or key events. If Claude attempts a write operation, the tool simply will not exist in the server's capability list. - Tag Filtering: You can restrict tools based on integration tags. If you only want the agent to access reporting features, you can pass
"tags": ["reporting"], entirely isolating the Admin API tools. - Expiration (
expires_at): You can assign a strict time-to-live for the server. Once the timestamp passes, the token is automatically purged from the underlying KV storage via a scheduled durable object alarm. Lookups fail immediately, severing Claude's access. - Additional API Token Auth: By default, possessing the MCP URL grants access to the tools. If you are deploying in a shared environment where the URL might be exposed, you can enable
require_api_token_auth: true. This forces the client to pass a valid Truto API token in theAuthorizationheader, providing a secondary layer of authentication.
Tokens are never stored in plain text. The random hex token provided in the URL is hashed via HMAC before being written to the database, ensuring that internal infrastructure compromises cannot leak active credentials.
Google Analytics Hero Tools
When Claude connects to the Google Analytics MCP server, it gains access to dozens of endpoints across the Admin and Data APIs. Here are the core "hero" tools that enable high-leverage workflows.
1. google_analytics_compatibility_check
Before running complex reports, Claude needs to know if the requested dimensions and metrics can actually be queried together. This tool validates compatibility for a specific property.
Usage Note: Always prompt the model to call this endpoint before attempting to build a custom report. It prevents the model from hitting hard 400 errors from the GA4 API.
"I need to build a report showing user acquisition by device category and total revenue. Please use
google_analytics_compatibility_checkon property properties/123456789 to verify if 'deviceCategory', 'sessionSource', and 'totalRevenue' are compatible metrics before running the report."
2. google_analytics_reports_run
This is the primary workhorse tool. It executes a customized report of Google Analytics event data for a specified property, accepting complex arrays of dimensions, metrics, and date ranges.
Usage Note: The JSON schema requires arrays for dimensions and metrics. Truto manages the flat input namespace, cleanly separating the query parameters from the complex reporting body schema.
"Run a report on property properties/123456789 for the last 30 days. Give me the 'eventName' and 'date' dimensions against the 'eventCount' and 'activeUsers' metrics. Return the rows grouped by day."
3. list_all_google_analytics_key_events
Retrieves a complete list of Key Events (formerly known as Conversions) for the specified GA4 property.
Usage Note: This is critical for auditing how a property is tracking success. It returns the event names, creation times, and counting methods.
"List all the key events currently configured for the production GA4 property. I need to audit which events are driving our primary conversion metrics and check if 'sign_up' is marked as a key event."
4. create_a_google_analytics_key_event
Allows Claude to programmatically provision a new Key Event for a property based on an existing event name.
Usage Note: You must pass the exact eventName that is already flowing into GA4. Marking it as a key event elevates its status in reporting and attribution.
"We just deployed a new checkout flow that fires the event 'purchase_complete_v2'. Use
create_a_google_analytics_key_eventto mark 'purchase_complete_v2' as a key event on property properties/123456789."
5. list_all_google_analytics_custom_dimensions
Retrieves all custom dimensions configured on a property. Custom dimensions allow you to report on custom event parameters or user properties.
Usage Note: Essential for data governance audits to see what custom data points a property is tracking (e.g., pricing_tier, user_role, subscription_status).
"Audit the custom dimensions for property properties/123456789. Provide a list of all custom dimension parameter names and their scope (event or user)."
6. create_a_google_analytics_custom_dimension
Provisions a new custom dimension for a property, mapping an event parameter to a reportable dimension.
Usage Note: Requires specifying the parameterName, the displayName, and the scope (typically EVENT or USER).
"We are starting to send a 'subscription_tier' parameter with our login events. Create a new event-scoped custom dimension named 'Subscription Tier' mapped to the 'subscription_tier' parameter on property properties/123456789."
To view the complete inventory of available Google Analytics tools and their exact JSON schemas, visit the Google Analytics integration page.
Workflows in Action
With Truto handling the OAuth state, MCP protocol, and parameter parsing, Claude can orchestrate complex, multi-step actions across both the Admin and Data APIs. Here are two real-world scenarios.
Scenario 1: Automated Weekly Traffic & Key Event Reporting
Marketing operations teams spend hours manually pulling data to verify that campaign traffic is resulting in actual conversions. An AI agent can fully automate this audit.
"I need a performance summary for our main website. First, find our primary property ID. Then, list our current Key Events so we know what we are tracking. Finally, run a report for the last 7 days showing 'sessionSourceMedium' and 'deviceCategory' against 'sessions' and the event count for our primary key event."
Step-by-step Execution:
- Claude calls
list_all_google_analytics_accounts_betaandlist_all_google_analytics_propertiesto identify the correctproperty_idfor the main website. - Claude calls
list_all_google_analytics_key_eventsto dynamically discover what constitutes a conversion (e.g., it identifiesgenerate_leadas the primary key event). - Claude calls
google_analytics_compatibility_checkto ensuresessionSourceMediumcan be queried alongsidesessionsandeventCount. - Claude calls
google_analytics_reports_run, passing the validated dimensions, metrics, and date ranges. - The model parses the returned rows and generates a natural language summary of the week's performance directly in the chat.
sequenceDiagram
participant User
participant Claude
participant Truto MCP Server
participant GA4 Admin API
participant GA4 Data API
User->>Claude: "Give me a performance summary..."
Claude->>Truto MCP Server: list_all_google_analytics_properties
Truto MCP Server->>GA4 Admin API: GET /v1beta/properties
GA4 Admin API-->>Truto MCP Server: Return Properties
Truto MCP Server-->>Claude: JSON Array
Claude->>Truto MCP Server: list_all_google_analytics_key_events
Truto MCP Server->>GA4 Admin API: GET /v1beta/properties/123/keyEvents
GA4 Admin API-->>Truto MCP Server: Return Key Events
Truto MCP Server-->>Claude: JSON Array
Claude->>Truto MCP Server: google_analytics_reports_run
Truto MCP Server->>GA4 Data API: POST /v1beta/properties/123:runReport
GA4 Data API-->>Truto MCP Server: Return Report Rows
Truto MCP Server-->>Claude: Report Data
Claude-->>User: Formatted performance summaryScenario 2: Provisioning Custom Tracking for a New Feature
When engineering launches a new feature, product managers often need to manually configure GA4 to recognize the new custom parameters and mark critical actions as conversions. Claude can provision this programmatically.
"We just launched the 'AI Assistant' feature. Engineers are firing an event called 'ai_assistant_usage' with a parameter 'prompt_type'. First, create an event-scoped custom dimension for 'prompt_type'. Then, mark the 'ai_assistant_usage' event as a Key Event so it shows up in our conversion reporting."
Step-by-step Execution:
- Claude calls
create_a_google_analytics_custom_dimension, passing theproperty_id, settingparameterNametoprompt_type,displayNametoPrompt Type, andscopetoEVENT. - Truto routes the request to the GA4 Admin API, and the new dimension is provisioned.
- Claude calls
create_a_google_analytics_key_event, passing theproperty_idand settingeventNametoai_assistant_usage. - Truto executes the creation, elevating the event to a Key Event.
- Claude confirms to the user that the reporting infrastructure for the new feature is fully configured.
The Reality of Google Analytics Rate Limits
When deploying AI agents against the GA4 API, you must design for rate limit saturation. Google Analytics enforces strict token buckets, particularly on the Data API (e.g., 25,000 property tokens per day, 5,000 per hour). Complex queries generated by an LLM will drain these buckets rapidly.
It is critical to understand how Truto handles these limits, especially since handling third-party API rate limits is a core requirement for agent stability. Truto does not retry, throttle, or apply automatic backoff on rate limit errors.
When the upstream Google Analytics API exhausts its quota and returns an HTTP 429 Too Many Requests error, Truto passes that exact error down to the caller via the MCP JSON-RPC protocol. Truto normalizes the upstream rate limit information into standardized HTTP headers per the IETF specification:
ratelimit-limit: The total capacity of the token bucket.ratelimit-remaining: The number of tokens remaining.ratelimit-reset: The time window until the bucket refreshes.
The calling application (or the agent orchestration framework like LangChain or your custom Claude integration) is entirely responsible for catching the 429 error, reading the normalized headers, and implementing exponential backoff.
Moving from Manual Analytics to Agentic Operations
Connecting Google Analytics to Claude via a managed MCP server removes the friction between intent and insight. Instead of navigating the cumbersome GA4 UI to build explorations or writing Python scripts against the Data API, you can orchestrate data extraction and schema configuration using natural language.
By leveraging Truto, you bypass the massive engineering overhead of maintaining OAuth lifecycles, mapping fragmented Admin and Data API endpoints, and keeping JSON schemas updated. You generate a secure, scoped URL, connect it to Claude, and immediately begin running complex analytics workflows.
FAQ
- Does Truto handle Google Analytics rate limits automatically?
- No. Truto passes HTTP 429 Too Many Requests errors directly to the caller, normalizing the upstream headers into standard ratelimit-limit, ratelimit-remaining, and ratelimit-reset fields. The calling agent is responsible for implementing retry and exponential backoff logic.
- How does Truto generate tools for Google Analytics?
- Truto dynamically derives MCP tools from the integration's underlying configuration and documentation records. When a client requests tools, Truto maps available GA4 endpoints into JSON Schema, defining parameters for query and body schemas on the fly.
- How do I filter which Google Analytics endpoints Claude can access?
- You can restrict an MCP server using method filters (e.g., read-only operations) or tag filters. This ensures Claude only has access to reporting endpoints without being able to modify or delete properties.
- How do I connect the MCP server to Claude Desktop?
- You can connect the server via the Claude Desktop UI by adding a new custom connector and pasting the Truto MCP URL. Alternatively, you can edit the claude_desktop_config.json file to run a Server-Sent Events (SSE) command via the Model Context Protocol CLI.