Mcp Google Analytics

io.github.leonardosepulvedat由 GitHub 账号 leonardosepulvedat 发布v1.3.0更新于 Oct 24, 2026

GA4 MCP that reads AND writes: reports, funnels, audits, and server-side events. 26 tools.

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

概览

AI 生成的概览

面向 Google Analytics 4 的本地 MCP 服务器,让助手运行报表、漏斗和媒体资源审计,并通过 Measurement Protocol 发送事件。

可以做什么
在 GA4 媒体资源上运行自定义、实时、透视、漏斗和批量报表,默认限制返回行数以节省 token,并可在查询前检查维度与指标兼容性。发现账号、媒体资源、数据流、自定义维度和指标、关键事件以及关联的 Google Ads 账号,支持跨多个媒体资源查询。审计媒体资源配置,例如自定义定义和转化事件。通过 Measurement Protocol 发送服务端事件:自定义事件、页面浏览、登录、注册、商品浏览、加入购物车、结账、购买和退款。在正式记录前用调试端点校验事件,再通过实时报表确认送达。
适用场景
适合让助手基于 GA4 数据回答分析问题、审计媒体资源的跟踪配置,或在没有 JavaScript 标签的后端与自动化中记录转化和电商事件。也适合代理商在一次对话中查询多个客户的媒体资源。
运行要求
通过 npx 或全局 npm 安装本地运行(需要 Node.js)。需要一个启用 Analytics Data API 的 Google Cloud 服务账号,并在 GA4 媒体资源上授予查看者权限,通过 GA_SERVICE_ACCOUNT_JSON(文件路径或内联 JSON)提供,读取工具还需 GA_PROPERTY_ID。发送事件还需 GA_MEASUREMENT_ID 和 GA_API_SECRET。需要访问 Google API 的网络。
安装前请注意
GA_SERVICE_ACCOUNT_JSON 是私密的服务账号密钥,GA_API_SECRET 是 Measurement Protocol 密钥,二者都属敏感信息,不应外泄。发送事件的工具会向 GA4 写入数据,包括购买和退款,错误数值会扭曲收入报表,建议先校验事件。传入 propertyId 时,读取工具可查询该服务账号能访问的任何媒体资源。

安装

在 SourceWeft 中

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

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

其他 MCP 客户端

参照 仓库 中的启动说明。

README

MCP Google Analytics Server

A Model Context Protocol (MCP) server for Google Analytics 4, providing comprehensive integration with both the Google Analytics Data API (for reading reports) and Measurement Protocol v2 (for sending events).

