Ga4

io.github.mharnett由 GitHub 账号 mharnett 发布v2.0.1更新于 Oct 24, 2026

Google Analytics 4 MCP: reports, realtime data, custom dimensions, data streams.

已验证STDIO仅桌面数据与分析商业与电商

概览

AI 生成的概览

一个本地 MCP 服务器,让助手查询 Google Analytics 4 媒体资源:运行报告、读取实时数据,并查看或创建自定义维度和数据流。

可以做什么
按指定维度、指标、日期范围和筛选条件运行标准 GA4 报告,支持 7daysAgo、30daysAgo 等相对日期,并查询最近 30 分钟的实时数据。列出该媒体资源的自定义维度和自定义指标,并可创建新的自定义维度。列出网站和应用数据流及其衡量 ID。返回当前生效的媒体资源 ID 和客户名称,并对查询结果提交反馈或改进建议。
适用场景
适合让助手拉取 GA4 的流量、页面、广告系列或设备数据并在对话中汇总,或在不打开 Analytics 界面的情况下查看实时活动和媒体资源配置。
运行要求
通过 npm 本地运行(npx mcp-ga4 或全局安装),需要 Node.js。需要 GA4_PROPERTY_ID,以及以下任一种凭据:GOOGLE_APPLICATION_CREDENTIALS 中的服务账号密钥文件路径,或 OAuth 三项 GA4_CLIENT_ID、GA4_CLIENT_SECRET、GA4_REFRESH_TOKEN。服务账号须在 GA4 媒体资源上获得访问权限;OAuth 需在 Google Cloud 创建桌面应用客户端并启用 Analytics Data API。需要访问 Google API 的网络连接。
安装前请注意
涉及 Google 凭据:服务账号密钥文件、OAuth 客户端密钥和刷新令牌均属敏感信息,令牌辅助脚本会把刷新令牌打印到标准输出,注意不要记录。默认授权范围包含 analytics.edit,因为创建自定义维度的工具会修改媒体资源;若只需报告,应改为只读范围。配置文件可能含凭据,不应提交到版本库。报告数据有 24-48 小时延迟,实时数据仅覆盖最近 30 分钟。

安装

在 SourceWeft 中

  1. 打开 控制台中的 Ga4,将其添加到工作区。
  2. 为需要使用其工具的对话启用该服务。

Desktop only,通过 STDIO。 STDIO 服务会启动本地进程,因此需要 SourceWeft 桌面宿主。

其他 MCP 客户端

参照 仓库 中的启动说明。

README

mcp-ga4

MCP server for Google Analytics 4 -- run reports, realtime data, custom dimensions, and property management via Claude.

Features

  • 9 tools covering reporting, realtime data, custom dimensions/metrics, data streams, and feedback
  • Two configuration modes: single-property (env vars) and multi-client (config.json)
  • Supports both service account and OAuth credentials
  • Relative date support (today, yesterday, 7daysAgo, 30daysAgo, 90daysAgo)
  • Built on official Google SDKs with resilience patterns

Quick start

  1. Get credentials -- a service-account keyfile, or a user-OAuth refresh token (see Authentication).

  2. Register the server with every Claude client on this machine:

    bash
    # service accountnpx -p mcp-ga4 mcp-ga4-setup --property-id 123456789 --credentials /path/to/service-account.json
    # or user OAuth: export GA4_CLIENT_ID / GA4_CLIENT_SECRET / GA4_REFRESH_TOKEN firstnpx -p mcp-ga4 mcp-ga4-setup --property-id 123456789

    The wizard detects Claude Desktop (~/Library/Application Support/Claude/claude_desktop_config.json on macOS, %APPDATA%\Claude\claude_desktop_config.json on Windows) and the Claude Code CLI (claude on PATH) and registers ga4 with each one it finds. Other servers and settings in the Desktop config are preserved; an invalid config file is left untouched and the wizard stops. Re-running is safe. Use --claude-desktop-only or --claude-code-only to target one client.

  3. Fully quit and reopen Claude Desktop (Cmd+Q), or restart your claude session.

