mcp-google-tagmanager 0.1.2 → 1.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/README.md CHANGED
@@ -1,98 +1,130 @@
1
- # Google Tag Manager MCP
1
+ # <img src="./assets/a1-logo.svg" alt="A1" width="40"> Google Tag Manager MCP
2
+
3
+ **English** | [Русский](./README.ru.md)
2
4
 
3
5
  [![npm](https://img.shields.io/npm/v/mcp-google-tagmanager)](https://www.npmjs.com/package/mcp-google-tagmanager)
4
6
  [![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
7
  [![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
8
  [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
7
9
 
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.
10
+ **A1 Google Tag Manager MCP** lets an AI app inspect and manage Google Tag Manager containers in plain language. See what fires on a page, work with tags, triggers and variables in a draft workspace, then deliberately compile and publish a version when you are ready.
11
+
12
+ It connects to the Google Tag Manager API v2 through your Google account. The difference from asking an AI to guess a GTM setup is that it works with the actual container, workspace and version you choose.
13
+
14
+ - **19 tools.** 10 operations only read GTM data; 4 create drafts or change built-in variables; 5 can alter, delete, compile or publish live configuration.
15
+ - **Draft first.** Tags, triggers and variables are created in a workspace. Publishing is a separate, explicitly destructive operation.
16
+ - **Quota-aware.** GTM permits 0.25 requests per second per project; the server spaces requests by at least 4.2 seconds instead of overwhelming the API.
17
+ - **Your Google access.** The server uses your OAuth credentials and requests only the Tag Manager scopes needed for reading, editing, versioning and publishing.
18
+
19
+ Start with a read-only question:
20
+
21
+ > Which tags in my containers fire on the page-view trigger?
22
+
23
+ [Connect the server](#quick-start) · [Explore use cases](#what-you-can-ask-it-to-do) · [Open technical documentation](#technical-documentation)
24
+
25
+ ---
26
+
27
+ ## See it work in a minute
28
+
29
+ > **You:** List my GTM containers and show which tags fire on page view.
30
+ >
31
+ > **Assistant:** Lists the containers, their workspaces, relevant triggers and the tags attached to them. Nothing changes.
32
+ >
33
+ > **You:** In the Default Workspace of `GTM-ABC123`, prepare a GA4 configuration tag for measurement ID `G-XXXXXXX` on all pages.
34
+ >
35
+ > **Assistant:** Shows the workspace, proposed tag and trigger configuration, then asks for confirmation before creating the draft.
36
+ >
37
+ > **You:** Confirm the draft.
38
+ >
39
+ > **Assistant:** Creates the tag in the workspace. It does not publish the container; compiling and publishing a version remains a separate step.
40
+
41
+ ## Contents
11
42
 
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.
43
+ - [Quick start](#quick-start)
44
+ - [What you can ask it to do](#what-you-can-ask-it-to-do)
45
+ - [How GTM changes are connected](#how-gtm-changes-are-connected)
46
+ - [What can change](#what-can-change)
47
+ - [Getting access](#getting-access)
48
+ - [Configuration](#configuration)
49
+ - [Data and telemetry](#data-and-telemetry)
50
+ - [Limits and background work](#limits-and-background-work)
51
+ - [Technical documentation](#technical-documentation)
52
+ - [Support](#support)
15
53
 
16
54
  ## Quick start
17
55
 
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)):
56
+ You need Node.js 20+, a Google account with access to a GTM container and OAuth credentials from a Google Cloud project where the Tag Manager API is enabled.
20
57
 
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@latest
27
- ```
58
+ 1. [Prepare Google OAuth access](#getting-access).
59
+ 2. Add the server to your AI app.
60
+ 3. Start with the read-only question above.
61
+
62
+ <details open>
63
+ <summary><strong>Codex</strong></summary>
28
64
 
29
- 3. Ask the assistant: "List my GTM containers and show which tags fire on page view."
65
+ <br>
30
66
 
31
- ## Tools
67
+ **In the app:**
32
68
 
33
- | Tool | Description |
69
+ 1. Open **Settings → Plugins → MCP servers**.
70
+ 2. Select **Add server**.
71
+ 3. Add `npx -y mcp-google-tagmanager@latest` and the three environment variables below.
72
+
73
+ | Variable | Value |
34
74
  |---|---|
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
75
+ | `GOOGLE_TAGMANAGER_CLIENT_ID` | Your Google OAuth client ID |
76
+ | `GOOGLE_TAGMANAGER_CLIENT_SECRET` | Your Google OAuth client secret |
77
+ | `GOOGLE_TAGMANAGER_REFRESH_TOKEN` | Your Google OAuth refresh token |
78
78
 
79
- <details open>
80
- <summary><b>Claude Code</b></summary>
79
+ **From the command line:**
81
80
 
82
81
  ```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 \
82
+ codex mcp add google-tagmanager \
83
+ --env GOOGLE_TAGMANAGER_CLIENT_ID=your_client_id \
84
+ --env GOOGLE_TAGMANAGER_CLIENT_SECRET=your_client_secret \
85
+ --env GOOGLE_TAGMANAGER_REFRESH_TOKEN=your_refresh_token \
87
86
  -- npx -y mcp-google-tagmanager@latest
88
87
  ```
89
88
 
89
+ ```bash
90
+ codex mcp list
91
+ ```
92
+
93
+ [Codex MCP documentation](https://learn.chatgpt.com/docs/extend/mcp?surface=cli)
94
+
90
95
  </details>
91
96
 
92
97
  <details>
93
- <summary><b>Claude Desktop</b></summary>
98
+ <summary><strong>Claude Code</strong></summary>
94
99
 
95
- `claude_desktop_config.json` — macOS `~/Library/Application Support/Claude/`, Windows `%APPDATA%\Claude\`
100
+ <br>
101
+
102
+ ```bash
103
+ claude mcp add \
104
+ --env GOOGLE_TAGMANAGER_CLIENT_ID=your_client_id \
105
+ --env GOOGLE_TAGMANAGER_CLIENT_SECRET=your_client_secret \
106
+ --env GOOGLE_TAGMANAGER_REFRESH_TOKEN=your_refresh_token \
107
+ --transport stdio \
108
+ --scope user \
109
+ google-tagmanager \
110
+ -- npx -y mcp-google-tagmanager@latest
111
+ ```
112
+
113
+ ```bash
114
+ claude mcp list
115
+ ```
116
+
117
+ [Claude Code MCP documentation](https://code.claude.com/docs/en/mcp)
118
+
119
+ </details>
120
+
121
+ <details>
122
+ <summary><strong>Claude Desktop</strong></summary>
123
+
124
+ <br>
125
+
126
+ 1. Open **Settings → Developer → Edit Config**.
127
+ 2. Add this entry to `mcpServers`:
96
128
 
97
129
  ```json
98
130
  {
@@ -110,17 +142,24 @@ claude mcp add google-tagmanager \
110
142
  }
111
143
  ```
112
144
 
145
+ If **Edit Config** is unavailable, edit `~/Library/Application Support/Claude/claude_desktop_config.json` on macOS or `%APPDATA%\Claude\claude_desktop_config.json` on Windows.
146
+
147
+ [Claude Desktop MCP documentation](https://support.claude.com/en/articles/10949351-getting-started-with-local-mcp-servers-on-claude-desktop)
148
+
113
149
  </details>
114
150
 
115
151
  <details>
116
- <summary><b>Cursor</b></summary>
152
+ <summary><strong>Cursor</strong></summary>
153
+
154
+ <br>
117
155
 
118
- `~/.cursor/mcp.json` (or `.cursor/mcp.json` in the project)
156
+ Add a user-level server to `~/.cursor/mcp.json` on macOS/Linux or `%USERPROFILE%\.cursor\mcp.json` on Windows:
119
157
 
120
158
  ```json
121
159
  {
122
160
  "mcpServers": {
123
161
  "google-tagmanager": {
162
+ "type": "stdio",
124
163
  "command": "npx",
125
164
  "args": ["-y", "mcp-google-tagmanager@latest"],
126
165
  "env": {
@@ -133,90 +172,163 @@ claude mcp add google-tagmanager \
133
172
  }
134
173
  ```
135
174
 
175
+ [Cursor MCP documentation](https://cursor.com/docs/mcp)
176
+
136
177
  </details>
137
178
 
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.
179
+ <details>
180
+ <summary><strong>VS Code</strong></summary>
181
+
182
+ <br>
183
+
184
+ Run **MCP: Open User Configuration** from the Command Palette and add:
185
+
186
+ ```json
187
+ {
188
+ "servers": {
189
+ "google-tagmanager": {
190
+ "type": "stdio",
191
+ "command": "npx",
192
+ "args": ["-y", "mcp-google-tagmanager@latest"],
193
+ "env": {
194
+ "GOOGLE_TAGMANAGER_CLIENT_ID": "${input:gtm_client_id}",
195
+ "GOOGLE_TAGMANAGER_CLIENT_SECRET": "${input:gtm_client_secret}",
196
+ "GOOGLE_TAGMANAGER_REFRESH_TOKEN": "${input:gtm_refresh_token}"
197
+ }
198
+ }
199
+ },
200
+ "inputs": [
201
+ { "type": "promptString", "id": "gtm_client_id", "description": "Google OAuth client ID" },
202
+ { "type": "promptString", "id": "gtm_client_secret", "description": "Google OAuth client secret", "password": true },
203
+ { "type": "promptString", "id": "gtm_refresh_token", "description": "Google OAuth refresh token", "password": true }
204
+ ]
205
+ }
206
+ ```
207
+
208
+ Check it with **MCP: List Servers**.
209
+
210
+ [VS Code MCP documentation](https://code.visualstudio.com/docs/agent-customization/mcp-servers)
211
+
212
+ </details>
213
+
214
+ ## What you can ask it to do
215
+
216
+ ### Understand the current setup
217
+
218
+ - List the GTM accounts and containers I can access.
219
+ - Which tags fire on page view in this workspace?
220
+ - Show the trigger and variable configuration for this tag.
221
+ - Which built-in variables are enabled?
222
+
223
+ ### Prepare tracking changes in a draft
224
+
225
+ - Create a workspace for the checkout tracking change.
226
+ - Prepare a GA4 tag and a trigger for a specific event.
227
+ - Enable the click variables needed for this trigger.
228
+ - Update this tag after showing me the complete replacement configuration.
229
+
230
+ ### Release a version deliberately
231
+
232
+ - Compile this workspace into a version named `April release`.
233
+ - Show the compiler errors, if any.
234
+ - Publish version `42` after I confirm the version and its changes.
235
+
236
+ ## How GTM changes are connected
237
+
238
+ GTM has a clear release path:
239
+
240
+ 1. An **account** contains one or more **containers**.
241
+ 2. A container has **workspaces** for draft changes.
242
+ 3. Tags, triggers and variables belong to a workspace.
243
+ 4. Compiling a workspace creates a **container version** and removes the source workspace. GTM provides a replacement workspace.
244
+ 5. Publishing makes a selected container version live.
245
+
246
+ This server can inspect each step. It does not treat a draft as a release: version creation and publishing are separate operations.
247
+
248
+ ## What can change
249
+
250
+ | Operation | What happens | Confirmation boundary |
251
+ |---|---|---|
252
+ | List accounts, containers, workspaces, tags, triggers, variables and versions | Reads GTM configuration | No change |
253
+ | Create a container or workspace | Adds a new GTM object | Changes GTM |
254
+ | Create a tag, trigger or variable | Adds a draft object to a workspace | Changes a draft workspace |
255
+ | Enable or disable built-in variables | Changes the workspace configuration | Changes a draft workspace |
256
+ | Update a tag, trigger or variable | Replaces the complete resource, protected by its fingerprint | Potentially destructive |
257
+ | Delete a tag, trigger or variable | Removes the selected object | Destructive |
258
+ | Compile a workspace | Creates a version and deletes the source workspace | Destructive |
259
+ | Publish a version | Makes a selected version live | Destructive |
260
+ | Raw API request | Can call API methods without a dedicated tool | Potentially destructive |
261
+
262
+ The AI client decides how it asks for confirmation. The server marks read-only, write and destructive operations so the client can distinguish inspection from a real change.
263
+
264
+ ## Getting access
265
+
266
+ The server uses Google OAuth 2.0. Google Tag Manager does not provide API keys for this user data.
267
+
268
+ 1. Create or select a Google Cloud project and enable the [Tag Manager API](https://console.cloud.google.com/apis/library/tagmanager.googleapis.com). A project without that API enabled receives no quota.
269
+ 2. Configure the OAuth consent screen and create an OAuth client. A **Desktop app** client is suitable for local use.
270
+ 3. Authorize your Google account and obtain a refresh token. The [OAuth 2.0 Playground](https://developers.google.com/oauthplayground) can do this if you enable **Use your own OAuth credentials**.
271
+ 4. Request these scopes together:
272
+
273
+ ```text
274
+ https://www.googleapis.com/auth/tagmanager.readonly
275
+ https://www.googleapis.com/auth/tagmanager.edit.containers
276
+ https://www.googleapis.com/auth/tagmanager.edit.containerversions
277
+ https://www.googleapis.com/auth/tagmanager.publish
278
+ ```
279
+
280
+ The scopes are separate: reading, editing, compiling versions and publishing each need their corresponding permission. Treat the client secret and refresh token as passwords.
174
281
 
175
282
  ## Configuration
176
283
 
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
284
+ | Variable | Required | Description |
285
+ |---|---|---|
286
+ | `GOOGLE_TAGMANAGER_CLIENT_ID` | Yes* | OAuth client ID. |
287
+ | `GOOGLE_TAGMANAGER_CLIENT_SECRET` | Yes* | OAuth client secret. |
288
+ | `GOOGLE_TAGMANAGER_REFRESH_TOKEN` | Yes* | OAuth refresh token. |
289
+ | `GOOGLE_TAGMANAGER_ACCESS_TOKEN` | Yes* | Short-lived alternative to the OAuth trio. |
290
+ | `GOOGLE_TAGMANAGER_API_BASE` | No | Tag Manager API base URL override. |
291
+ | `GOOGLE_TAGMANAGER_TIMEOUT_MS` | No | Per-request timeout; default `60000` ms. |
292
+ | `GOOGLE_TAGMANAGER_MAX_RETRIES` | No | Maximum retries on temporary failures; default `3`. |
293
+ | `GOOGLE_TAGMANAGER_MIN_INTERVAL_MS` | No | Minimum request spacing; default `4200` ms. |
294
+
295
+ \* Provide either the OAuth trio or an access token. Access tokens expire in about an hour and are not refreshed automatically.
296
+
297
+ ## Data and telemetry
298
+
299
+ The server runs locally and sends GTM API requests and OAuth refresh requests to Google. Its anonymous telemetry contains a random installation ID, package version, AI client and Node.js/operating-system versions, and tool names. It does not send OAuth tokens, GTM data, tool arguments or prompts.
300
+
301
+ Disable telemetry for A1 MCP servers with:
302
+
303
+ ```bash
304
+ ASKADS_TELEMETRY=0
305
+ ```
306
+
307
+ ## Limits and background work
308
+
309
+ - **GTM is rate-limited.** The API allows 0.25 requests per second per project, so the server serializes calls at least 4.2 seconds apart. Broad audits can therefore take time.
310
+ - **Temporary limits are retried carefully.** `429` and Google quota `403` responses use exponential backoff and `Retry-After`. Reads retry after network and `5xx` failures; writes are not replayed after an uncertain failure.
311
+ - **There is no background monitoring.** The server runs only when your AI app calls it. If the app supports scheduled tasks, it can periodically inspect a container or its live version.
312
+ - **A workspace disappears when compiled.** Before calling `create_version`, save anything you need from the workspace and inspect the returned replacement workspace path.
313
+
314
+ ## Technical documentation
315
+
316
+ - [MCP capability catalog](./docs/capabilities/index.md) — task-oriented pages for every tool.
317
+ - [All tools and inputs](./docs/TOOLS.md)
318
+ - [Development documentation](./docs/DEVELOPMENT.md)
319
+ - [Publishing documentation](./docs/PUBLISHING.md)
213
320
  - [Google Tag Manager API v2 reference](https://developers.google.com/tag-platform/tag-manager/api/reference/rest)
214
321
 
215
322
  ## Support
216
323
 
217
- Questions and issues → [GitHub Issues](https://github.com/A1-x-Tech/mcp-google-tagmanager/issues)
218
- or Telegram [@gistrec](https://t.me/gistrec).
324
+ Found a bug or need a scenario? [Create an issue](https://github.com/A1-x-Tech/mcp-google-tagmanager/issues) or write in [Telegram](https://t.me/a1_mcp).
325
+
326
+ <br>
219
327
 
220
- ## License
328
+ <p align="center">
329
+ <img src="https://github.com/ztemerbekov/a1-yandex-kit-skills/raw/main/assets/images/mona-hifive-yandex-kit-warm.gif" alt="Две Моны дают пять" width="256">
330
+ </p>
221
331
 
222
- [MIT](./LICENSE)
332
+ <p align="center">
333
+ You made it to the end!
334
+ </p>
package/README.ru.md ADDED
@@ -0,0 +1,334 @@
1
+ # <img src="./assets/a1-logo.svg" alt="A1" width="40"> Google Tag Manager MCP
2
+
3
+ [English](./README.md) | **Русский**
4
+
5
+ [![npm](https://img.shields.io/npm/v/mcp-google-tagmanager)](https://www.npmjs.com/package/mcp-google-tagmanager)
6
+ [![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)
7
+ [![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)
8
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
9
+
10
+ **A1 Google Tag Manager MCP** позволяет AI-приложению проверять и настраивать контейнеры Google Tag Manager на естественном языке. Можно увидеть, что срабатывает на странице, подготовить теги, триггеры и переменные в черновом рабочем пространстве, а затем осознанно собрать и опубликовать версию.
11
+
12
+ Сервер подключается к Google Tag Manager API v2 через ваш аккаунт Google. В отличие от догадки AI о настройке GTM, он работает с выбранными вами настоящими контейнером, рабочим пространством и версией.
13
+
14
+ - **19 инструментов.** 10 операций только читают данные GTM; 4 создают черновики или меняют встроенные переменные; 5 могут изменить, удалить, собрать или опубликовать конфигурацию.
15
+ - **Сначала черновик.** Теги, триггеры и переменные создаются в рабочем пространстве. Публикация — отдельная явно разрушительная операция.
16
+ - **С учётом квоты.** GTM разрешает 0,25 запроса в секунду на проект; сервер делает паузу не менее 4,2 секунды между запросами, а не перегружает API.
17
+ - **Ваш доступ Google.** Сервер использует ваши OAuth-данные и запрашивает только scope GTM, нужные для чтения, редактирования, версий и публикации.
18
+
19
+ Начните с запроса, который только читает данные:
20
+
21
+ > Какие теги в моих контейнерах срабатывают по триггеру просмотра страницы?
22
+
23
+ [Подключить сервер](#быстрый-старт) · [Посмотреть сценарии](#что-можно-поручить) · [Открыть техническую документацию](#техническая-документация)
24
+
25
+ ---
26
+
27
+ ## Увидеть работу за минуту
28
+
29
+ > **Вы:** Покажи мои контейнеры GTM и теги, которые срабатывают при просмотре страницы.
30
+ >
31
+ > **Ассистент:** Показывает контейнеры, их рабочие пространства, подходящие триггеры и привязанные теги. Ничего не меняется.
32
+ >
33
+ > **Вы:** В Default Workspace контейнера `GTM-ABC123` подготовь GA4 configuration tag для measurement ID `G-XXXXXXX` на всех страницах.
34
+ >
35
+ > **Ассистент:** Показывает рабочее пространство, предлагаемые настройки тега и триггера, затем запрашивает подтверждение перед созданием черновика.
36
+ >
37
+ > **Вы:** Подтверждаю черновик.
38
+ >
39
+ > **Ассистент:** Создаёт тег в рабочем пространстве. Контейнер не публикуется: сборка и публикация версии остаются отдельным шагом.
40
+
41
+ ## Содержание
42
+
43
+ - [Быстрый старт](#быстрый-старт)
44
+ - [Что можно поручить](#что-можно-поручить)
45
+ - [Как связаны изменения GTM](#как-связаны-изменения-gtm)
46
+ - [Что может измениться](#что-может-измениться)
47
+ - [Как получить доступ](#как-получить-доступ)
48
+ - [Конфигурация](#конфигурация)
49
+ - [Данные и телеметрия](#данные-и-телеметрия)
50
+ - [Ограничения и работа в фоне](#ограничения-и-работа-в-фоне)
51
+ - [Техническая документация](#техническая-документация)
52
+ - [Поддержка](#поддержка)
53
+
54
+ ## Быстрый старт
55
+
56
+ Нужны Node.js 20+, Google-аккаунт с доступом к контейнеру GTM и OAuth-данные из проекта Google Cloud, в котором включён Tag Manager API.
57
+
58
+ 1. [Подготовьте Google OAuth-доступ](#как-получить-доступ).
59
+ 2. Добавьте сервер в AI-приложение.
60
+ 3. Начните с запроса, который только читает данные.
61
+
62
+ <details open>
63
+ <summary><strong>Codex</strong></summary>
64
+
65
+ <br>
66
+
67
+ **В приложении:**
68
+
69
+ 1. Откройте **Settings → Plugins → MCP servers**.
70
+ 2. Нажмите **Add server**.
71
+ 3. Добавьте `npx -y mcp-google-tagmanager@latest` и три переменные окружения ниже.
72
+
73
+ | Переменная | Значение |
74
+ |---|---|
75
+ | `GOOGLE_TAGMANAGER_CLIENT_ID` | Ваш Google OAuth client ID |
76
+ | `GOOGLE_TAGMANAGER_CLIENT_SECRET` | Ваш Google OAuth client secret |
77
+ | `GOOGLE_TAGMANAGER_REFRESH_TOKEN` | Ваш Google OAuth refresh token |
78
+
79
+ **В командной строке:**
80
+
81
+ ```bash
82
+ codex mcp add google-tagmanager \
83
+ --env GOOGLE_TAGMANAGER_CLIENT_ID=your_client_id \
84
+ --env GOOGLE_TAGMANAGER_CLIENT_SECRET=your_client_secret \
85
+ --env GOOGLE_TAGMANAGER_REFRESH_TOKEN=your_refresh_token \
86
+ -- npx -y mcp-google-tagmanager@latest
87
+ ```
88
+
89
+ ```bash
90
+ codex mcp list
91
+ ```
92
+
93
+ [Документация Codex MCP](https://learn.chatgpt.com/docs/extend/mcp?surface=cli)
94
+
95
+ </details>
96
+
97
+ <details>
98
+ <summary><strong>Claude Code</strong></summary>
99
+
100
+ <br>
101
+
102
+ ```bash
103
+ claude mcp add \
104
+ --env GOOGLE_TAGMANAGER_CLIENT_ID=your_client_id \
105
+ --env GOOGLE_TAGMANAGER_CLIENT_SECRET=your_client_secret \
106
+ --env GOOGLE_TAGMANAGER_REFRESH_TOKEN=your_refresh_token \
107
+ --transport stdio \
108
+ --scope user \
109
+ google-tagmanager \
110
+ -- npx -y mcp-google-tagmanager@latest
111
+ ```
112
+
113
+ ```bash
114
+ claude mcp list
115
+ ```
116
+
117
+ [Документация Claude Code MCP](https://code.claude.com/docs/en/mcp)
118
+
119
+ </details>
120
+
121
+ <details>
122
+ <summary><strong>Claude Desktop</strong></summary>
123
+
124
+ <br>
125
+
126
+ 1. Откройте **Settings → Developer → Edit Config**.
127
+ 2. Добавьте запись в `mcpServers`:
128
+
129
+ ```json
130
+ {
131
+ "mcpServers": {
132
+ "google-tagmanager": {
133
+ "command": "npx",
134
+ "args": ["-y", "mcp-google-tagmanager@latest"],
135
+ "env": {
136
+ "GOOGLE_TAGMANAGER_CLIENT_ID": "your_client_id",
137
+ "GOOGLE_TAGMANAGER_CLIENT_SECRET": "your_client_secret",
138
+ "GOOGLE_TAGMANAGER_REFRESH_TOKEN": "your_refresh_token"
139
+ }
140
+ }
141
+ }
142
+ }
143
+ ```
144
+
145
+ Если **Edit Config** недоступна, отредактируйте `~/Library/Application Support/Claude/claude_desktop_config.json` на macOS или `%APPDATA%\Claude\claude_desktop_config.json` на Windows.
146
+
147
+ [Документация Claude Desktop MCP](https://support.claude.com/en/articles/10949351-getting-started-with-local-mcp-servers-on-claude-desktop)
148
+
149
+ </details>
150
+
151
+ <details>
152
+ <summary><strong>Cursor</strong></summary>
153
+
154
+ <br>
155
+
156
+ Добавьте сервер уровня пользователя в `~/.cursor/mcp.json` на macOS/Linux или в `%USERPROFILE%\.cursor\mcp.json` на Windows:
157
+
158
+ ```json
159
+ {
160
+ "mcpServers": {
161
+ "google-tagmanager": {
162
+ "type": "stdio",
163
+ "command": "npx",
164
+ "args": ["-y", "mcp-google-tagmanager@latest"],
165
+ "env": {
166
+ "GOOGLE_TAGMANAGER_CLIENT_ID": "your_client_id",
167
+ "GOOGLE_TAGMANAGER_CLIENT_SECRET": "your_client_secret",
168
+ "GOOGLE_TAGMANAGER_REFRESH_TOKEN": "your_refresh_token"
169
+ }
170
+ }
171
+ }
172
+ }
173
+ ```
174
+
175
+ [Документация Cursor MCP](https://cursor.com/docs/mcp)
176
+
177
+ </details>
178
+
179
+ <details>
180
+ <summary><strong>VS Code</strong></summary>
181
+
182
+ <br>
183
+
184
+ Запустите **MCP: Open User Configuration** из Command Palette и добавьте:
185
+
186
+ ```json
187
+ {
188
+ "servers": {
189
+ "google-tagmanager": {
190
+ "type": "stdio",
191
+ "command": "npx",
192
+ "args": ["-y", "mcp-google-tagmanager@latest"],
193
+ "env": {
194
+ "GOOGLE_TAGMANAGER_CLIENT_ID": "${input:gtm_client_id}",
195
+ "GOOGLE_TAGMANAGER_CLIENT_SECRET": "${input:gtm_client_secret}",
196
+ "GOOGLE_TAGMANAGER_REFRESH_TOKEN": "${input:gtm_refresh_token}"
197
+ }
198
+ }
199
+ },
200
+ "inputs": [
201
+ { "type": "promptString", "id": "gtm_client_id", "description": "Google OAuth client ID" },
202
+ { "type": "promptString", "id": "gtm_client_secret", "description": "Google OAuth client secret", "password": true },
203
+ { "type": "promptString", "id": "gtm_refresh_token", "description": "Google OAuth refresh token", "password": true }
204
+ ]
205
+ }
206
+ ```
207
+
208
+ Проверьте сервер командой **MCP: List Servers**.
209
+
210
+ [Документация VS Code MCP](https://code.visualstudio.com/docs/agent-customization/mcp-servers)
211
+
212
+ </details>
213
+
214
+ ## Что можно поручить
215
+
216
+ ### Понять текущую настройку
217
+
218
+ - Покажи доступные мне аккаунты и контейнеры GTM.
219
+ - Какие теги срабатывают при просмотре страницы в этом рабочем пространстве?
220
+ - Покажи настройки триггера и переменных для этого тега.
221
+ - Какие встроенные переменные включены?
222
+
223
+ ### Подготовить изменение аналитики в черновике
224
+
225
+ - Создай рабочее пространство для изменения отслеживания checkout.
226
+ - Подготовь GA4-тег и триггер для нужного события.
227
+ - Включи переменные клика, необходимые для этого триггера.
228
+ - Обнови этот тег, сначала показав мне полную конфигурацию для замены.
229
+
230
+ ### Осознанно выпустить версию
231
+
232
+ - Собери из этого рабочего пространства версию с названием `April release`.
233
+ - Покажи ошибки компилятора, если они есть.
234
+ - Опубликуй версию `42` после моего подтверждения версии и её изменений.
235
+
236
+ ## Как связаны изменения GTM
237
+
238
+ В GTM есть понятный путь выпуска:
239
+
240
+ 1. В **аккаунте** находятся один или несколько **контейнеров**.
241
+ 2. У контейнера есть **рабочие пространства** для черновых изменений.
242
+ 3. Теги, триггеры и переменные принадлежат рабочему пространству.
243
+ 4. Сборка рабочего пространства создаёт **версию контейнера** и удаляет исходное рабочее пространство. GTM создаёт замену.
244
+ 5. Публикация делает выбранную версию контейнера рабочей.
245
+
246
+ Сервер умеет проверить каждый шаг. Он не приравнивает черновик к выпуску: создание версии и публикация — разные операции.
247
+
248
+ ## Что может измениться
249
+
250
+ | Операция | Что происходит | Граница подтверждения |
251
+ |---|---|---|
252
+ | Просмотр аккаунтов, контейнеров, пространств, тегов, триггеров, переменных и версий | Читает конфигурацию GTM | Ничего не меняет |
253
+ | Создание контейнера или рабочего пространства | Добавляет объект GTM | Меняет GTM |
254
+ | Создание тега, триггера или переменной | Добавляет черновой объект в пространство | Меняет черновое пространство |
255
+ | Включение или выключение встроенных переменных | Меняет конфигурацию пространства | Меняет черновое пространство |
256
+ | Обновление тега, триггера или переменной | Полностью заменяет ресурс, защищённый fingerprint | Потенциально разрушительно |
257
+ | Удаление тега, триггера или переменной | Удаляет выбранный объект | Разрушительно |
258
+ | Сборка рабочего пространства | Создаёт версию и удаляет исходное пространство | Разрушительно |
259
+ | Публикация версии | Делает выбранную версию рабочей | Разрушительно |
260
+ | Технический запрос API | Может вызвать метод API без отдельного инструмента | Потенциально разрушительно |
261
+
262
+ То, как AI-приложение запрашивает подтверждение, определяет само приложение. Сервер помечает операции как read-only, write и destructive, чтобы оно могло отличить проверку от реального изменения.
263
+
264
+ ## Как получить доступ
265
+
266
+ Сервер использует Google OAuth 2.0. Google Tag Manager не предоставляет API-ключи для этих пользовательских данных.
267
+
268
+ 1. Создайте или выберите проект Google Cloud и включите [Tag Manager API](https://console.cloud.google.com/apis/library/tagmanager.googleapis.com). Проект без включённого API не получает квоту.
269
+ 2. Настройте OAuth consent screen и создайте OAuth-клиент. Для локальной работы подходит тип **Desktop app**.
270
+ 3. Авторизуйте свой Google-аккаунт и получите refresh token. Это можно сделать через [OAuth 2.0 Playground](https://developers.google.com/oauthplayground), если включить **Use your own OAuth credentials**.
271
+ 4. Запросите все scope вместе:
272
+
273
+ ```text
274
+ https://www.googleapis.com/auth/tagmanager.readonly
275
+ https://www.googleapis.com/auth/tagmanager.edit.containers
276
+ https://www.googleapis.com/auth/tagmanager.edit.containerversions
277
+ https://www.googleapis.com/auth/tagmanager.publish
278
+ ```
279
+
280
+ Scope разделены: для чтения, редактирования, сборки версии и публикации требуется соответствующее разрешение. Храните client secret и refresh token как пароли.
281
+
282
+ ## Конфигурация
283
+
284
+ | Переменная | Обязательна | Описание |
285
+ |---|---|---|
286
+ | `GOOGLE_TAGMANAGER_CLIENT_ID` | Да* | OAuth client ID. |
287
+ | `GOOGLE_TAGMANAGER_CLIENT_SECRET` | Да* | OAuth client secret. |
288
+ | `GOOGLE_TAGMANAGER_REFRESH_TOKEN` | Да* | OAuth refresh token. |
289
+ | `GOOGLE_TAGMANAGER_ACCESS_TOKEN` | Да* | Короткоживущая альтернатива OAuth-тройке. |
290
+ | `GOOGLE_TAGMANAGER_API_BASE` | Нет | Переопределяет базовый URL Tag Manager API. |
291
+ | `GOOGLE_TAGMANAGER_TIMEOUT_MS` | Нет | Тайм-аут запроса; по умолчанию `60000` мс. |
292
+ | `GOOGLE_TAGMANAGER_MAX_RETRIES` | Нет | Максимум повторов при временных ошибках; по умолчанию `3`. |
293
+ | `GOOGLE_TAGMANAGER_MIN_INTERVAL_MS` | Нет | Минимальная пауза между запросами; по умолчанию `4200` мс. |
294
+
295
+ \* Передайте либо OAuth-тройку, либо access token. Access token истекает примерно через час и автоматически не обновляется.
296
+
297
+ ## Данные и телеметрия
298
+
299
+ Сервер работает локально и отправляет запросы GTM API и OAuth refresh requests в Google. Анонимная телеметрия содержит случайный ID установки, версию пакета, версии AI-клиента, Node.js и операционной системы, а также имена инструментов. OAuth-токены, данные GTM, аргументы инструментов и промпты не отправляются.
300
+
301
+ Отключить телеметрию для MCP-серверов A1 можно так:
302
+
303
+ ```bash
304
+ ASKADS_TELEMETRY=0
305
+ ```
306
+
307
+ ## Ограничения и работа в фоне
308
+
309
+ - **GTM ограничивает частоту.** API разрешает 0,25 запроса в секунду на проект, поэтому сервер выполняет запросы с интервалом не менее 4,2 секунды. Широкая проверка может занять время.
310
+ - **Временные лимиты обрабатываются осторожно.** Ответы `429` и quota `403` от Google обрабатываются с экспоненциальной задержкой и `Retry-After`. Чтение повторяется после сетевых и `5xx` ошибок; запись после неопределённой ошибки не повторяется.
311
+ - **Постоянного наблюдения нет.** Сервер работает только во время вызова из AI-приложения. Если приложение поддерживает задания по расписанию, оно может периодически проверять контейнер или его рабочую версию.
312
+ - **Рабочее пространство исчезает при сборке.** Перед `create_version` сохраните нужные данные и проверьте путь к созданному GTM пространству-замене.
313
+
314
+ ## Техническая документация
315
+
316
+ - [Каталог MCP-возможностей](./docs/capabilities/index.md) — страницы по пользовательским задачам для каждого инструмента.
317
+ - [Все инструменты и параметры](./docs/TOOLS.md)
318
+ - [Документация по разработке](./docs/DEVELOPMENT.md)
319
+ - [Документация по публикации](./docs/PUBLISHING.md)
320
+ - [Справочник Google Tag Manager API v2](https://developers.google.com/tag-platform/tag-manager/api/reference/rest)
321
+
322
+ ## Поддержка
323
+
324
+ Нашли ошибку или не хватает сценария? [Создайте issue](https://github.com/A1-x-Tech/mcp-google-tagmanager/issues) или напишите в [Telegram](https://t.me/a1_mcp).
325
+
326
+ <br>
327
+
328
+ <p align="center">
329
+ <img src="https://github.com/ztemerbekov/a1-yandex-kit-skills/raw/main/assets/images/mona-hifive-yandex-kit-warm.gif" alt="Две Моны дают пять" width="256">
330
+ </p>
331
+
332
+ <p align="center">
333
+ Вы дочитали до конца!
334
+ </p>
package/dist/auth.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { CredentialsError } from "./config.js";
1
2
  import { TagManagerError } from "./types.js";
2
3
  /** Google OAuth 2.0 token endpoint. */
3
4
  const TOKEN_URL = "https://oauth2.googleapis.com/token";
@@ -20,6 +21,11 @@ const DEFAULT_LIFETIME_S = 3600;
20
21
  *
21
22
  * Token-endpoint calls do not count against the GTM API quota, so they bypass
22
23
  * the client's rate limiter.
24
+ *
25
+ * With no credentials at all (a degraded start), {@link CredentialsError} is
26
+ * thrown BEFORE any fetch — a missing setup must never enter the retry/backoff
27
+ * loop or reach the token endpoint, because no amount of retrying mints
28
+ * credentials.
23
29
  */
24
30
  export class TokenProvider {
25
31
  config;
@@ -32,6 +38,9 @@ export class TokenProvider {
32
38
  async getAccessToken() {
33
39
  if (this.config.accessToken)
34
40
  return this.config.accessToken;
41
+ if (!this.config.clientId && !this.config.clientSecret && !this.config.refreshToken) {
42
+ throw new CredentialsError();
43
+ }
35
44
  if (this.cachedToken && Date.now() < this.cachedUntil)
36
45
  return this.cachedToken;
37
46
  if (!this.pending) {
@@ -44,7 +53,8 @@ export class TokenProvider {
44
53
  async refresh() {
45
54
  const { clientId, clientSecret, refreshToken } = this.config;
46
55
  if (!clientId || !clientSecret || !refreshToken) {
47
- // loadConfig guarantees the trio when accessToken is absent; this guards direct construction.
56
+ // loadConfig yields either a full trio or no credentials at all (caught
57
+ // above as CredentialsError); this guards a direct partial construction.
48
58
  throw new Error("OAuth refresh requires GOOGLE_TAGMANAGER_CLIENT_ID, GOOGLE_TAGMANAGER_CLIENT_SECRET and GOOGLE_TAGMANAGER_REFRESH_TOKEN.");
49
59
  }
50
60
  const body = new URLSearchParams({
package/dist/config.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /** Default Google Tag Manager API host. */
2
- const DEFAULT_BASE = "https://tagmanager.googleapis.com";
2
+ export const DEFAULT_BASE = "https://tagmanager.googleapis.com";
3
3
  /**
4
4
  * GTM enforces 0.25 QPS per project (25 requests / 100 s sliding window), so
5
5
  * requests are spaced at least this far apart by default: 100_000 ms / 25 = 4_000,
@@ -7,9 +7,10 @@ const DEFAULT_BASE = "https://tagmanager.googleapis.com";
7
7
  */
8
8
  const DEFAULT_MIN_INTERVAL_MS = 4_200;
9
9
  /**
10
- * A missing or malformed environment variable. Thrown instead of exiting on the
11
- * spot so index.ts owns the process exit; `reason` is a machine-readable code
12
- * (never a variable's value).
10
+ * A malformed environment variable combination. Thrown instead of exiting on
11
+ * the spot so index.ts can catch it, report the drop-off and start degraded
12
+ * instead of dying; `reason` is a machine-readable code (never a variable's
13
+ * value).
13
14
  */
14
15
  export class ConfigError extends Error {
15
16
  reason;
@@ -19,12 +20,42 @@ export class ConfigError extends Error {
19
20
  this.reason = reason;
20
21
  }
21
22
  }
22
- function die(message, reason) {
23
- throw new ConfigError(message, reason);
23
+ /**
24
+ * What a tool call without credentials reads. The first sentence is the
25
+ * historical startup error, verbatim (it already names both auth modes) — the
26
+ * rest exists because credentials come only from the environment, so the fix
27
+ * is an operator action plus a restart, never a retry.
28
+ */
29
+ export const MISSING_CREDENTIALS_MESSAGE = "GOOGLE_TAGMANAGER_CLIENT_ID is required (OAuth client id; or set GOOGLE_TAGMANAGER_ACCESS_TOKEN directly). " +
30
+ "This is not a network failure and retrying will not help: the operator must set these " +
31
+ "environment variables in the MCP client's server config and restart the server — they are " +
32
+ "read only at startup.";
33
+ /**
34
+ * Raised when a tool call needs credentials and none were configured. The
35
+ * message is the whole point of the class: it is the only text the calling
36
+ * model reads about the missing setup, so it names the fix (which variables,
37
+ * and that a restart is needed) instead of the failure.
38
+ */
39
+ export class CredentialsError extends Error {
40
+ constructor(message = MISSING_CREDENTIALS_MESSAGE) {
41
+ super(message);
42
+ this.name = "CredentialsError";
43
+ }
44
+ }
45
+ /** True when the config carries usable credentials (a direct access token or the full refresh trio). */
46
+ export function hasCredentials(config) {
47
+ return Boolean(config.accessToken || (config.clientId && config.clientSecret && config.refreshToken));
24
48
  }
25
49
  /**
26
- * Builds the client config from environment variables, throwing ConfigError if
27
- * a required one is missing.
50
+ * Builds the client config from environment variables.
51
+ *
52
+ * Missing credentials are NOT an error here: the server starts anyway and the
53
+ * token provider raises {@link CredentialsError} on the first tool call, so an
54
+ * unconfigured install completes the MCP handshake and carries the fix into
55
+ * the session instead of dying before it with nothing to read. A malformed
56
+ * setup — some credential variable set but no workable combination — still
57
+ * throws, keeping the historical per-variable messages and reason codes,
58
+ * because guessing what the user meant is worse.
28
59
  *
29
60
  * Two auth modes:
30
61
  * GOOGLE_TAGMANAGER_ACCESS_TOKEN ready-made OAuth access token (quick sessions;
@@ -39,19 +70,24 @@ function die(message, reason) {
39
70
  * GOOGLE_TAGMANAGER_MIN_INTERVAL_MS min spacing between API requests (default 4200)
40
71
  */
41
72
  export function loadConfig() {
42
- const accessToken = process.env.GOOGLE_TAGMANAGER_ACCESS_TOKEN;
43
- const clientId = process.env.GOOGLE_TAGMANAGER_CLIENT_ID;
44
- const clientSecret = process.env.GOOGLE_TAGMANAGER_CLIENT_SECRET;
45
- const refreshToken = process.env.GOOGLE_TAGMANAGER_REFRESH_TOKEN;
46
- if (!accessToken) {
73
+ // An empty string counts as "not set" — a blank value in an MCP config is
74
+ // the same operator mistake as a missing one.
75
+ const accessToken = process.env.GOOGLE_TAGMANAGER_ACCESS_TOKEN || undefined;
76
+ const clientId = process.env.GOOGLE_TAGMANAGER_CLIENT_ID || undefined;
77
+ const clientSecret = process.env.GOOGLE_TAGMANAGER_CLIENT_SECRET || undefined;
78
+ const refreshToken = process.env.GOOGLE_TAGMANAGER_REFRESH_TOKEN || undefined;
79
+ // None of the four set → not an error (degraded start). Some set but no
80
+ // workable combination → the historical checks in their historical order.
81
+ const anyProvided = Boolean(accessToken || clientId || clientSecret || refreshToken);
82
+ if (anyProvided && !accessToken) {
47
83
  if (!clientId) {
48
- die("GOOGLE_TAGMANAGER_CLIENT_ID is required (OAuth client id; or set GOOGLE_TAGMANAGER_ACCESS_TOKEN directly).", "missing_client_id");
84
+ throw new ConfigError("GOOGLE_TAGMANAGER_CLIENT_ID is required (OAuth client id; or set GOOGLE_TAGMANAGER_ACCESS_TOKEN directly).", "missing_client_id");
49
85
  }
50
86
  if (!clientSecret) {
51
- die("GOOGLE_TAGMANAGER_CLIENT_SECRET is required (OAuth client secret).", "missing_client_secret");
87
+ throw new ConfigError("GOOGLE_TAGMANAGER_CLIENT_SECRET is required (OAuth client secret).", "missing_client_secret");
52
88
  }
53
89
  if (!refreshToken) {
54
- die("GOOGLE_TAGMANAGER_REFRESH_TOKEN is required (OAuth refresh token).", "missing_refresh_token");
90
+ throw new ConfigError("GOOGLE_TAGMANAGER_REFRESH_TOKEN is required (OAuth refresh token).", "missing_refresh_token");
55
91
  }
56
92
  }
57
93
  const timeoutMs = Number(process.env.GOOGLE_TAGMANAGER_TIMEOUT_MS);
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ import { readFileSync } from "node:fs";
3
3
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
4
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
5
  import { TagManagerClient } from "./client.js";
6
- import { ConfigError, loadConfig } from "./config.js";
6
+ import { ConfigError, DEFAULT_BASE, hasCredentials, loadConfig } from "./config.js";
7
7
  import { instrumentToolCalls, Telemetry } from "./telemetry.js";
8
8
  import { registerAccountTools } from "./tools/accounts.js";
9
9
  import { registerBuiltInVariableTools } from "./tools/builtins.js";
@@ -12,6 +12,37 @@ import { registerEntityTools } from "./tools/entities.js";
12
12
  import { registerRawTool } from "./tools/raw.js";
13
13
  import { registerVersionTools } from "./tools/versions.js";
14
14
  import { registerWorkspaceTools } from "./tools/workspaces.js";
15
+ /**
16
+ * The prose the calling model receives in the initialize result, before it sees
17
+ * a single tool. It carries only what the tool list cannot: what this API is
18
+ * not, where the live-site danger sits, what the quota costs, and which errors
19
+ * mean something other than what they say.
20
+ */
21
+ const INSTRUCTIONS = "Google Tag Manager API v2 configures what a container deploys — tags, triggers, variables, " +
22
+ "versions. It is not Google Analytics: no visits, conversions or reporting exist here. Tag, " +
23
+ "trigger and variable edits land in a workspace draft and change nothing on real sites until " +
24
+ "create_version compiles it; compiling consumes the workspace, so a workspace id from before a " +
25
+ "create_version is dead. Quota binds everything: 0.25 QPS per project (25 calls/100 s) and 10k a " +
26
+ "day, so requests are spaced 4.2 s apart by default — auditing a container takes minutes by " +
27
+ "design; plan the fewest calls, never poll. 429 and quota-403 are already retried with backoff; " +
28
+ "retrying by hand only burns quota. A 403 is as often a missing OAuth scope (readonly, " +
29
+ "edit.containers, edit.containerversions and publish are granted separately) as a real permission " +
30
+ "problem, an empty list_accounts means the authorized Google account sees no GTM account, not " +
31
+ "that none exists, and with a direct access token (no refresh trio) a 401 after an hour is just " +
32
+ "expiry. publish_version replaces production on every site with the container.";
33
+ /**
34
+ * Prepended to INSTRUCTIONS when no credentials are configured. The model reads
35
+ * this before it picks a tool, so an unconfigured session opens with the fix
36
+ * rather than with a failed call. There is no in-chat login here: credentials
37
+ * come only from the environment, so the fix is an operator action + restart.
38
+ */
39
+ const UNCONFIGURED_PREFIX = "ATTENTION: Google Tag Manager is not connected yet — no credentials are configured, so every " +
40
+ "tool call will fail. The operator must set GOOGLE_TAGMANAGER_CLIENT_ID + " +
41
+ "GOOGLE_TAGMANAGER_CLIENT_SECRET + GOOGLE_TAGMANAGER_REFRESH_TOKEN (recommended; an OAuth " +
42
+ "client from console.cloud.google.com with the Tag Manager API enabled, plus a refresh token " +
43
+ "minted at developers.google.com/oauthplayground — see the README's \"Getting credentials\"), " +
44
+ "or GOOGLE_TAGMANAGER_ACCESS_TOKEN with a short-lived access token, in the MCP client's server " +
45
+ "config and restart this server — the variables are read only at startup. ";
15
46
  /** Reads the package version so the server reports its real version to MCP clients. */
16
47
  function readVersion() {
17
48
  try {
@@ -23,21 +54,27 @@ function readVersion() {
23
54
  }
24
55
  }
25
56
  /**
26
- * Loads the config, reporting the drop-off if it is missing. An unconfigured
27
- * server dies before the MCP handshake, so this ping is the only trace such an
28
- * install ever leaves — and it has to be awaited, or process.exit() below would
29
- * kill the request in flight.
57
+ * Loads the config without dying on a bad value. A server that exits here never
58
+ * completes the MCP handshake, so the user sees a dead server and no reason.
59
+ * Instead the problem is carried into the session, where the model can read it
60
+ * and relay it: the config degrades to "no credentials" and every tool call
61
+ * fails with the actionable message.
30
62
  */
31
- async function loadConfigOrExit(telemetry) {
63
+ function loadConfigOrDegraded(telemetry) {
32
64
  try {
33
- return loadConfig();
65
+ return { config: loadConfig() };
34
66
  }
35
67
  catch (err) {
36
68
  if (!(err instanceof ConfigError))
37
69
  throw err;
38
70
  console.error(`Error: ${err.message}`);
39
- await telemetry.sendBlocking("startup_failed", { reason: err.reason });
40
- process.exit(1);
71
+ // Fire-and-forget now that the process survives: the historical
72
+ // `startup_failed` funnel stays comparable, but nothing blocks startup.
73
+ telemetry.send("startup_failed", { reason: err.reason });
74
+ return {
75
+ config: { apiBase: process.env.GOOGLE_TAGMANAGER_API_BASE || DEFAULT_BASE },
76
+ problem: err,
77
+ };
41
78
  }
42
79
  }
43
80
  async function main() {
@@ -45,16 +82,30 @@ async function main() {
45
82
  // arguments); opt out with ASKADS_TELEMETRY=0. Built before the config so
46
83
  // missing credentials can be reported; wired to the server before tools register.
47
84
  const telemetry = new Telemetry(readVersion());
48
- const config = await loadConfigOrExit(telemetry);
85
+ const { config, problem } = loadConfigOrDegraded(telemetry);
49
86
  const client = new TagManagerClient(config);
87
+ // Decided once, at startup: credentials come only from the environment, so
88
+ // "restart after setting the variables" is the accurate advice to give.
89
+ const connected = hasCredentials(config);
90
+ // `instructions` belongs to the SDK's ServerOptions (2nd argument); passed
91
+ // next to name/version it would be silently dropped from the initialize result.
50
92
  const server = new McpServer({
51
93
  name: "mcp-google-tagmanager",
52
94
  version: readVersion(),
95
+ }, {
96
+ instructions: connected
97
+ ? INSTRUCTIONS
98
+ : UNCONFIGURED_PREFIX + (problem ? `Configuration problem: ${problem.message} ` : "") + INSTRUCTIONS,
53
99
  });
54
100
  instrumentToolCalls(server, telemetry);
55
101
  server.server.oninitialized = () => {
56
102
  telemetry.setClientInfo(server.server.getClientVersion());
57
- telemetry.send("server_start");
103
+ // Split on purpose: `server_start` keeps meaning "a usable install started",
104
+ // so the unconfigured case gets its own event instead of inflating that number.
105
+ if (connected)
106
+ telemetry.send("server_start");
107
+ else
108
+ telemetry.send("unconfigured_start", { reason: problem?.reason ?? "missing_client_id" });
58
109
  };
59
110
  registerAccountTools(server, client);
60
111
  registerContainerTools(server, client);
@@ -66,7 +117,7 @@ async function main() {
66
117
  const transport = new StdioServerTransport();
67
118
  await server.connect(transport);
68
119
  // stderr: stdout is reserved for the MCP protocol.
69
- console.error("mcp-google-tagmanager running on stdio");
120
+ console.error(`mcp-google-tagmanager running on stdio${connected ? "" : " (no credentials — set the environment variables and restart)"}`);
70
121
  }
71
122
  main().catch((err) => {
72
123
  console.error("Fatal error starting mcp-google-tagmanager:", err);
package/dist/telemetry.js CHANGED
@@ -69,9 +69,9 @@ export class Telemetry {
69
69
  void this.post(event, fields);
70
70
  }
71
71
  /**
72
- * The same ping, awaited. Only for the startup_failed path: that caller
73
- * calls process.exit() immediately after, which would kill an in-flight
74
- * fire-and-forget request before it ever left the machine.
72
+ * The same ping, awaited. Only for a caller that exits right after — a
73
+ * fire-and-forget request would die in flight with the process. No startup
74
+ * path needs it anymore (a config problem degrades instead of exiting).
75
75
  */
76
76
  async sendBlocking(event, fields = {}) {
77
77
  await this.post(event, fields);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-google-tagmanager",
3
- "version": "0.1.2",
3
+ "version": "1.1.0",
4
4
  "description": "MCP server for the Google Tag Manager API v2 — accounts, containers, workspaces, tags, triggers, variables, versions and publishing. For Claude, Cursor, Codex and other AI clients.",
5
5
  "mcpName": "io.github.A1-x-Tech/mcp-google-tagmanager",
6
6
  "type": "module",
@@ -45,6 +45,16 @@ test("dist binary completes a real MCP handshake over stdio and lists every tool
45
45
  assert.equal(serverInfo.name, "mcp-google-tagmanager");
46
46
  assert.notEqual(serverInfo.version, "0.0.0"); // real version read from package.json
47
47
 
48
+ // The only prose the calling model gets before it picks a tool. An empty
49
+ // one means the option was dropped somewhere between src and dist.
50
+ const instructions = client.getInstructions();
51
+ assert.ok(instructions, "initialize must carry instructions");
52
+ assert.ok(instructions.length > 300, `instructions look truncated (${instructions.length} chars)`);
53
+ // Regression guard on the two facts that cost the most to rediscover: GTM
54
+ // configures tags, it does not report data, and the quota is the bottleneck.
55
+ assert.match(instructions, /not Google Analytics/);
56
+ assert.match(instructions, /0\.25 QPS/);
57
+
48
58
  const { tools } = await client.listTools();
49
59
  assert.deepEqual(tools.map((t) => t.name).sort(), ALL_TOOLS);
50
60
  for (const tool of tools) {
@@ -56,20 +66,47 @@ test("dist binary completes a real MCP handshake over stdio and lists every tool
56
66
  }
57
67
  });
58
68
 
59
- test("dist binary exits with an error when unconfigured", async () => {
60
- const { spawn } = await import("node:child_process");
61
- // Opt out so the startup_failed ping never leaves the test machine.
62
- const env = { ...process.env, ASKADS_TELEMETRY: "0" };
63
- delete env.GOOGLE_TAGMANAGER_ACCESS_TOKEN;
64
- delete env.GOOGLE_TAGMANAGER_CLIENT_ID;
65
- delete env.GOOGLE_TAGMANAGER_CLIENT_SECRET;
66
- delete env.GOOGLE_TAGMANAGER_REFRESH_TOKEN;
67
- const child = spawn(process.execPath, [fileURLToPath(new URL("../dist/index.js", import.meta.url))], { env });
68
- let stderr = "";
69
- child.stderr.on("data", (chunk) => (stderr += chunk));
70
- const code = await new Promise((resolve) => child.on("close", resolve));
71
- assert.equal(code, 1);
72
- assert.match(stderr, /GOOGLE_TAGMANAGER_CLIENT_ID is required/);
69
+ /**
70
+ * The degraded-start contract: without any credentials the binary used to
71
+ * exit(1) before the handshake, leaving the client a dead server and no reason.
72
+ * It must now start, list every tool, open the instructions with the fix, and
73
+ * answer a tool call with the actionable error — offline: the CredentialsError
74
+ * fires before any fetch, so this test never touches the network.
75
+ */
76
+ test("dist binary starts without credentials: handshake, tool list, actionable call error", async () => {
77
+ const env = Object.fromEntries(
78
+ Object.entries(process.env).filter(
79
+ ([key, value]) => value !== undefined && !key.startsWith("GOOGLE_TAGMANAGER_"),
80
+ ),
81
+ );
82
+ env.ASKADS_TELEMETRY = "0"; // keep the suite offline
83
+ const transport = new StdioClientTransport({
84
+ command: process.execPath,
85
+ args: [fileURLToPath(new URL("../dist/index.js", import.meta.url))],
86
+ env,
87
+ stderr: "pipe",
88
+ });
89
+ const client = new Client({ name: "dist-smoke-unconfigured", version: "0.0.0" });
90
+ await client.connect(transport);
91
+ try {
92
+ // The model must read the fix before it picks a tool.
93
+ const instructions = client.getInstructions() ?? "";
94
+ assert.match(instructions, /not connected/);
95
+ assert.match(instructions, /GOOGLE_TAGMANAGER_CLIENT_ID/);
96
+ assert.match(instructions, /restart/);
97
+
98
+ const { tools } = await client.listTools();
99
+ assert.deepEqual(tools.map((t) => t.name).sort(), ALL_TOOLS);
100
+
101
+ // A tool call fails with the exact message instead of killing the server.
102
+ const result = await client.callTool({ name: "list_accounts", arguments: {} });
103
+ assert.equal(result.isError, true);
104
+ const text = result.content.map((c) => c.text ?? "").join(" ");
105
+ assert.match(text, /GOOGLE_TAGMANAGER_CLIENT_ID is required \(OAuth client id; or set GOOGLE_TAGMANAGER_ACCESS_TOKEN directly\)\./);
106
+ assert.match(text, /restart the server/);
107
+ } finally {
108
+ await client.close();
109
+ }
73
110
  });
74
111
 
75
112
  test("dist client rejects foreign-origin paths before sending the token", async () => {