mcp-google-tagmanager 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 A1 x Tech
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,222 @@
1
+ # Google Tag Manager MCP
2
+
3
+ [![npm](https://img.shields.io/npm/v/mcp-google-tagmanager)](https://www.npmjs.com/package/mcp-google-tagmanager)
4
+ [![CI](https://github.com/A1-x-Tech/mcp-google-tagmanager/actions/workflows/ci.yml/badge.svg)](https://github.com/A1-x-Tech/mcp-google-tagmanager/actions/workflows/ci.yml)
5
+ [![Glama](https://glama.ai/mcp/servers/A1-x-Tech/mcp-google-tagmanager/badges/score.svg)](https://glama.ai/mcp/servers/A1-x-Tech/mcp-google-tagmanager)
6
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
7
+
8
+ MCP server for the **Google Tag Manager API v2**: manage containers, workspaces, tags,
9
+ triggers, variables and publishing from Claude, Cursor, Codex and other AI clients in
10
+ natural language.
11
+
12
+ Ask the assistant to audit a container, wire up a new GA4 tag with its trigger, enable
13
+ built-in variables, compile a version and push it live — the full GTM workflow without
14
+ clicking through the web UI.
15
+
16
+ ## Quick start
17
+
18
+ 1. [Get OAuth credentials](#getting-credentials) for a Google Cloud project with the Tag Manager API enabled.
19
+ 2. Add the server — for example in Claude Code ([other clients](#installation)):
20
+
21
+ ```bash
22
+ claude mcp add google-tagmanager \
23
+ -e GOOGLE_TAGMANAGER_CLIENT_ID=your_client_id \
24
+ -e GOOGLE_TAGMANAGER_CLIENT_SECRET=your_client_secret \
25
+ -e GOOGLE_TAGMANAGER_REFRESH_TOKEN=your_refresh_token \
26
+ -- npx -y mcp-google-tagmanager
27
+ ```
28
+
29
+ 3. Ask the assistant: "List my GTM containers and show which tags fire on page view."
30
+
31
+ ## Tools
32
+
33
+ | Tool | Description |
34
+ |---|---|
35
+ | `list_accounts` | List all GTM accounts the user can access |
36
+ | `get_account` | Get one account |
37
+ | `list_containers` | List containers of an account (with `GTM-XXXXXX` public ids) |
38
+ | `get_container` | Get one container |
39
+ | `create_container` | Create a container (`web`, `server`, ...) |
40
+ | `list_workspaces` | List workspaces of a container |
41
+ | `get_workspace` | Get one workspace |
42
+ | `create_workspace` | Create a workspace (draft) |
43
+ | `list_tags` | List tags of a workspace |
44
+ | `list_triggers` | List triggers of a workspace |
45
+ | `list_variables` | List user-defined variables of a workspace |
46
+ | `get_resource` | Get any resource by its API path (tag, trigger, variable, version, ...) |
47
+ | `create_entity` | Create a tag, trigger or variable |
48
+ | `update_entity` | Update a tag/trigger/variable (PUT full replace, fingerprint-guarded) |
49
+ | `delete_entity` | Delete a tag/trigger/variable |
50
+ | `manage_built_in_variables` | List / enable / disable built-in variables (full enum from the discovery doc) |
51
+ | `create_version` | Compile a workspace into a container version (⚠️ deletes the workspace) |
52
+ | `publish_version` | Publish a version, get one version, or fetch the live version |
53
+ | `raw_request` | Escape hatch: call any Tag Manager API v2 path directly |
54
+
55
+ ## Built-in rate limiting
56
+
57
+ The Tag Manager API quota is unusually strict: **0.25 QPS per project** (25 requests per
58
+ 100-second sliding window) and 10,000 requests per day. The server handles this for you:
59
+
60
+ - every API request goes through a serialized queue with a minimum spacing of
61
+ **4.2 s** between requests (tunable via `GOOGLE_TAGMANAGER_MIN_INTERVAL_MS`);
62
+ - `429` and quota-`403` (`rateLimitExceeded` / `userRateLimitExceeded` / `quotaExceeded`)
63
+ responses are retried with exponential backoff honoring `Retry-After`;
64
+ - `5xx` and network errors are retried for reads only — a write that may have committed
65
+ is never replayed.
66
+
67
+ Big fan-out requests ("list everything in every container") will therefore be slow by
68
+ design — that is the quota, not the server.
69
+
70
+ ## Example prompts
71
+
72
+ - "Which tags in container GTM-ABC123 fire on the page-view trigger?"
73
+ - "Create a Custom HTML tag in the default workspace that logs to the console, firing on all pages."
74
+ - "Enable the clickText and clickClasses built-in variables in my workspace."
75
+ - "Compile my workspace into a version named 'March release' and publish it."
76
+
77
+ ## Installation
78
+
79
+ <details open>
80
+ <summary><b>Claude Code</b></summary>
81
+
82
+ ```bash
83
+ claude mcp add google-tagmanager \
84
+ -e GOOGLE_TAGMANAGER_CLIENT_ID=your_client_id \
85
+ -e GOOGLE_TAGMANAGER_CLIENT_SECRET=your_client_secret \
86
+ -e GOOGLE_TAGMANAGER_REFRESH_TOKEN=your_refresh_token \
87
+ -- npx -y mcp-google-tagmanager
88
+ ```
89
+
90
+ </details>
91
+
92
+ <details>
93
+ <summary><b>Claude Desktop</b></summary>
94
+
95
+ `claude_desktop_config.json` — macOS `~/Library/Application Support/Claude/`, Windows `%APPDATA%\Claude\`
96
+
97
+ ```json
98
+ {
99
+ "mcpServers": {
100
+ "google-tagmanager": {
101
+ "command": "npx",
102
+ "args": ["-y", "mcp-google-tagmanager"],
103
+ "env": {
104
+ "GOOGLE_TAGMANAGER_CLIENT_ID": "your_client_id",
105
+ "GOOGLE_TAGMANAGER_CLIENT_SECRET": "your_client_secret",
106
+ "GOOGLE_TAGMANAGER_REFRESH_TOKEN": "your_refresh_token"
107
+ }
108
+ }
109
+ }
110
+ }
111
+ ```
112
+
113
+ </details>
114
+
115
+ <details>
116
+ <summary><b>Cursor</b></summary>
117
+
118
+ `~/.cursor/mcp.json` (or `.cursor/mcp.json` in the project)
119
+
120
+ ```json
121
+ {
122
+ "mcpServers": {
123
+ "google-tagmanager": {
124
+ "command": "npx",
125
+ "args": ["-y", "mcp-google-tagmanager"],
126
+ "env": {
127
+ "GOOGLE_TAGMANAGER_CLIENT_ID": "your_client_id",
128
+ "GOOGLE_TAGMANAGER_CLIENT_SECRET": "your_client_secret",
129
+ "GOOGLE_TAGMANAGER_REFRESH_TOKEN": "your_refresh_token"
130
+ }
131
+ }
132
+ }
133
+ }
134
+ ```
135
+
136
+ </details>
137
+
138
+ For a quick one-off session you can skip the trio and pass a short-lived token directly:
139
+ `GOOGLE_TAGMANAGER_ACCESS_TOKEN=ya29....` (Google access tokens expire after about an
140
+ hour and are not refreshed automatically).
141
+
142
+ ## Getting credentials
143
+
144
+ The Tag Manager API only supports OAuth 2.0 — there are no API keys for user data. One-time setup:
145
+
146
+ 1. **Create/pick a Google Cloud project** at [console.cloud.google.com](https://console.cloud.google.com)
147
+ and enable the **Tag Manager API** ([direct link](https://console.cloud.google.com/apis/library/tagmanager.googleapis.com)).
148
+ Without a registered project the API grants **zero quota** — this step is mandatory.
149
+ 2. **Configure the OAuth consent screen** (APIs & Services → OAuth consent screen).
150
+ For personal use, External + your account as a test user is enough.
151
+ 3. **Create an OAuth client** (APIs & Services → Credentials → Create credentials →
152
+ OAuth client ID → *Desktop app* or *Web application*). Save the **client id** and **client secret**.
153
+ 4. **Mint a refresh token.** The easiest path is the
154
+ [OAuth 2.0 Playground](https://developers.google.com/oauthplayground):
155
+ - gear icon → check *Use your own OAuth credentials* → paste the client id/secret
156
+ (for a Web client also add `https://developers.google.com/oauthplayground` to its
157
+ authorized redirect URIs);
158
+ - in Step 1 authorize these scopes (space-separated):
159
+
160
+ ```
161
+ https://www.googleapis.com/auth/tagmanager.readonly https://www.googleapis.com/auth/tagmanager.edit.containers https://www.googleapis.com/auth/tagmanager.edit.containerversions https://www.googleapis.com/auth/tagmanager.publish
162
+ ```
163
+
164
+ - in Step 2 click *Exchange authorization code for tokens* and copy the **refresh token**.
165
+ 5. Put the three values into the environment variables above. The server exchanges the
166
+ refresh token for access tokens automatically and caches them until just before expiry.
167
+
168
+ > ⚠️ The credentials are stored as plain text in your client's MCP config. Scope the OAuth
169
+ > consent to the four Tag Manager scopes above and nothing else.
170
+ >
171
+ > Note the scope split: reading needs `readonly`, editing needs `edit.containers`,
172
+ > `create_version` needs `edit.containerversions`, and publishing needs `publish`.
173
+ > Authorize all four at once or re-consent mid-flow.
174
+
175
+ ## Configuration
176
+
177
+ | Variable | Required | Default | Description |
178
+ |---|---|---|---|
179
+ | `GOOGLE_TAGMANAGER_CLIENT_ID` | yes* | — | OAuth client id |
180
+ | `GOOGLE_TAGMANAGER_CLIENT_SECRET` | yes* | — | OAuth client secret |
181
+ | `GOOGLE_TAGMANAGER_REFRESH_TOKEN` | yes* | — | OAuth refresh token |
182
+ | `GOOGLE_TAGMANAGER_ACCESS_TOKEN` | no | — | Ready-made access token; replaces the trio for quick sessions |
183
+ | `GOOGLE_TAGMANAGER_API_BASE` | no | `https://tagmanager.googleapis.com` | API root override |
184
+ | `GOOGLE_TAGMANAGER_TIMEOUT_MS` | no | `60000` | Per-request timeout |
185
+ | `GOOGLE_TAGMANAGER_MAX_RETRIES` | no | `3` | Retries on transient errors |
186
+ | `GOOGLE_TAGMANAGER_MIN_INTERVAL_MS` | no | `4200` | Minimum spacing between API requests (0.25 QPS quota) |
187
+
188
+ \* the trio is required unless `GOOGLE_TAGMANAGER_ACCESS_TOKEN` is set.
189
+
190
+ ## Good to know
191
+
192
+ - **`create_version` deletes the source workspace.** The response's `newWorkspacePath`
193
+ points to the automatically created replacement — the server surfaces it and the tool
194
+ description warns the model, but keep it in mind when scripting.
195
+ - **`compilerError: true` can arrive with HTTP 200** on `create_version` and publish.
196
+ The server converts it into a tool error so it is never mistaken for success.
197
+ - **Updates are full replacements** (PUT, not PATCH): `update_entity` expects the complete
198
+ resource. Fetch with `get_resource`, edit, send back, and pass the `fingerprint` for
199
+ optimistic-concurrency safety.
200
+ - **All ids are strings**, and every resource carries its own `path` field — echo it back
201
+ rather than assembling paths by hand.
202
+
203
+ ## Requirements
204
+
205
+ - Node.js >= 20
206
+ - A Google account with access to at least one GTM container
207
+
208
+ ## Documentation
209
+
210
+ - [docs/TOOLS.md](docs/TOOLS.md) — tool reference
211
+ - [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md) — architecture and dev commands
212
+ - [docs/PUBLISHING.md](docs/PUBLISHING.md) — release checklist
213
+ - [Google Tag Manager API v2 reference](https://developers.google.com/tag-platform/tag-manager/api/reference/rest)
214
+
215
+ ## Support
216
+
217
+ Questions and issues → [GitHub Issues](https://github.com/A1-x-Tech/mcp-google-tagmanager/issues)
218
+ or Telegram [@gistrec](https://t.me/gistrec).
219
+
220
+ ## License
221
+
222
+ [MIT](./LICENSE)
package/dist/auth.js ADDED
@@ -0,0 +1,86 @@
1
+ import { TagManagerError } from "./types.js";
2
+ /** Google OAuth 2.0 token endpoint. */
3
+ const TOKEN_URL = "https://oauth2.googleapis.com/token";
4
+ /**
5
+ * Refresh the access token this many milliseconds before its reported expiry,
6
+ * so a token never goes stale mid-request.
7
+ */
8
+ const EXPIRY_MARGIN_MS = 60_000;
9
+ /** Fallback lifetime when the token response has no usable expires_in. */
10
+ const DEFAULT_LIFETIME_S = 3600;
11
+ /**
12
+ * Supplies OAuth access tokens for API requests.
13
+ *
14
+ * With GOOGLE_TAGMANAGER_ACCESS_TOKEN set, that token is returned as-is (quick
15
+ * sessions; Google access tokens expire in ~1 hour and are not auto-refreshed).
16
+ * Otherwise the client-id/secret/refresh-token trio is exchanged at
17
+ * https://oauth2.googleapis.com/token (form-urlencoded, grant_type=refresh_token)
18
+ * and the resulting access token is cached until 60 s before expiry. Concurrent
19
+ * callers share one in-flight exchange; a failed exchange is not cached.
20
+ *
21
+ * Token-endpoint calls do not count against the GTM API quota, so they bypass
22
+ * the client's rate limiter.
23
+ */
24
+ export class TokenProvider {
25
+ config;
26
+ cachedToken;
27
+ cachedUntil = 0;
28
+ pending;
29
+ constructor(config) {
30
+ this.config = config;
31
+ }
32
+ async getAccessToken() {
33
+ if (this.config.accessToken)
34
+ return this.config.accessToken;
35
+ if (this.cachedToken && Date.now() < this.cachedUntil)
36
+ return this.cachedToken;
37
+ if (!this.pending) {
38
+ this.pending = this.refresh().finally(() => {
39
+ this.pending = undefined;
40
+ });
41
+ }
42
+ return this.pending;
43
+ }
44
+ async refresh() {
45
+ const { clientId, clientSecret, refreshToken } = this.config;
46
+ if (!clientId || !clientSecret || !refreshToken) {
47
+ // loadConfig guarantees the trio when accessToken is absent; this guards direct construction.
48
+ throw new Error("OAuth refresh requires GOOGLE_TAGMANAGER_CLIENT_ID, GOOGLE_TAGMANAGER_CLIENT_SECRET and GOOGLE_TAGMANAGER_REFRESH_TOKEN.");
49
+ }
50
+ const body = new URLSearchParams({
51
+ client_id: clientId,
52
+ client_secret: clientSecret,
53
+ refresh_token: refreshToken,
54
+ grant_type: "refresh_token",
55
+ });
56
+ const timeoutMs = this.config.timeoutMs ?? 60_000;
57
+ const res = await fetch(TOKEN_URL, {
58
+ method: "POST",
59
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
60
+ body: body.toString(),
61
+ signal: AbortSignal.timeout(timeoutMs),
62
+ });
63
+ const text = await res.text();
64
+ let data = undefined;
65
+ if (text) {
66
+ try {
67
+ data = JSON.parse(text);
68
+ }
69
+ catch {
70
+ data = text;
71
+ }
72
+ }
73
+ if (!res.ok)
74
+ throw new TagManagerError(res.status, data);
75
+ const record = (data ?? {});
76
+ const token = record.access_token;
77
+ if (typeof token !== "string" || !token) {
78
+ throw new Error("OAuth token response contained no access_token.");
79
+ }
80
+ const expiresIn = Number(record.expires_in);
81
+ const lifetimeMs = (Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : DEFAULT_LIFETIME_S) * 1000;
82
+ this.cachedToken = token;
83
+ this.cachedUntil = Date.now() + lifetimeMs - EXPIRY_MARGIN_MS;
84
+ return token;
85
+ }
86
+ }
@@ -0,0 +1,126 @@
1
+ /**
2
+ * The full BuiltInVariableType enum, generated from the Google Tag Manager API v2
3
+ * discovery document (https://www.googleapis.com/discovery/v1/apis/tagmanager/v2/rest,
4
+ * revision 20260805). `builtInVariableTypeUnspecified` is excluded: it is a
5
+ * protobuf placeholder, not a variable a workspace can enable.
6
+ *
7
+ * Do not edit by hand — refresh from the discovery document when Google adds values.
8
+ */
9
+ export const BUILT_IN_VARIABLE_TYPES = [
10
+ "pageUrl",
11
+ "pageHostname",
12
+ "pagePath",
13
+ "referrer",
14
+ "event",
15
+ "clickElement",
16
+ "clickClasses",
17
+ "clickId",
18
+ "clickTarget",
19
+ "clickUrl",
20
+ "clickText",
21
+ "firstPartyServingUrl",
22
+ "formElement",
23
+ "formClasses",
24
+ "formId",
25
+ "formTarget",
26
+ "formUrl",
27
+ "formText",
28
+ "errorMessage",
29
+ "errorUrl",
30
+ "errorLine",
31
+ "newHistoryUrl",
32
+ "oldHistoryUrl",
33
+ "newHistoryFragment",
34
+ "oldHistoryFragment",
35
+ "newHistoryState",
36
+ "oldHistoryState",
37
+ "historySource",
38
+ "containerVersion",
39
+ "debugMode",
40
+ "randomNumber",
41
+ "containerId",
42
+ "appId",
43
+ "appName",
44
+ "appVersionCode",
45
+ "appVersionName",
46
+ "language",
47
+ "osVersion",
48
+ "platform",
49
+ "sdkVersion",
50
+ "deviceName",
51
+ "resolution",
52
+ "advertiserId",
53
+ "advertisingTrackingEnabled",
54
+ "htmlId",
55
+ "environmentName",
56
+ "ampBrowserLanguage",
57
+ "ampCanonicalPath",
58
+ "ampCanonicalUrl",
59
+ "ampCanonicalHost",
60
+ "ampReferrer",
61
+ "ampTitle",
62
+ "ampClientId",
63
+ "ampClientTimezone",
64
+ "ampClientTimestamp",
65
+ "ampClientScreenWidth",
66
+ "ampClientScreenHeight",
67
+ "ampClientScrollX",
68
+ "ampClientScrollY",
69
+ "ampClientMaxScrollX",
70
+ "ampClientMaxScrollY",
71
+ "ampTotalEngagedTime",
72
+ "ampPageViewId",
73
+ "ampPageLoadTime",
74
+ "ampPageDownloadTime",
75
+ "ampGtmEvent",
76
+ "eventName",
77
+ "firebaseEventParameterCampaign",
78
+ "firebaseEventParameterCampaignAclid",
79
+ "firebaseEventParameterCampaignAnid",
80
+ "firebaseEventParameterCampaignClickTimestamp",
81
+ "firebaseEventParameterCampaignContent",
82
+ "firebaseEventParameterCampaignCp1",
83
+ "firebaseEventParameterCampaignGclid",
84
+ "firebaseEventParameterCampaignSource",
85
+ "firebaseEventParameterCampaignTerm",
86
+ "firebaseEventParameterCurrency",
87
+ "firebaseEventParameterDynamicLinkAcceptTime",
88
+ "firebaseEventParameterDynamicLinkLinkid",
89
+ "firebaseEventParameterNotificationMessageDeviceTime",
90
+ "firebaseEventParameterNotificationMessageId",
91
+ "firebaseEventParameterNotificationMessageName",
92
+ "firebaseEventParameterNotificationMessageTime",
93
+ "firebaseEventParameterNotificationTopic",
94
+ "firebaseEventParameterPreviousAppVersion",
95
+ "firebaseEventParameterPreviousOsVersion",
96
+ "firebaseEventParameterPrice",
97
+ "firebaseEventParameterProductId",
98
+ "firebaseEventParameterQuantity",
99
+ "firebaseEventParameterValue",
100
+ "videoProvider",
101
+ "videoUrl",
102
+ "videoTitle",
103
+ "videoDuration",
104
+ "videoPercent",
105
+ "videoVisible",
106
+ "videoStatus",
107
+ "videoCurrentTime",
108
+ "scrollDepthThreshold",
109
+ "scrollDepthUnits",
110
+ "scrollDepthDirection",
111
+ "elementVisibilityRatio",
112
+ "elementVisibilityTime",
113
+ "elementVisibilityFirstTime",
114
+ "elementVisibilityRecentTime",
115
+ "requestPath",
116
+ "requestMethod",
117
+ "clientName",
118
+ "queryString",
119
+ "serverPageLocationUrl",
120
+ "serverPageLocationPath",
121
+ "serverPageLocationHostname",
122
+ "visitorRegion",
123
+ "analyticsClientId",
124
+ "analyticsSessionId",
125
+ "analyticsSessionNumber",
126
+ ];