Installation

bash
npm install mcp-ga4

Or clone the repository:

bash
git clone https://github.com/mharnett/mcp-ga4.gitcd mcp-ga4npm installnpm run build

Authentication

mcp-ga4 supports two credential families. Selection is deterministic and happens once, at startup: an explicit keyfile / service account wins, then user OAuth, and if neither is configured the server exits with a loud onboarding error naming both options. There is no machine-local credentials path baked into the code and no silent runtime failover -- the only credential inputs are environment variables and (optionally) your own per-user config.json. (A later 403 therefore surfaces as the API error, not as a silent switch to the other credential family.)

Precedence: when both families are configured, the keyfile / service account takes precedence over user OAuth.

Option A: Service account (recommended for unattended / server use)

Use this for any always-on or server deployment. Point GOOGLE_APPLICATION_CREDENTIALS (or config.json credentials_file) at a JSON keyfile. The service account must be granted access on the GA4 property (Admin → Property Access Management → add the service-account email with at least Viewer). No refresh token is involved -- the server hands the keyfile to the GA4 SDKs directly:

bash
GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json

The keyfile may be a real service-account key or an authorized_user OAuth token dump -- both are accepted via the keyFile option.

Option B: User OAuth (personal / interactive use)

Use this if you want the server to act as a Google user (your own GA4 login). You bring your own Google OAuth client and mint a refresh token once.

  1. In Google Cloud Console, create an OAuth 2.0 Client ID of type Desktop app. Enable the Google Analytics Data API (and the Admin API if you use the custom-dimension tools).

  2. Export your client credentials and run the token helper (uses PKCE, opens a browser, prints the token to stdout):

    bash
    export GA4_CLIENT_ID=...            # from the Desktop-app clientexport GA4_CLIENT_SECRET=...node get-refresh-token.cjs          # or: npm run auth

    Do not redirect this command's stdout to a shared log -- the refresh token is printed there by design.

  3. Copy the printed GA4_REFRESH_TOKEN=... into your environment. At runtime the server reads these three env vars:

    bash
    GA4_CLIENT_ID=...GA4_CLIENT_SECRET=...GA4_REFRESH_TOKEN=...

The scope requested is read from config.json oauth.scope (see below), so the helper and the running server never disagree on what you granted.

Scopes (minimum grant)

Scopes live in config.json under oauth.scope. The committed default is:

https://www.googleapis.com/auth/analytics.readonlyhttps://www.googleapis.com/auth/analytics.edit

analytics.edit is required because ga4_create_custom_dimension mutates the property via the Admin API. If you only need read access, override oauth.scope in your own config.json to analytics.readonly alone and re-run the helper.

Configuration

Security: Never share your .mcp.json file or commit it to git -- it may contain API credentials. Add .mcp.json to your .gitignore.

Mode 1: Single Property (env vars)

Set a property ID plus one of the auth families above:

bash
GA4_PROPERTY_ID=123456789# then EITHER the OAuth trio (GA4_CLIENT_ID/SECRET/REFRESH_TOKEN)# OR a service account: GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json

Mode 2: Multi-Client (config.json)

Create a config.json in the project root to map multiple GA4 properties to project directories. The server auto-detects which property to use based on the caller's working directory. Credentials come from the environment (Option A/B above); config.json may optionally carry a credentials_file service-account path for a config-only SA setup.

json
{  "oauth": {    "scope": "https://www.googleapis.com/auth/analytics.readonly https://www.googleapis.com/auth/analytics.edit"  },  "clients": {    "client-a": {      "name": "Client A",      "folder": "/path/to/client-a/project",      "property_id": "123456789"    },    "client-b": {      "name": "Client B",      "folder": "/path/to/client-b/project",      "property_id": "987654321"    }  }}

Usage

Manual configuration

