Skip to main content
Glama
ga4-mcp-server

ga4-mcp-server

by dienhokhanh

ga4-mcp-server

CI npm License: MIT

A Model Context Protocol server for Google Analytics 4. Ask your AI assistant questions like "How did organic traffic change this week?" or "Which landing pages convert worst?" and it queries GA4 for you.

Works with Claude Code, Claude Desktop, OpenAI Codex, Cursor, VS Code (Copilot), Gemini CLI, Windsurf and any other MCP client.

Built and maintained by Dien Ho of PPCBlogPro, a blog on PPC, analytics and AI marketing tools.

  • 📊 Reports: standard, pivot, realtime and batched reports with filters, sorting, totals and date comparisons

  • 🔎 Discovery: accounts, properties, data streams, dimension/metric catalogue, compatibility checks

  • 🏷️ Friendly property lookup: say "My Blog" instead of properties/123456789

  • 🧠 Context-friendly output: compact JSON records, row caps, and clear error messages with fix-it hints

  • 🔐 Three ways to sign in: service account, browser sign-in, or gcloud Application Default Credentials

  • ✍️ Optional admin writes: create custom dimensions/metrics and key events. Off by default.

Quick start

1. Get credentials. You need Node.js 22+ and access to a GA4 property. The fastest route for most people is a service account:

  1. In Google Cloud Console, pick or create a project and enable the Google Analytics Data API and Google Analytics Admin API.

  2. Go to IAM & Admin → Service Accounts, create a service account, and download a JSON key.

  3. In GA4 → Admin → Property access management, add the service account's email as a Viewer.

Prefer to sign in with your own Google account? See docs/authentication.md.

2. Add the server to your client (replace the path and property):

claude mcp add ga4 \
  -e GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json \
  -e GA4_DEFAULT_PROPERTY=123456789 \
  -- npx -y ga4-mcp-server
[mcp_servers.ga4]
command = "npx"
args = ["-y", "ga4-mcp-server"]

[mcp_servers.ga4.env]
GOOGLE_APPLICATION_CREDENTIALS = "/path/to/service-account.json"
GA4_DEFAULT_PROPERTY = "123456789"

Or: codex mcp add ga4 --env GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json -- npx -y ga4-mcp-server

{
  "mcpServers": {
    "ga4": {
      "command": "npx",
      "args": ["-y", "ga4-mcp-server"],
      "env": {
        "GOOGLE_APPLICATION_CREDENTIALS": "/path/to/service-account.json",
        "GA4_DEFAULT_PROPERTY": "123456789"
      }
    }
  }
}

Same mcpServers block as Claude Desktop above.

{
  "servers": {
    "ga4": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "ga4-mcp-server"],
      "env": {
        "GOOGLE_APPLICATION_CREDENTIALS": "/path/to/service-account.json"
      }
    }
  }
}

More ready-to-copy configs are in examples/. On Windows, use paths like C:\\keys\\sa.json in JSON, or 'C:\keys\sa.json' in TOML.

3. Ask away:

Which GA4 properties can I access?

Compare sessions and key events by channel for the last 28 days vs the previous 28 days.

Show the top 20 landing pages by sessions last week, with engagement rate.

How many people are on the site right now, by country?

Related MCP server: Google Analytics MCP Server

Tools

Tool

What it does

list_accounts

Accounts you can access, each with its properties

list_properties

Flat, filterable list of properties

get_property

Time zone, currency, industry, service level

list_data_streams

Web/app streams and measurement IDs

get_metadata

Searchable catalogue of dimensions & metrics (incl. custom)

check_compatibility

Can these dimensions and metrics be used together?

run_report

Core Data API report: dimensions, metrics, date ranges, filters, sorting, totals

batch_run_reports

Up to 5 reports in one call

run_pivot_report

Cross-tab reports

run_realtime_report

Last 30 minutes of activity

list_custom_dimensions, list_custom_metrics, list_key_events, list_audiences

