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 分