
Samarth Gtm Mcp
io.github.samarthanalytics-sj由 GitHub 账号 samarthanalytics-sj 发布v1.19.0更新于 Oct 24, 2026
Google Tag Manager + read-only GA4 MCP server. Read-only by default, gated writes, audits.
概览
面向 Google Tag Manager 与只读 GA4 的本地 MCP 服务器:可浏览、审计,并在开启后编辑、发布或删除 GTM 资源。
- 可以做什么
- 列出并查看 GTM 账户、容器、工作区和关联目标,获取容器安装代码
- 读取、创建、更新和删除代码、触发器、变量、文件夹与内置变量
- 管理版本、环境、用户权限,以及客户端、转换、区域、模板、gtag 配置等服务端资源
- 审计工作区中的分析配置问题,并将工作区导出为结构化 JSON
- 查询 GA4 Admin 设置,并运行 GA4 Data API 报表(含实时报表)
- 适用场景
- 适合让助手检查或维护 Google Tag Manager 配置并与 GA4 报表相互核对,例如审计容器、比对已配置事件与实际上报数据,或在受控条件下修改代码和触发器。
- 运行要求
- 以 npm 包形式通过 stdio 在本机运行(README 要求 Node.js 18 或更高版本)。需要启用 Tag Manager、Analytics Admin 和 Analytics Data API 的 Google Cloud 项目、一个 Google OAuth 桌面客户端,以及 GOOGLE_OAUTH_CLIENT_ID 和 GOOGLE_OAUTH_CLIENT_SECRET;需通过安装脚本完成一次 OAuth 登录。README 中的桌面应用还会要求填写 LLM API 密钥。
安装
在 SourceWeft 中
- 打开 控制台中的 Samarth Gtm Mcp,将其添加到工作区。
- 为需要使用其工具的对话启用该服务。
Desktop only,通过 STDIO。 STDIO 服务会启动本地进程,因此需要 SourceWeft 桌面宿主。
其他 MCP 客户端
参照 仓库 中的启动说明。
README
Samarth Analytics MCP
An open-source Model Context Protocol (MCP) server that lets AI assistants such as Claude Desktop, Claude Code and Cursor work with Google Tag Manager and GA4. It covers the full GTM API v2 surface (100+ tools, including server-side containers), the GA4 Admin and Data APIs, a built-in implementation audit, and a second server that crawls a website to check its tags and Consent Mode v2 setup. Built by Samarth Analytics for our own client work and released under the MIT license for the analytics community.
Read-only by default. Creating, updating, publishing and deleting are each behind a separate environment flag, every write also requires confirm=true, and a dry-run mode simulates writes without touching the API. See Guardrails.
Use it at your own risk, and start on a dummy container. The server acts with your Google credentials, so every change it makes is yours. Try it first on a sandbox GTM container and a test GA4 property, keep the write flags off until you have watched how it behaves, and review the container's version history after any write session. We run it in production, but your setup is not ours.
Three ways to use it
The repo also ships Samarth Desktop, a local Electron app with a chat UI that embeds this server (Quick Start), and a browser-based customer portal in apps/portal/ that runs live, read-only QC audits.
Contributions are welcome. Bug reports with a reproducible container setup are the most useful thing you can send. Read CONTRIBUTING.md first; CI runs on every pull request.
Table of Contents
- Features
- Quick Start
- Google Cloud OAuth Setup
- Service Account Limitations
- Environment Variables Reference
- Guardrails
- Available Tools
- Cloud Deployment
- Security Notes
- Development
- Releases
- Troubleshooting
Features
- Full GTM API v2 surface — accounts, containers, workspaces, tags, triggers, variables, folders, built-in variables, versions, sync, publish, preview
- Server-side & advanced GTM coverage — environments, user permissions, destinations, clients, transformations, zones, custom templates, gtag config, plus container snippet/lookup/combine/move-tag-id and workspace change-diff status
- GA4 coverage — GA4 Admin tools (
ga4_*) plus GA4 Data API reporting (ga4_run_report,ga4_run_realtime_report) for intent-vs-reality reconciliation. Reads and reporting need onlyanalytics.readonly; the GA4 Admin write tools are off by default behindGA4_MCP_ENABLE_WRITES/GA4_MCP_ENABLE_DELETESand additionally needanalytics.edit - Automatic pagination — every paginated list tool transparently follows
nextPageTokento return all results, with optionalmaxPages/pageTokenbounds - Retry with exponential backoff + jitter — transient Google API failures (HTTP 408/429/5xx, network errors) on read requests are retried automatically; mutations are never auto-retried (tunable via
GTM_MCP_RETRY_*) - Two transport modes: stdio (local, for Claude Desktop/Cursor) and Streamable HTTP (cloud/team)
- Guardrails by default: read-only unless explicitly enabled; publish and delete gated separately
- Dry-run mode: simulate all writes without touching the API
confirm=truerequired on all write/delete/publish operations- Audit tool: inspects workspace for common GA4/GTM implementation issues
- Export tool: full workspace dump as structured JSON
- Zod schema validation on all inputs
- Detailed Google API error messages surfaced to the MCP client
Quick Start
The way to run Samarth is the desktop app - a local Electron app with a chat UI that embeds the MCP server in-process. Multi-account Google sign-in, per-account LLM keys (OpenAI / Anthropic / Gemini), secrets in the OS keychain. Nothing to configure by hand: the Google OAuth client and your LLM key are entered in the app on first run.
You need: Node.js 18 or newer, Git, and a free Google "Desktop app" OAuth client - two values you create once in your Google Cloud project (exact click-by-click steps).
The window opens; paste your OAuth client ID + secret and an LLM API key when asked, sign in to Google, and start chatting with your GTM / GA4 setup.
Prefer a config file over typing in the app? Put the OAuth client in a
.env file instead - the app reads it on launch (values typed in the app and
real shell variables always take precedence):
Save it as apps/desktop/.env or at the repo root (already gitignored - never
commit it). A repo-root .env using the server's GOOGLE_OAUTH_CLIENT_ID /
GOOGLE_OAUTH_CLIENT_SECRET names works too, so one file can serve both the
app and the MCP server. A packaged install reads .env from its data
directory instead (%APPDATA% on Windows).
Your everyday launch afterwards is just:
Full guide - Windows/macOS specifics, first-run setup, building a real
.exe/.dmg installer, and the Error: Electron uninstall fix:
apps/desktop/INSTALL.md.
Google Cloud OAuth Setup
Step 1: Enable the GTM API
- Go to Google Cloud Console
- Select or create a project
- Navigate to APIs & Services → Library
- Search for "Tag Manager API" and click Enable
- Search for "Google Analytics Admin API" and click Enable (required for the read-only
ga4_*Admin tools) - Search for "Google Analytics Data API" and click Enable (required for
ga4_run_report/ga4_run_realtime_report)
Step 2: Create OAuth 2.0 Credentials
- Go to APIs & Services → Credentials
- Click Create Credentials → OAuth 2.0 Client ID
- Choose application type:
- Desktop app — simplest for local stdio use (no redirect URI needed)
- Web application — for the HTTP server (add your redirect URI)
- Download the JSON or copy the Client ID and Client Secret
- Add to
.env:
Step 3: Configure OAuth Consent Screen
- Go to APIs & Services → OAuth consent screen
- Choose External (or Internal if you have Google Workspace)
- Fill in App name, support email
- Add scopes:
https://www.googleapis.com/auth/tagmanager.readonlyhttps://www.googleapis.com/auth/tagmanager.edit.containershttps://www.googleapis.com/auth/tagmanager.edit.containerversionshttps://www.googleapis.com/auth/tagmanager.manage.accountshttps://www.googleapis.com/auth/tagmanager.manage.usershttps://www.googleapis.com/auth/tagmanager.publishhttps://www.googleapis.com/auth/analytics.readonly(read-only GA4 Admin and Data API tools)https://www.googleapis.com/auth/analytics.edit(GA4 Admin write tools — gated byGA4_MCP_ENABLE_WRITES)https://www.googleapis.com/auth/analytics.manage.users(GA4 access-binding write tools)
- Add your Google account as a test user (while the app is in "testing" mode)
Note: For personal/agency use, keeping the app in "Testing" mode is fine. You will need to re-authorize every 7 days unless you publish the app or get it verified.
Step 4: Run OAuth Setup
Or, if you prefer the older paste-the-code helper:
Service Account Limitations
Short version: Service accounts do NOT work with GTM by default. Use OAuth 2.0.
The Google Tag Manager API is a user-data API — it manages resources owned by individual Google accounts. Service accounts are not Google users and are not automatically granted access to GTM containers.
Option A: Add the service account as a GTM user (simplest)
If you still want to use a service account:
- Get the service account email (e.g.,
[email protected]) - In GTM, go to Admin → User Management at the account or container level
- Add the service account email with the appropriate role (Read, Edit, Approve, Publish)
- Set
GOOGLE_SERVICE_ACCOUNT_KEY_FILE=/path/to/key.jsonin.env
Caveats: This only works if the GTM container is associated with a Google account, not a Google Workspace that restricts external sharing.
Option B: Domain-Wide Delegation (Google Workspace only)
For Google Workspace organizations:
- Create a service account with a JSON key
- Enable Domain-Wide Delegation on the service account in Google Cloud Console
- In Google Workspace Admin Console → Security → API Controls → Domain-wide Delegation:
- Add the service account client ID
- Add scopes:
https://www.googleapis.com/auth/tagmanager.edit.containers(and others as needed)
- In
.env, set: - The server will impersonate the user automatically if you set a subject in
buildGoogleAuth()
Caveats: Requires a paid Google Workspace account. Only available for your own domain.
Environment Variables Reference
Guardrails
The server enforces three independent guardrails in addition to the confirm=true requirement:
confirm=true is always required on write/delete/publish tools regardless of env settings. This prevents accidental modifications even when guardrails are enabled.
Recommended Configurations
Read-only exploration (default — safe for sharing with team):
Development workspace edits (no publishing):
Full access (use with care):
Available Tools
Accounts
Containers
Destinations
Workspaces
Tags
Triggers
Variables
Folders
Built-In Variables
Versions
Environments
User Permissions (account-level)
Server-Side & Advanced Container Resources
These are workspace-scoped resources from GTM API v2. Create/update accept the full
resource as a JSON string (bodyJson) since their bodies are deeply nested. Each
supports *_list (auto-paginated), *_get, *_create ✏️, *_update ✏️, *_delete 🗑️,
and (except gtag_config) *_revert ✏️.
Analytics & Export
GA4 Admin (read-only)
Read-only wrappers over the Google Analytics Admin API (v1beta, with a single
v1alpha call for enhanced measurement). These never write, update, or delete GA4
resources and require no confirm flag. They power the senior audit framework's
GA4_ADMIN checks (custom dimensions/metrics, data streams & measurement IDs, data
retention, enhanced measurement, key events, Google Ads links).
Requires the https://www.googleapis.com/auth/analytics.readonly scope and the
Google Analytics Admin API enabled in your Google Cloud project. A 403 mentioning
scope means you should re-run npm run auth:google.
Accepts either a bare numeric ID (123456789) or the fully-qualified form
(properties/123456789, accounts/123456) wherever a property/account is required.
Documented limitations (not exposed by the GA4 Admin API v1beta, so intentionally not implemented rather than faked):
- Internal-traffic / unwanted-referral data filters — no public
dataFilterscollection; configured per data stream. - Referral exclusions — no dedicated Admin API resource.
- Channel groups and audiences — exist only on the v1alpha surface and are out of scope for this read-only v1beta set.
GA4 Data API (read-only reporting)
Read-only wrappers over the Google Analytics Data API (v1beta). They never
write and require no confirm flag. Use them to reconcile intent vs. reality —
comparing the events a container is configured to send against the events GA4
actually reports (zero reported activity for a configured event is a red flag).
These use the same https://www.googleapis.com/auth/analytics.readonly scope
as the GA4 Admin tools, so no extra consent is needed. Enable the Google
Analytics Data API in your Google Cloud project.
Documented gaps (intentionally not exposed rather than faked): pivot reports, cohorts, and funnels.
Pagination
All list tools backed by paginated GTM endpoints (accounts_*-scoped containers,
workspaces, tags, triggers, variables, folders, folder entities, environments,
user permissions, clients, transformations, zones, templates, gtag configs)
auto-follow pagination and return all results by default. Optional arguments:
maxPages— cap the number of API pages fetched (default 50). If more pages remain, the response includes"truncated": trueand anextPageToken.pageToken— resume from a previous truncated result.
Non-truncated responses keep the original { <key>: [...], count } shape unchanged.
Two tools differ, because one list key does not describe what they return:
folders_entitiesreturns three parallel collections (tag,trigger,variable, always present, empty when the folder has none) plus acountsobject, and addstruncated/nextPageTokenonly when the page ceiling was hit.export_containerpages five collections independently, so it takesmaxPages(applied per collection) but nopageToken. A short export is markedincomplete: truewithtruncatedCollections, per-collectionnextPageTokensand awarning— in every format, including the defaultsummary.
Legend: ✏️ requires GTM_MCP_ENABLE_WRITES=true | 🗑️ requires GTM_MCP_ENABLE_DELETES=true | 🚀 requires GTM_MCP_ENABLE_PUBLISH=true
All ✏️ 🗑️ 🚀 tools also require confirm: true in the tool arguments.
Cloud Deployment
Transport
For cloud deployments, use GTM_MCP_TRANSPORT=http. The server exposes:
POST /mcp— Streamable HTTP MCP endpointGET /mcp— SSE stream for existing sessionsDELETE /mcp— Session terminationGET /health— Health check
There is no /oauth/callback route on this server. npm run auth:google runs its own short-lived listener on 127.0.0.1:3001 for the redirect; an unauthenticated callback on the hosted transport could overwrite the server's stored Google credentials, so it was removed.
Connecting Remote Clients
Clients that support Streamable HTTP can connect directly to the /mcp endpoint. For clients that only support stdio (like Claude Desktop), use mcp-remote as a proxy:
Vercel
Limitation: Vercel Serverless Functions have a 10-second timeout (hobby) / 60-second (pro). Stateful SSE sessions require persistent connections which Vercel does not support well. Use Vercel only for stateless MCP interactions. Recommended alternative: Vercel + external session store (Redis/Upstash), or use Render/Fly.io instead.
For Vercel, export the Express app as a serverless handler:
Set env vars in Vercel Dashboard → Settings → Environment Variables.
Render
- Create a new Web Service in Render
- Connect your GitHub repo
- Build command:
npm install && npm run build - Start command:
GTM_MCP_TRANSPORT=http node dist/index.js - Add environment variables in Render Dashboard
- Important: Set
RENDER=trueenv var and ensure your health check hits/health
Render supports persistent long-lived connections — recommended for SSE/streaming.
Fly.io
Fly.io has no request timeout limitations and supports persistent WebSocket/SSE connections. Recommended for production.
Docker
Security Notes
-
Never commit
.env— it contains OAuth tokens..envis already in.gitignore. -
Rotate tokens regularly — OAuth refresh tokens are long-lived but can be revoked. Revoke at myaccount.google.com/permissions.
-
Minimum scopes — If you only need read access, revoke write scopes by removing them from the OAuth consent screen and re-authorizing. The server reads fine with
tagmanager.readonlyonly. -
Cloud deployment: Store secrets in your platform's secret manager (Render Secrets, Fly.io Secrets, Vercel Env Vars), never in code or Docker images.
-
HTTP transport:
/mcphas two built-in auth modes —GTM_MCP_HTTP_AUTH_TOKEN(one shared bearer token, identifies the deployment) andSTYTCH_PROJECT_ID(per-user OAuth, each request resolved to that user's own Google grant). With neither set the transport refuses to start;GTM_MCP_HTTP_ALLOW_UNAUTHENTICATED=trueoverrides that for local development and binds loopback only. -
Publish guard: Keep
GTM_MCP_ENABLE_PUBLISH=falseunless you explicitly intend to publish from an AI client. Publishing incorrect tags to production is the highest-risk operation. -
Audit logs: The server logs all session events to stderr. Pipe to a logging service in production.
Development
Project Structure
Releases
Releases are fully automated via semantic-release and GitHub Actions. Every push to main triggers the release.yml workflow, which:
- Installs dependencies, type-checks, builds, and runs tests.
- Inspects commits since the last tag using the Conventional Commits spec.
- Determines the next semantic version (
MAJOR.MINOR.PATCH). - Updates
CHANGELOG.mdand bumps theversioninpackage.json/package-lock.json. - Commits those files back to
mainwithchore(release): x.y.z [skip ci](the[skip ci]marker prevents an infinite release loop). - Publishes the package to npm as
samarth-gtm-mcpwith a provenance attestation. - Creates a Git tag (
vX.Y.Z) and a GitHub Release with auto-generated notes.
npm publishing uses Trusted Publishing: the job's GitHub OIDC token is exchanged for a short-lived npm token, so there is no npm token secret to rotate. The trusted publisher is configured on npmjs.com (GitHub Actions, this repository, workflow release.yml, no environment). Because main is protected, the release commit is pushed with a RELEASE_TOKEN secret (a fine-grained token of a repo admin with Contents, Issues and Pull requests read/write).
Conventional Commit Examples
Commit messages drive the version bump:
Breaking change examples
or:
Dry run locally
To preview what the next release would look like without publishing:
Manual release skip
To intentionally land a commit without triggering a release, use a non-releasing type (chore:, docs:, etc.) or append [skip ci] to the commit subject.
Troubleshooting
"The caller does not have permission" (403)
- Your Google account may not have access to this GTM account/container
- Service account not added to GTM — see Service Account Limitations
- Check your OAuth scopes on the consent screen
"invalid_grant" or "Token has been expired or revoked"
- Re-run
npm run auth:googleto refresh the token file - Or set
GOOGLE_REFRESH_TOKENdirectly in.envif you prefer env-managed tokens - If you're stuck in a loop where Google won't return a
refresh_token, revoke prior access at myaccount.google.com/permissions and re-run the auth script
"Write operations are disabled"
- Set
GTM_MCP_ENABLE_WRITES=truein your.env - Restart the server / the desktop app
Stdio server shows no output
- The stdio server intentionally writes nothing to stdout (stdout is the JSON-RPC channel)
- Diagnostic output goes to stderr — check your terminal or Claude Desktop logs
Desktop app: Error: Electron uninstall on npm run dev
- The Electron binary downloaded but never finished extracting - see the reliable re-extract fix in apps/desktop/INSTALL.md
TypeScript errors on googleapis types
- Run
npm installto ensure all deps are installed - The
googleapispackage ships its own types — no@types/googleapisneeded
TODOs / Known Limitations
workspace_resolve_conflict: The GTM API's resolve_conflict endpoint accepts a full entity body — the exact request body schema is complex. The current implementation passes through the user-supplied JSON; validate it against the entity type before calling.containers_create: TheusageContextenum values may differ slightly by GTM region/version. Refer to the GTM API docs for the latest allowed values.- Single-identity HTTP auth is a shared secret:
GTM_MCP_HTTP_AUTH_TOKENgates/mcpwith one bearer token for every client, so it identifies the deployment, not the caller. For per-user identity, setSTYTCH_PROJECT_IDto enable multi-user mode — see Security Notes. - HTTP sessions are in-memory: sessions live in the server process, so horizontal scaling requires sticky sessions. Fine for a single team instance; not yet built for multi-instance load balancing.
- Single OAuth identity per deployment — single-identity mode only: without
STYTCH_PROJECT_ID, all requests share one Google identity and therefore one Google API quota pool. Heavy multi-user load through one deployment will exhaust it; retries with backoff soften this but don't remove the quota ceiling. Multi-user mode sidesteps it — each member uses their own Google grant and quota.
Built by Samarth Analytics — Swapnil Jaykar & Sarthak Mandage
来源:README.md,提交 135d609
工具
0版本历史
1- v1.19.0最新Sep 16, 2026
评分
已满足适用检查项的 50%
该评分衡量此收录条目的完整程度,依据注册中心条目、端点与公开来源计算得出。它不是对服务器本身的评价,也不表示服务器安全或当前可用:可连通性是带日期的检查结果,评分也不包含安装量或用户评价。
- 近 30 天内可连通25 分
请保持端点能够响应 MCP 握手;SourceWeft 每 30 天探测一次。
- 已声明认证方式10 分
请在注册中心条目中声明凭据请求头,或保持端点能够响应探测,以便判定其认证方式。
- 已列出工具15 分
请让服务器在无凭据时响应 tools/list,或发布可在沙箱中无凭据启动的软件包。
- 描述必需15 分
- 图标10 分
- 文档15 分
- 许可证10 分