Property configuration

Write tools (only when GA4_MCP_ENABLE_WRITES=true): create_custom_dimension, create_custom_metric, create_key_event, archive_custom_dimension, archive_custom_metric.

Prompts: weekly_traffic_summary, top_landing_pages, channel_performance.

Full parameter reference: docs/tools.md.

Configuration

Variable

Default

Description

GOOGLE_APPLICATION_CREDENTIALS

none

Path to a service account key (or other ADC JSON)

GA4_DEFAULT_PROPERTY

none

Property ID or display name used when a tool call omits property

GA4_MCP_ENABLE_WRITES

false

Register write tools and request the analytics.edit scope

GA4_MCP_MAX_ROWS

1000

Hard cap on rows returned per report (protects the model's context window)

GA4_MCP_TOKEN_FILE

OS config dir token.json

Where ga4-mcp-server auth saves the browser sign-in token

Credentials are chosen in this order: GOOGLE_APPLICATION_CREDENTIALS → saved browser sign-in token → Application Default Credentials.

Enabling write tools

Write tools change your GA4 configuration, so they're opt-in:

  1. Set GA4_MCP_ENABLE_WRITES=true in the server's env.

  2. Give the service account Editor on the property (or re-run npx ga4-mcp-server auth --enable-writes for browser sign-in).

Tools are annotated (readOnlyHint / destructiveHint) so clients can ask you before running anything that changes data.

Troubleshooting

Message

Fix

Could not load the default credentials

Set GOOGLE_APPLICATION_CREDENTIALS, or run npx ga4-mcp-server auth. See authentication.

Permission denied

Add the service account / user to the GA4 property, and make sure both Analytics APIs are enabled in your Cloud project.

... is not a valid dimension

Ask the assistant to call get_metadata with a search term to find the exact API name.

insufficient authentication scopes

Write tools need GA4_MCP_ENABLE_WRITES=true and credentials with the analytics.edit scope.

Test the server interactively with the MCP Inspector: npx @modelcontextprotocol/inspector npx -y ga4-mcp-server.

Development

git clone https://github.com/dienhokhanh/ga4-mcp-server.git
cd ga4-mcp-server
npm install
npm run build
npm test          # unit + integration tests (mocked Google APIs, no credentials needed)
npm run lint
npm run inspect   # open the MCP Inspector against the local build
npm run smoke     # optional: live read-only check against your GA4 (needs credentials)

See CONTRIBUTING.md.

Privacy & security

The server runs locally and talks only to Google's Analytics APIs. Report data goes to the AI client you connect it to, so treat it as you would any analytics export. Never commit credential files. See SECURITY.md.

Author

Made by Dien Ho. I write about Google Ads, LinkedIn Ads, GA4 measurement and AI tools for marketers at PPCBlogPro.com. If this server saves you time, a ⭐ on GitHub or a visit to the blog is appreciated.

License

MIT. Not affiliated with or endorsed by Google. Google Analytics is a trademark of Google LLC.

Available Tools

14 tools
batch_run_reportsRun several GA4 reportsA
Read-only

Run up to 5 reports for one property in a single API call (cheaper and faster than separate run_report calls). Each request takes the same fields as run_report.

Inputs: requests (required), property.

check_compatibilityCheck dimension/metric compatibilityA
Read-only

Check whether a set of dimensions and metrics can be used together in one report. Returns the incompatible fields (if any). Use before run_report when mixing scopes, e.g. item-scoped with session-scoped fields.

Inputs: metrics, property, dimensions, metricFilter, +1 more.

get_metadataGet dimensions & metricsA
Read-only

List the dimension and metric API names available for reports on a property, including the property's custom dimensions/metrics (e.g. customEvent:plan_type). Use search to narrow the list — the full catalogue is large.

Inputs: kind, search, property, customOnly, +1 more.

get_propertyGet GA4 property detailsA
Read-only

Get a GA4 property's settings: time zone, currency, industry category, service level (Standard/360), creation time and parent account.

Inputs: property.

list_accountsList GA4 accountsA
Read-only

List the Google Analytics accounts the authenticated user can access, each with its GA4 properties (ID and display name). Start here when you don't know the property ID.

Inputs: no named parameters.

list_audiencesList audiencesA
Read-only

List a property's audiences (uses the v1alpha Admin API). By default returns a summary; set includeDefinitions for full filter clauses.

Inputs: property, includeDefinitions.

list_custom_dimensionsList custom dimensionsA
Read-only

List a property's custom dimensions (parameter name, display name, scope). In reports they're referenced as customEvent:, customUser: or customItem:.

Inputs: property.

list_custom_metricsList custom metricsB
Read-only

List a property's custom metrics (parameter name, display name, unit, scope).

Inputs: property.

list_data_streamsList data streamsB
Read-only

List a property's data streams (web, Android, iOS) including measurement IDs (G-XXXX), website URLs and app IDs.

Inputs: property.

list_key_eventsList key eventsB
Read-only

List a property's key events (formerly called conversions), with counting method and creation time.

Inputs: property.

list_propertiesList GA4 propertiesA
Read-only

List accessible GA4 properties as a flat list. Optionally filter by account (ID or name) or by a case-insensitive search on the property name.

Inputs: search, account.

run_pivot_reportRun GA4 pivot reportB
Read-only

Run a pivot (cross-tab) report. Every dimension must appear in exactly one pivot's fieldNames. Example: pivots [{fieldNames:["country"],limit:5},{fieldNames:["deviceCategory"],limit:3}] with metric sessions.

Inputs: pivots (required), metrics (required), dimensions (required), property, +5 more.

run_realtime_reportRun GA4 realtime reportA
Read-only

Report on events from the last 30 minutes (up to 60 for GA4 360). Realtime supports a limited set of fields, e.g. dimensions country, city, deviceCategory, unifiedScreenName, eventName, minutesAgo; metrics activeUsers, eventCount, keyEvents, screenPageViews.

Inputs: metrics (required), limit, orderBys, property, +5 more.

run_reportRun GA4 reportA
Read-only

Run a Google Analytics 4 report (Data API runReport). Returns rows as JSON records keyed by dimension/metric name. Examples: traffic by channel, top pages, conversions by campaign, revenue by country, daily trend with dimension "date".

Inputs: metrics (required), limit, offset, orderBys, +8 more.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.8/5.0

    Scored across 14 tools

    Disambiguation4/5

    Tools are mostly distinct by resource and action, but get_metadata overlaps with list_custom_dimensions/list_custom_metrics for custom fields, and list_accounts/list_properties both surface property information. Descriptions help clarify the intended use, so misselection is unlikely but possible.

    Naming Consistency5/5

    All names follow a consistent snake_case verb_noun pattern (list_*, get_*, run_*, check_*, batch_run_*). There is no mixing of casing or verb styles, making the set predictable and easy to navigate.

    Tool Count5/5

    With 14 tools, the server comfortably covers the GA4 reporting and metadata surface without feeling bloated. Each tool maps to a meaningful operation and the count falls within a well-scoped range.

    Completeness4/5

    The read/query surface is strong, covering accounts, properties, streams, metadata, compatibility checks, multiple report types, custom dimensions/metrics, key events, and audiences. However, admin write operations (create/update/delete) and some report types like funnel reports are absent, leaving minor gaps for full GA4 lifecycle coverage.

    Maintenance

    ActivitySlowing
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI agents to interact with Google Analytics 4 data, providing tools for historical reporting, real-time activity monitoring, and property management. It supports secure service account authentication to access metrics like traffic summaries, user acquisition, and custom dimensions.
      MIT
    • A
      license
      B
      quality
      D
      maintenance
      Enables managing Google Analytics 4 properties, data streams, conversions, and running reports using natural language through the Admin and Data APIs.
      23
      MIT