The GA4 MCP that reads AND writes. Most GA4 MCP servers (including Google's official one) are read-only. This one gives your AI agent the full loop: run reports and funnels, audit your setup (custom dimensions, key events, compatibility checks), send ecommerce and conversion events server-side, and verify them in the realtime report — 26 tools in one npx command.

Built for agencies too: every read tool accepts an optional propertyId, so one conversation can query all your clients' properties — no reconfiguration between clients. See Multi-Property Mode.

[npm version] [npm downloads] [CI] [License: MIT] [smithery badge]

⚡ One-Click Install

You only need two values to start (same as any other GA4 MCP): the service account JSON and your property ID. Sending events is an optional extra.

[Install MCP Server]

Click Install in Cursor, then paste:

  1. GA_SERVICE_ACCOUNT_JSON — path to the downloaded key file, or the JSON itself
  2. GA_PROPERTY_ID — the numeric ID in GA4 Admin → Property Settings (e.g. 123456789)

That is enough to ask “users by country this week”. To also send events, add two more keys later (see Send events (optional)).

💡 Keep reports small

Reports can get large. This server is designed with token optimization in mind:

  • All read tools default to 10 results - Adjust the limit parameter as needed
  • Use specific date ranges - Avoid querying years of data at once
  • Select only needed dimensions/metrics - Don't request everything
  • Check TOKEN_OPTIMIZATION.md for detailed best practices

See the dedicated Token Optimization Guide for strategies to minimize token usage.

🚀 Quick Start

See QUICKSTART.md for a 5-minute setup guide, or follow the installation steps below.

📦 Installation

Option 1: Install globally via npm

bash
npm install -g mcp-google-analytics

Option 2: Use with npx (no installation needed)

bash
npx mcp-google-analytics

🔧 Configuration

Start with two values. That unlocks reports, funnels, realtime, and property audits — everything most people need, and the same setup every other GA4 MCP asks for.

1. Service account key

  1. In Google Cloud Console, enable Google Analytics Data API.
  2. IAM & Admin → Service Accounts → Create. Download a JSON key.
  3. In GA4: Admin → Property Access Management → add the service account email as Viewer.

Use the file path or paste the JSON into GA_SERVICE_ACCOUNT_JSON.

2. Property ID

GA4 Admin → Property Settings → Property ID (numbers only, e.g. 123456789).

json
{  "mcpServers": {    "google-analytics": {      "command": "npx",      "args": ["-y", "mcp-google-analytics"],      "env": {        "GA_SERVICE_ACCOUNT_JSON": "/path/to/service-account.json",        "GA_PROPERTY_ID": "123456789"      }    }  }}

You can now ask: “Show me active users by country this week.”

Send events (optional)

Only if you want the agent to record events (purchases, signups, custom events). Most GA4 MCPs cannot do this; it is extra, not required.

  1. GA4 Admin → Data Streams → your stream → copy Measurement ID (G-XXXXXXXXXX).
  2. Measurement Protocol API secrets → Create → copy the secret.

Add them next to the two values you already have:

json
"GA_MEASUREMENT_ID": "G-XXXXXXXXXX","GA_API_SECRET": "your-api-secret"

🏢 Multi-Property Mode (Agencies)

Every read tool accepts an optional propertyId argument that overrides the configured GA_PROPERTY_ID — so a single conversation can query any property the service account can access, with no reconfiguration between clients.

  1. Grant your service account "Viewer" access on each client's GA4 property (or at account level).
  2. Set only GA_SERVICE_ACCOUNT_JSON (GA_PROPERTY_ID becomes optional — if set, it acts as the default).
  3. Discover properties, then query any of them:
Show me all my accounts and properties          → ga_get_account_summariesCompare last week's active users between the    → ga_run_report with propertyId "111111"Acme property and the Globex property             and again with propertyId "222222"

propertyId accepts both 123456789 and properties/123456789. Event sending (Measurement Protocol) remains tied to the configured GA_MEASUREMENT_ID/GA_API_SECRET, since each data stream has its own secret.

🔌 Integration with Claude Desktop

Add to your Claude Desktop configuration file:

macOS: ~/Library/Application Support/Claude/claude_desktop_config.json Windows: %APPDATA%/Claude/claude_desktop_config.json

json
{  "mcpServers": {    "google-analytics": {      "command": "npx",      "args": ["-y", "mcp-google-analytics"],      "env": {        "GA_SERVICE_ACCOUNT_JSON": "/path/to/service-account.json",        "GA_PROPERTY_ID": "123456789"      }    }  }}

Or if installed globally:

json
{  "mcpServers": {    "google-analytics": {      "command": "mcp-google-analytics",      "env": {        "GA_SERVICE_ACCOUNT_JSON": "/path/to/service-account.json",        "GA_PROPERTY_ID": "123456789"      }    }  }}

Restart Claude Desktop after updating the configuration.

🎯 Integration with Cursor

Add to your Cursor MCP settings file:

macOS/Linux: ~/.cursor/mcp.json Windows: %USERPROFILE%\.cursor\mcp.json

json
{  "mcpServers": {    "google-analytics": {      "command": "npx",      "args": ["-y", "mcp-google-analytics"],      "env": {        "GA_SERVICE_ACCOUNT_JSON": "/path/to/service-account.json",        "GA_PROPERTY_ID": "123456789"      }    }  }}

Restart Cursor after updating the configuration.

🛠️ Available Tools

At a Glance

Reading data (Google Analytics Data API) — all read tools default to 10 rows to save tokens:

ToolPurposeNotes
ga_run_reportCustom reports with dimensions and metricsAdjust limit as needed
ga_run_realtime_reportReal-time data (last 30 minutes)Great for verifying sent events
ga_get_metadataAll available dimensions and metricsLarge response (500+ items), use sparingly
ga_list_accountsList accessible GA accounts
ga_list_propertiesList GA4 propertiesAggregates all accounts if no accountId
ga_get_propertyDetails of the configured property
ga_list_data_streamsData streams of the propertyUseful to find measurement IDs
ga_run_pivot_reportPivot table reportsResponses can be very large
ga_run_funnel_reportFunnel analysis across event stepsUses Data API v1alpha
ga_batch_run_reportsMultiple reports in one request2–5 reports per batch recommended
ga_get_account_summariesAll accounts and properties in one callFastest way to discover IDs
ga_list_custom_dimensionsCustom dimensions of the propertyDiscover API names for reports
ga_list_custom_metricsCustom metrics of the propertyDiscover API names for reports
ga_list_key_eventsKey events (conversions) of the propertyKnow what counts as a conversion
ga_list_google_ads_linksGoogle Ads accounts linked to the property
ga_check_compatibilityValidate dimension/metric combos before reportingAvoids wasted requests and error loops

Sending events (Measurement Protocol):

ToolPurpose
ga_send_eventAny custom GA4 event with parameters
ga_validate_eventTest an event against the debug endpoint without recording it
ga_send_pageviewPage/screen views
ga_send_purchaseEcommerce purchases with transaction and items
ga_send_loginUser logins
ga_send_signupUser registrations
ga_send_view_itemProduct/item detail views
ga_send_add_to_cartAdd-to-cart events
ga_send_begin_checkoutCheckout initiations
ga_send_refundFull or partial refunds

Google Analytics Data API (Reading Data)

ga_run_report

Run custom reports with dimensions and metrics.

Common Dimensions: date, city, country, deviceCategory, browser, pagePath, eventName, sessionSource, sessionMedium, sessionCampaignName

Common Metrics: activeUsers, sessions, screenPageViews, conversions, totalRevenue, engagementRate, averageSessionDuration

Example:

typescript
{  "dateRanges": [{"startDate": "7daysAgo", "endDate": "today"}],  "dimensions": [{"name": "city"}],  "metrics": [{"name": "activeUsers"}],  "limit": 10}
ga_run_realtime_report

Get real-time data (last 30 minutes).

Example:

typescript
{  "metrics": [{"name": "activeUsers"}],  "dimensions": [{"name": "country"}],  "limit": 10}
ga_get_metadata

Get all available dimensions and metrics for your property.

Warning: Returns 500+ items. Use sparingly.

ga_list_accounts

List all GA accounts accessible to the service account.

ga_list_properties

List GA4 properties, optionally filtered by account ID.

ga_get_property

Get details about the configured property.

ga_list_data_streams

List data streams for the configured property.

ga_run_pivot_report

Run pivot table reports with row/column dimensions.

Example:

typescript
{  "dateRanges": [{"startDate": "7daysAgo", "endDate": "today"}],  "dimensions": [{"name": "country"}, {"name": "deviceCategory"}],  "metrics": [{"name": "activeUsers"}],  "pivots": [{"fieldNames": ["deviceCategory"], "limit": 5}]}
ga_run_funnel_report

Run funnel analysis to track user progression.

Note: Funnel reporting uses the Data API v1alpha channel (the only channel where Google exposes it). Each step matches an event: set eventName per step, or omit it to use the step's name as the event name. For advanced matching, pass a full filterExpression.

Example:

typescript
{  "dateRanges": [{"startDate": "7daysAgo", "endDate": "today"}],  "funnelSteps": [    {"name": "page_view"},    {"name": "add_to_cart"},    {"name": "begin_checkout"},    {"name": "Purchase", "eventName": "purchase"}  ]}
ga_batch_run_reports

Run multiple reports in a single request.

Warning: Can return large datasets. Limit to 2-5 reports per batch.

ga_get_account_summaries

Get all accessible accounts with their properties in a single compact call. The fastest way to discover account and property IDs.

ga_list_custom_dimensions / ga_list_custom_metrics

List the custom dimensions and metrics defined for the property, including their API names (e.g., customEvent:plan_type) so you can use them in reports.

ga_list_key_events

List the key events (conversions) configured for the property — useful before building conversion reports or deciding which events to send.

ga_list_google_ads_links

List Google Ads accounts linked to the property.

ga_check_compatibility

Check whether a dimension/metric combination is valid before running a report, avoiding wasted requests and token-heavy error loops.

Example:

typescript
{  "dimensions": [{"name": "city"}],  "metrics": [{"name": "activeUsers"}],  "compatibilityFilter": "COMPATIBLE"}

Measurement Protocol (Sending Events)

Good to know:

  • Events take a few minutes to appear in standard reports, but show up almost immediately in the realtime report (ga_run_realtime_report).
  • Use ga_validate_event to test new events without recording them.
  • If you omit client_id, one is auto-generated per call. To have GA group several events (e.g., a cart-to-purchase flow) into the same session and user, pass the same client_id to every call.
ga_send_event

Send custom events to GA4.

Example:

typescript
{  "events": [{    "name": "button_click",    "params": {      "button_id": "cta_signup",      "page": "/landing"    }  }],  "user_id": "user123"}
ga_validate_event

Validate events before sending (uses debug endpoint).

ga_send_pageview

Send page view events.

Example:

typescript
{  "page_location": "https://example.com/products",  "page_title": "Products",  "user_id": "user123"}
ga_send_purchase

Send ecommerce purchase events.

Example:

typescript
{  "transaction_id": "T12345",  "value": 99.99,  "currency": "USD",  "items": [{    "item_id": "SKU123",    "item_name": "Product Name",    "price": 99.99,    "quantity": 1  }]}
ga_send_login

Send login events.

ga_send_signup

Send user registration events.

ga_send_view_item

Send product/item detail view events. Completes the standard ecommerce funnel: view_item → add_to_cart → begin_checkout → purchase.

ga_send_add_to_cart

Send add-to-cart events.

ga_send_begin_checkout

Send checkout initiation events.

ga_send_refund

Send full or partial refund events. Use the same transaction_id as the original purchase; omit items for a full refund, include them for a partial one.

Example (partial refund):

typescript
{  "transaction_id": "T12345",  "currency": "USD",  "value": 49.99,  "items": [{"item_id": "SKU123", "quantity": 1}]}

📖 Usage Examples

See EXAMPLES.md for practical usage examples in Spanish.

Example: Get users by country (last 7 days)

Show me active users by country for the last 7 days

Claude will use ga_run_report:

json
{  "dateRanges": [{"startDate": "7daysAgo", "endDate": "today"}],  "dimensions": [{"name": "country"}],  "metrics": [{"name": "activeUsers"}],  "limit": 10,  "orderBys": [{"metric": {"metricName": "activeUsers"}, "desc": true}]}

Example: Track a purchase

Send a purchase event for order #12345, $99.99 USD

Claude will use ga_send_purchase:

json
{  "transaction_id": "12345",  "value": 99.99,  "currency": "USD",  "items": [{    "item_id": "product_1",    "item_name": "Example Product",    "price": 99.99,    "quantity": 1  }]}

Example: Validate an event before sending it

Recommended before wiring up any new event: the debug endpoint checks the payload without recording anything.

Validate this tutorial_complete event before we send it for real

Claude will use ga_validate_event:

json
{  "client_id": "test.123",  "events": [{    "name": "tutorial_complete",    "params": {"tutorial_id": "onboarding", "duration_seconds": 120}  }]}

The response lists validation messages; an empty list means the event is well-formed.

Example: Server-side conversion tracking

Track signups or logins that happen in your backend, where no JavaScript tag runs:

A user just registered with Google OAuth, record the signup in Analytics

Claude will use ga_send_signup:

json
{  "user_id": "user_789",  "method": "Google"}

Example: Full ecommerce funnel from an agent

Send the same client_id on each call so GA groups the events into one session:

Track this user's journey: they added a $49 course to the cart, started checkout, and completed the purchase

Claude will chain ga_send_add_to_cart → ga_send_begin_checkout → ga_send_purchase, reusing the client ID:

json
{  "client_id": "555.1717000000",  "currency": "USD",  "value": 49,  "items": [{"item_id": "course_101", "item_name": "Intro Course", "price": 49, "quantity": 1}]}

Example: Custom events from automations

Measure things GA never sees natively, like AI agent activity or scheduled jobs:

Log that the weekly report generator ran successfully

Claude will use ga_send_event:

json
{  "events": [{    "name": "automation_run",    "params": {"job": "weekly_report", "status": "success", "duration_ms": 5400}  }]}

Example: Send and verify in one conversation

Combine both APIs to confirm your tracking works end to end:

Send a test event and confirm Analytics received it

Claude will call ga_send_event, then check with ga_run_realtime_report:

json
{  "dimensions": [{"name": "eventName"}],  "metrics": [{"name": "eventCount"}],  "limit": 10}

Measurement Protocol events appear in the realtime report within seconds, while standard reports can take a few minutes.

🔍 Debugging

Enable debug logging by setting:

bash
export DEBUG=mcp-google-analytics:*

For Measurement Protocol, use ga_validate_event to check events before sending them live.

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

📄 License

MIT License - see LICENSE file for details.

🔗 Links

🆘 Support

For issues and questions:

📝 Changelog

See CHANGELOG.md for version history.


来源:README.md,提交 97731c9

工具

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

版本历史

1
  1. v1.3.0最新Sep 16, 2026

评分

已满足适用检查项的 50%

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

  • 近 30 天内可连通25 分

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

  • 已声明认证方式10 分

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

  • 已列出工具15 分

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

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