mcp-ga4-setup (see Quick start) writes this for you. To manage the entry by hand, the single-property shape is:

json
{  "mcpServers": {    "ga4": {      "command": "npx",      "args": ["mcp-ga4"],      "env": {        "GA4_PROPERTY_ID": "123456789",        "GOOGLE_APPLICATION_CREDENTIALS": "/path/to/credentials.json"      }    }  }}

Multi-client mode:

json
{  "mcpServers": {    "ga4": {      "command": "node",      "args": ["/path/to/mcp-ga4/dist/index.js"]    }  }}

The same mcpServers shape is used by Claude Code project configs and by Claude Desktop's claude_desktop_config.json.

Common Query Patterns

Top pages: dimensions=pagePath, metrics=screenPageViews, order_by=screenPageViews

Traffic sources: dimensions=sessionSource,sessionMedium, metrics=sessions,totalUsers

Daily trend: dimensions=date, metrics=sessions,totalUsers

Campaign performance: dimensions=sessionCampaignName, metrics=sessions,conversions

Device breakdown: dimensions=deviceCategory, metrics=sessions,totalUsers

Tools

ToolDescription
ga4_get_client_contextReturns the active GA4 property ID and client name
ga4_run_reportRun a standard GA4 report with dimensions, metrics, date range, and filters
ga4_realtime_reportQuery realtime data (last 30 minutes)
ga4_list_custom_dimensionsList all custom dimensions for the property
ga4_create_custom_dimensionCreate a new custom dimension
ga4_list_custom_metricsList all custom metrics for the property
ga4_list_data_streamsList web/app data streams and their measurement IDs
ga4_send_feedbackSubmit feedback on a query result
ga4_suggest_improvementSuggest a new query pattern or improvement

Date Formats

Use YYYY-MM-DD for absolute dates, or these relative shortcuts:

  • today
  • yesterday
  • 7daysAgo
  • 30daysAgo
  • 90daysAgo

Common Dimensions and Metrics

Dimensions: date, dateHour, eventName, pagePath, pageTitle, sessionSource, sessionMedium, sessionCampaignName, country, city, deviceCategory, browser, operatingSystem, landingPage, pageReferrer, newVsReturning, firstUserSource, firstUserMedium, firstUserCampaignName

Metrics: sessions, totalUsers, newUsers, activeUsers, screenPageViews, eventCount, conversions, engagedSessions, engagementRate, averageSessionDuration, bounceRate, sessionsPerUser, screenPageViewsPerSession, userEngagementDuration

Data Freshness

  • Standard reports: 24-48 hour delay
  • Realtime reports: last 30 minutes only

Architecture

Built on:

  • @google-analytics/data -- GA4 Data API for reports
  • @google-analytics/admin -- GA4 Admin API for property management
  • cockatiel -- resilience (retry, circuit breaker)
  • pino -- structured logging

License

MIT

Author

Built by Mark Harnett / drak-marketing

来源:README.md,提交 e44f8b0

工具

0
SourceWeft 尚未在沙箱中启动过该软件包,因此其工具未知。

版本历史

1
  1. v2.0.1最新Sep 16, 2026

评分

已满足适用检查项的 50%

该评分衡量此收录条目的完整程度,依据注册中心条目、端点与公开来源计算得出。它不是对服务器本身的评价,也不表示服务器安全或当前可用:可连通性是带日期的检查结果,评分也不包含安装量或用户评价。

  • 近 30 天内可连通25 分

    请保持端点能够响应 MCP 握手;SourceWeft 每 30 天探测一次。

  • 已声明认证方式10 分

    请在注册中心条目中声明凭据请求头,或保持端点能够响应探测,以便判定其认证方式。

  • 已列出工具15 分

    请让服务器在无凭据时响应 tools/list,或发布可在沙箱中无凭据启动的软件包。

  • 描述必需15 分
  • 图标10 分
  • 文档15 分
  • 许可证10 分