mcp-google-tagmanager 1.1.0 → 1.3.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
@@ -3,15 +3,16 @@
3
3
  **English** | [Русский](./README.ru.md)
4
4
 
5
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
6
  [![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)
7
+ [![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)
8
8
  [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
9
9
 
10
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
11
 
12
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
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.
14
+ - **25 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
+ - **Connects from the conversation.** Say "connect Google Tag Manager": the server walks you through the OAuth client, catches Google's redirect on `127.0.0.1` with PKCE and keeps the tokens itself — no config files, no restart.
15
16
  - **Draft first.** Tags, triggers and variables are created in a workspace. Publishing is a separate, explicitly destructive operation.
16
17
  - **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
18
  - **Your Google access.** The server uses your OAuth credentials and requests only the Tag Manager scopes needed for reading, editing, versioning and publishing.
@@ -53,10 +54,10 @@ Start with a read-only question:
53
54
 
54
55
  ## Quick start
55
56
 
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.
57
+ You need Node.js 20+ and a Google account. Credentials are not required at install time — the server connects from the conversation.
57
58
 
58
- 1. [Prepare Google OAuth access](#getting-access).
59
- 2. Add the server to your AI app.
59
+ 1. Add the server to your AI app.
60
+ 2. Say "connect Google Tag Manager": the assistant walks you through [creating the OAuth client and approving access](#getting-access) without editing config files.
60
61
  3. Start with the read-only question above.
61
62
 
62
63
  <details open>
@@ -66,9 +67,9 @@ You need Node.js 20+, a Google account with access to a GTM container and OAuth
66
67
 
67
68
  **In the app:**
68
69
 
69
- 1. Open **Settings → Plugins → MCP servers**.
70
+ 1. Open **Settings → MCP servers**.
70
71
  2. Select **Add server**.
71
- 3. Add `npx -y mcp-google-tagmanager@latest` and the three environment variables below.
72
+ 3. Choose **STDIO**, then enter `npx -y mcp-google-tagmanager@latest` and the three environment variables below.
72
73
 
73
74
  | Variable | Value |
74
75
  |---|---|
@@ -76,13 +77,12 @@ You need Node.js 20+, a Google account with access to a GTM container and OAuth
76
77
  | `GOOGLE_TAGMANAGER_CLIENT_SECRET` | Your Google OAuth client secret |
77
78
  | `GOOGLE_TAGMANAGER_REFRESH_TOKEN` | Your Google OAuth refresh token |
78
79
 
80
+ 4. Select **Save**, then **Restart**.
81
+
79
82
  **From the command line:**
80
83
 
81
84
  ```bash
82
85
  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
86
  -- npx -y mcp-google-tagmanager@latest
87
87
  ```
88
88
 
@@ -101,9 +101,6 @@ codex mcp list
101
101
 
102
102
  ```bash
103
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
104
  --transport stdio \
108
105
  --scope user \
109
106
  google-tagmanager \
@@ -123,26 +120,22 @@ claude mcp list
123
120
 
124
121
  <br>
125
122
 
126
- 1. Open **Settings → Developer → Edit Config**.
127
- 2. Add this entry to `mcpServers`:
123
+ The current official path is **Settings → Extensions**. For a custom desktop extension, open **Advanced settings → Extension Developer → Install Extension…**, select a `.mcpb` file and follow the prompts.
124
+
125
+ This repository currently publishes an npm stdio package and does not contain a `.mcpb` bundle. For Claude Desktop builds that still support local configuration, use the following JSON stdio configuration as a fallback:
128
126
 
129
127
  ```json
130
128
  {
131
129
  "mcpServers": {
132
130
  "google-tagmanager": {
133
131
  "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
- }
132
+ "args": ["-y", "mcp-google-tagmanager@latest"]
140
133
  }
141
134
  }
142
135
  }
143
136
  ```
144
137
 
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.
138
+ In those builds, save it to `~/Library/Application Support/Claude/claude_desktop_config.json` on macOS or `%APPDATA%\Claude\claude_desktop_config.json` on Windows.
146
139
 
147
140
  [Claude Desktop MCP documentation](https://support.claude.com/en/articles/10949351-getting-started-with-local-mcp-servers-on-claude-desktop)
148
141
 
@@ -161,12 +154,7 @@ Add a user-level server to `~/.cursor/mcp.json` on macOS/Linux or `%USERPROFILE%
161
154
  "google-tagmanager": {
162
155
  "type": "stdio",
163
156
  "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
- }
157
+ "args": ["-y", "mcp-google-tagmanager@latest"]
170
158
  }
171
159
  }
172
160
  }
@@ -189,19 +177,9 @@ Run **MCP: Open User Configuration** from the Command Palette and add:
189
177
  "google-tagmanager": {
190
178
  "type": "stdio",
191
179
  "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
- }
180
+ "args": ["-y", "mcp-google-tagmanager@latest"]
198
181
  }
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
- ]
182
+ }
205
183
  }
206
184
  ```
207
185
 
@@ -263,7 +241,20 @@ The AI client decides how it asks for confirmation. The server marks read-only,
263
241
 
264
242
  ## Getting access
265
243
 
266
- The server uses Google OAuth 2.0. Google Tag Manager does not provide API keys for this user data.
244
+ Google Tag Manager requires OAuth 2.0; an API key is not enough. There are two ways in, and the first one needs no configuration files.
245
+
246
+ ### Connect from the chat (recommended)
247
+
248
+ Say "connect Google Tag Manager" and the assistant runs the flow with you:
249
+
250
+ 1. `setup_instructions` prints the checklist: create or select a Google Cloud project, enable **Tag Manager API**, configure the consent screen and create a **Desktop app** OAuth client.
251
+ 2. Download that client's JSON ("Download JSON") and give the assistant its **path** — `set_client` stores it owner-only. The secret never goes through the conversation.
252
+ 3. `start_login` returns a Google consent link. Open it **on this machine** and approve; the code comes back to a one-shot listener on `127.0.0.1` (PKCE), never through the chat.
253
+ 4. `finish_login` exchanges the code and saves the tokens to `~/.config/mcp-google-tagmanager/credentials.json` (mode 0600) and verifies them with a real Tag Manager API call — so an API that is still switched off is caught right there.
254
+
255
+ The tokens are re-read on every call, so the connection works immediately — no restart of the AI app. `auth_status` shows what is connected, `logout` revokes and deletes it.
256
+
257
+ ### Environment variables (CI, unattended installs)
267
258
 
268
259
  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
260
  2. Configure the OAuth consent screen and create an OAuth client. A **Desktop app** client is suitable for local use.
@@ -281,12 +272,15 @@ The scopes are separate: reading, editing, compiling versions and publishing eac
281
272
 
282
273
  ## Configuration
283
274
 
275
+ Every variable is optional — with none of them the server connects [from the chat](#connect-from-the-chat-recommended).
276
+
284
277
  | Variable | Required | Description |
285
278
  |---|---|---|
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. |
279
+ | `GOOGLE_TAGMANAGER_CLIENT_ID` | No* | OAuth client ID. |
280
+ | `GOOGLE_TAGMANAGER_CLIENT_SECRET` | No* | OAuth client secret. |
281
+ | `GOOGLE_TAGMANAGER_REFRESH_TOKEN` | No* | OAuth refresh token. |
282
+ | `GOOGLE_TAGMANAGER_ACCESS_TOKEN` | No* | Short-lived alternative to the OAuth trio. |
283
+ | `GOOGLE_TAGMANAGER_OAUTH_PORT` | No | Fixed loopback port for the in-chat login; useful over SSH port forwarding. |
290
284
  | `GOOGLE_TAGMANAGER_API_BASE` | No | Tag Manager API base URL override. |
291
285
  | `GOOGLE_TAGMANAGER_TIMEOUT_MS` | No | Per-request timeout; default `60000` ms. |
292
286
  | `GOOGLE_TAGMANAGER_MAX_RETRIES` | No | Maximum retries on temporary failures; default `3`. |
@@ -296,7 +290,7 @@ The scopes are separate: reading, editing, compiling versions and publishing eac
296
290
 
297
291
  ## Data and telemetry
298
292
 
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.
293
+ 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. For each tool call it also sends the outcome and, on failure, an excerpt of the error text with e-mails, addresses, tokens, numbers of 4+ digits and quoted text replaced by `#`; a value from your request can appear in it if the error text contains it.
300
294
 
301
295
  Disable telemetry for A1 MCP servers with:
302
296
 
package/README.ru.md CHANGED
@@ -11,7 +11,8 @@
11
11
 
12
12
  Сервер подключается к Google Tag Manager API v2 через ваш аккаунт Google. В отличие от догадки AI о настройке GTM, он работает с выбранными вами настоящими контейнером, рабочим пространством и версией.
13
13
 
14
- - **19 инструментов.** 10 операций только читают данные GTM; 4 создают черновики или меняют встроенные переменные; 5 могут изменить, удалить, собрать или опубликовать конфигурацию.
14
+ - **25 инструментов.** 10 операций только читают данные GTM; 4 создают черновики или меняют встроенные переменные; 5 могут изменить, удалить, собрать или опубликовать конфигурацию.
15
+ - **Подключение из диалога.** Скажите «подключи Google Tag Manager»: сервер проведёт через создание OAuth-клиента, поймает редирект Google на `127.0.0.1` с PKCE и сам сохранит токены — без конфигов и перезапуска.
15
16
  - **Сначала черновик.** Теги, триггеры и переменные создаются в рабочем пространстве. Публикация — отдельная явно разрушительная операция.
16
17
  - **С учётом квоты.** GTM разрешает 0,25 запроса в секунду на проект; сервер делает паузу не менее 4,2 секунды между запросами, а не перегружает API.
17
18
  - **Ваш доступ Google.** Сервер использует ваши OAuth-данные и запрашивает только scope GTM, нужные для чтения, редактирования, версий и публикации.
@@ -53,10 +54,10 @@
53
54
 
54
55
  ## Быстрый старт
55
56
 
56
- Нужны Node.js 20+, Google-аккаунт с доступом к контейнеру GTM и OAuth-данные из проекта Google Cloud, в котором включён Tag Manager API.
57
+ Нужны Node.js 20+ и Google-аккаунт. Учётные данные при установке не нужны: сервер подключается прямо в диалоге.
57
58
 
58
- 1. [Подготовьте Google OAuth-доступ](#как-получить-доступ).
59
- 2. Добавьте сервер в AI-приложение.
59
+ 1. Добавьте сервер в AI-приложение.
60
+ 2. Скажите «подключи Google Tag Manager» — ассистент проведёт [создание OAuth-клиента и выдачу доступа](#как-получить-доступ), не трогая конфиги.
60
61
  3. Начните с запроса, который только читает данные.
61
62
 
62
63
  <details open>
@@ -66,9 +67,9 @@
66
67
 
67
68
  **В приложении:**
68
69
 
69
- 1. Откройте **Settings → Plugins → MCP servers**.
70
+ 1. Откройте **Settings → MCP servers**.
70
71
  2. Нажмите **Add server**.
71
- 3. Добавьте `npx -y mcp-google-tagmanager@latest` и три переменные окружения ниже.
72
+ 3. Выберите **STDIO**, затем укажите `npx -y mcp-google-tagmanager@latest` и три переменные окружения ниже.
72
73
 
73
74
  | Переменная | Значение |
74
75
  |---|---|
@@ -76,13 +77,12 @@
76
77
  | `GOOGLE_TAGMANAGER_CLIENT_SECRET` | Ваш Google OAuth client secret |
77
78
  | `GOOGLE_TAGMANAGER_REFRESH_TOKEN` | Ваш Google OAuth refresh token |
78
79
 
80
+ 4. Нажмите **Save**, затем **Restart**.
81
+
79
82
  **В командной строке:**
80
83
 
81
84
  ```bash
82
85
  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
86
  -- npx -y mcp-google-tagmanager@latest
87
87
  ```
88
88
 
@@ -101,9 +101,6 @@ codex mcp list
101
101
 
102
102
  ```bash
103
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
104
  --transport stdio \
108
105
  --scope user \
109
106
  google-tagmanager \
@@ -123,26 +120,22 @@ claude mcp list
123
120
 
124
121
  <br>
125
122
 
126
- 1. Откройте **Settings → Developer → Edit Config**.
127
- 2. Добавьте запись в `mcpServers`:
123
+ Актуальный официальный путь — **Settings → Extensions**. Для пользовательского desktop extension откройте **Advanced settings → Extension Developer → Install Extension…**, выберите файл `.mcpb` и следуйте подсказкам.
124
+
125
+ Этот репозиторий сейчас публикует npm-пакет со stdio и пока не содержит `.mcpb`. Поэтому используйте приведённый ниже JSON stdio-конфиг как fallback только в сборках Claude Desktop, где ещё поддерживается локальная конфигурация:
128
126
 
129
127
  ```json
130
128
  {
131
129
  "mcpServers": {
132
130
  "google-tagmanager": {
133
131
  "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
- }
132
+ "args": ["-y", "mcp-google-tagmanager@latest"]
140
133
  }
141
134
  }
142
135
  }
143
136
  ```
144
137
 
145
- Если **Edit Config** недоступна, отредактируйте `~/Library/Application Support/Claude/claude_desktop_config.json` на macOS или `%APPDATA%\Claude\claude_desktop_config.json` на Windows.
138
+ В таких сборках сохраните его в `~/Library/Application Support/Claude/claude_desktop_config.json` на macOS или `%APPDATA%\Claude\claude_desktop_config.json` на Windows.
146
139
 
147
140
  [Документация Claude Desktop MCP](https://support.claude.com/en/articles/10949351-getting-started-with-local-mcp-servers-on-claude-desktop)
148
141
 
@@ -161,12 +154,7 @@ claude mcp list
161
154
  "google-tagmanager": {
162
155
  "type": "stdio",
163
156
  "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
- }
157
+ "args": ["-y", "mcp-google-tagmanager@latest"]
170
158
  }
171
159
  }
172
160
  }
@@ -189,19 +177,9 @@ claude mcp list
189
177
  "google-tagmanager": {
190
178
  "type": "stdio",
191
179
  "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
- }
180
+ "args": ["-y", "mcp-google-tagmanager@latest"]
198
181
  }
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
- ]
182
+ }
205
183
  }
206
184
  ```
207
185
 
@@ -263,7 +241,20 @@ claude mcp list
263
241
 
264
242
  ## Как получить доступ
265
243
 
266
- Сервер использует Google OAuth 2.0. Google Tag Manager не предоставляет API-ключи для этих пользовательских данных.
244
+ Google Tag Manager требует OAuth 2.0: одного API-ключа недостаточно. Путей два, и первый не требует править конфигурационные файлы.
245
+
246
+ ### Подключение из диалога (рекомендуемый путь)
247
+
248
+ Скажите «подключи Google Tag Manager», и ассистент пройдёт флоу вместе с вами:
249
+
250
+ 1. `setup_instructions` выдаёт чек-лист: создать или выбрать проект Google Cloud, включить **Tag Manager API**, настроить consent screen и создать OAuth-клиент типа **Desktop app**.
251
+ 2. Скачайте JSON этого клиента («Download JSON») и передайте ассистенту **путь** к файлу — `set_client` сохранит его с правами только для владельца. Секрет через переписку не проходит.
252
+ 3. `start_login` возвращает ссылку на согласие Google. Откройте её **на этой же машине** и подтвердите доступ: код возвращается на одноразовый слушатель `127.0.0.1` (PKCE), а не в чат.
253
+ 4. `finish_login` меняет код на токены и кладёт их в `~/.config/mcp-google-tagmanager/credentials.json` (права 0600) и проверяет их реальным вызовом Tag Manager API — так невключённый API ловится сразу.
254
+
255
+ Токены перечитываются на каждый вызов, поэтому подключение действует немедленно — перезапускать AI-приложение не нужно. `auth_status` показывает состояние, `logout` отзывает токен и удаляет его.
256
+
257
+ ### Переменные окружения (CI и автоматические установки)
267
258
 
268
259
  1. Создайте или выберите проект Google Cloud и включите [Tag Manager API](https://console.cloud.google.com/apis/library/tagmanager.googleapis.com). Проект без включённого API не получает квоту.
269
260
  2. Настройте OAuth consent screen и создайте OAuth-клиент. Для локальной работы подходит тип **Desktop app**.
@@ -281,12 +272,15 @@ Scope разделены: для чтения, редактирования, с
281
272
 
282
273
  ## Конфигурация
283
274
 
275
+ Все переменные необязательные — без единой из них сервер подключается [из диалога](#подключение-из-диалога-рекомендуемый-путь).
276
+
284
277
  | Переменная | Обязательна | Описание |
285
278
  |---|---|---|
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-тройке. |
279
+ | `GOOGLE_TAGMANAGER_CLIENT_ID` | Нет* | OAuth client ID. |
280
+ | `GOOGLE_TAGMANAGER_CLIENT_SECRET` | Нет* | OAuth client secret. |
281
+ | `GOOGLE_TAGMANAGER_REFRESH_TOKEN` | Нет* | OAuth refresh token. |
282
+ | `GOOGLE_TAGMANAGER_ACCESS_TOKEN` | Нет* | Короткоживущая альтернатива OAuth-тройке. |
283
+ | `GOOGLE_TAGMANAGER_OAUTH_PORT` | Нет | Фиксированный порт loopback-слушателя для входа из диалога; нужен при пробросе портов по SSH. |
290
284
  | `GOOGLE_TAGMANAGER_API_BASE` | Нет | Переопределяет базовый URL Tag Manager API. |
291
285
  | `GOOGLE_TAGMANAGER_TIMEOUT_MS` | Нет | Тайм-аут запроса; по умолчанию `60000` мс. |
292
286
  | `GOOGLE_TAGMANAGER_MAX_RETRIES` | Нет | Максимум повторов при временных ошибках; по умолчанию `3`. |
@@ -296,7 +290,7 @@ Scope разделены: для чтения, редактирования, с
296
290
 
297
291
  ## Данные и телеметрия
298
292
 
299
- Сервер работает локально и отправляет запросы GTM API и OAuth refresh requests в Google. Анонимная телеметрия содержит случайный ID установки, версию пакета, версии AI-клиента, Node.js и операционной системы, а также имена инструментов. OAuth-токены, данные GTM, аргументы инструментов и промпты не отправляются.
293
+ Сервер работает локально и отправляет запросы GTM API и OAuth refresh requests в Google. Анонимная телеметрия содержит случайный ID установки, версию пакета, версии AI-клиента, Node.js и операционной системы, а также имена инструментов. OAuth-токены, данные GTM, аргументы инструментов и промпты не отправляются. При вызове инструмента сервер также отправляет его исход, а при ошибке - фрагмент её текста: код и сообщение, в которых e-mail, адреса, токены, числа от 4 цифр и текст в кавычках заменены на «#». Если в тексте ошибки есть значение из запроса, оно тоже может попасть во фрагмент.
300
294
 
301
295
  Отключить телеметрию для MCP-серверов A1 можно так:
302
296
 
package/dist/auth.js CHANGED
@@ -9,36 +9,29 @@ const TOKEN_URL = "https://oauth2.googleapis.com/token";
9
9
  const EXPIRY_MARGIN_MS = 60_000;
10
10
  /** Fallback lifetime when the token response has no usable expires_in. */
11
11
  const DEFAULT_LIFETIME_S = 3600;
12
- /**
13
- * Supplies OAuth access tokens for API requests.
14
- *
15
- * With GOOGLE_TAGMANAGER_ACCESS_TOKEN set, that token is returned as-is (quick
16
- * sessions; Google access tokens expire in ~1 hour and are not auto-refreshed).
17
- * Otherwise the client-id/secret/refresh-token trio is exchanged at
18
- * https://oauth2.googleapis.com/token (form-urlencoded, grant_type=refresh_token)
19
- * and the resulting access token is cached until 60 s before expiry. Concurrent
20
- * callers share one in-flight exchange; a failed exchange is not cached.
21
- *
22
- * Token-endpoint calls do not count against the GTM API quota, so they bypass
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.
29
- */
30
12
  export class TokenProvider {
31
13
  config;
14
+ fallback;
32
15
  cachedToken;
33
16
  cachedUntil = 0;
34
17
  pending;
35
- constructor(config) {
18
+ constructor(config,
19
+ /**
20
+ * Consulted only when the environment carries no credentials — env wins, so
21
+ * existing refresh-trio and access-token installs behave exactly as before.
22
+ * It re-reads the stored login per call, which is what lets a finish_login
23
+ * taken mid-session work without a restart.
24
+ */
25
+ fallback) {
36
26
  this.config = config;
27
+ this.fallback = fallback;
37
28
  }
38
29
  async getAccessToken() {
39
30
  if (this.config.accessToken)
40
31
  return this.config.accessToken;
41
32
  if (!this.config.clientId && !this.config.clientSecret && !this.config.refreshToken) {
33
+ if (this.fallback)
34
+ return this.fallback.getAccessToken();
42
35
  throw new CredentialsError();
43
36
  }
44
37
  if (this.cachedToken && Date.now() < this.cachedUntil)
package/dist/client.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { TokenProvider } from "./auth.js";
2
2
  import { isQuotaError, TagManagerError } from "./types.js";
3
+ import { DEFAULT_BASE } from "./config.js";
3
4
  const ENTITY_COLLECTION = {
4
5
  tag: "tags",
5
6
  trigger: "triggers",
@@ -240,3 +241,29 @@ function compact(obj) {
240
241
  function delay(ms) {
241
242
  return new Promise((resolve) => setTimeout(resolve, ms));
242
243
  }
244
+ /**
245
+ * One cheap Tag Manager read, used to verify a fresh in-chat login against the
246
+ * API the server actually talks to. Standalone (not a client method) because it
247
+ * runs with a token the client does not hold yet — the login is still being
248
+ * finished, and it must bypass the client's rate limiter. Throws
249
+ * TagManagerError exactly like the client does, so the caller can recognize a
250
+ * disabled-API 403 and give the actionable advice.
251
+ */
252
+ export async function probeApi(accessToken) {
253
+ const base = (process.env.GOOGLE_TAGMANAGER_API_BASE || DEFAULT_BASE).replace(/\/+$/, "");
254
+ const res = await fetch(`${base}/tagmanager/v2/accounts`, {
255
+ headers: { Authorization: `Bearer ${accessToken}` },
256
+ signal: AbortSignal.timeout(10_000),
257
+ });
258
+ const text = await res.text();
259
+ if (res.ok)
260
+ return;
261
+ let data;
262
+ try {
263
+ data = JSON.parse(text);
264
+ }
265
+ catch {
266
+ data = text;
267
+ }
268
+ throw new TagManagerError(res.status, data);
269
+ }
package/dist/index.js CHANGED
@@ -12,6 +12,8 @@ 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
+ import { authUnconfiguredPrefix, hasAuthToken, registerAuthTools } from "./tools/auth.js";
16
+ import { TokenProvider } from "./auth.js";
15
17
  /**
16
18
  * The prose the calling model receives in the initialize result, before it sees
17
19
  * a single tool. It carries only what the tool list cannot: what this API is
@@ -36,13 +38,6 @@ const INSTRUCTIONS = "Google Tag Manager API v2 configures what a container depl
36
38
  * rather than with a failed call. There is no in-chat login here: credentials
37
39
  * come only from the environment, so the fix is an operator action + restart.
38
40
  */
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. ";
46
41
  /** Reads the package version so the server reports its real version to MCP clients. */
47
42
  function readVersion() {
48
43
  try {
@@ -83,10 +78,9 @@ async function main() {
83
78
  // missing credentials can be reported; wired to the server before tools register.
84
79
  const telemetry = new Telemetry(readVersion());
85
80
  const { config, problem } = loadConfigOrDegraded(telemetry);
86
- const client = new TagManagerClient(config);
87
81
  // Decided once, at startup: credentials come only from the environment, so
88
82
  // "restart after setting the variables" is the accurate advice to give.
89
- const connected = hasCredentials(config);
83
+ const connected = hasCredentials(config) || hasAuthToken();
90
84
  // `instructions` belongs to the SDK's ServerOptions (2nd argument); passed
91
85
  // next to name/version it would be silently dropped from the initialize result.
92
86
  const server = new McpServer({
@@ -95,7 +89,7 @@ async function main() {
95
89
  }, {
96
90
  instructions: connected
97
91
  ? INSTRUCTIONS
98
- : UNCONFIGURED_PREFIX + (problem ? `Configuration problem: ${problem.message} ` : "") + INSTRUCTIONS,
92
+ : authUnconfiguredPrefix() + (problem ? `Configuration problem: ${problem.message} ` : "") + INSTRUCTIONS,
99
93
  });
100
94
  instrumentToolCalls(server, telemetry);
101
95
  server.server.oninitialized = () => {
@@ -107,6 +101,11 @@ async function main() {
107
101
  else
108
102
  telemetry.send("unconfigured_start", { reason: problem?.reason ?? "missing_client_id" });
109
103
  };
104
+ // The auth tools come first so their provider exists before the client:
105
+ // this server's own TokenProvider falls back to it whenever the
106
+ // environment carries no credentials (env always wins).
107
+ const loginProvider = registerAuthTools(server);
108
+ const client = new TagManagerClient(config, new TokenProvider(config, loginProvider));
110
109
  registerAccountTools(server, client);
111
110
  registerContainerTools(server, client);
112
111
  registerWorkspaceTools(server, client);
package/dist/telemetry.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * Anonymous usage telemetry — fire-and-forget pings to usage.gistrec.cloud.
3
3
  *
4
4
  * Privacy contract (mirrored by the receiver): only an anonymous random
5
- * instance id, event/tool names, a fixed-vocabulary failure reason and
5
+ * instance id, event/tool names, a fixed-vocabulary failure reason or tool outcome and
6
6
  * environment versions ever leave the machine. The OAuth credentials,
7
7
  * account/container ids and paths, tool arguments, prompts and the names or
8
8
  * values of environment variables are never read, serialized or sent. Sends
@@ -64,6 +64,10 @@ export class Telemetry {
64
64
  setClientInfo(info) {
65
65
  this.clientInfo = info;
66
66
  }
67
+ /** Whether pings go out at all (ASKADS_TELEMETRY opt-out). */
68
+ isEnabled() {
69
+ return this.enabled;
70
+ }
67
71
  /** Fire-and-forget: the server's own work never waits on a ping. */
68
72
  send(event, fields = {}) {
69
73
  void this.post(event, fields);
@@ -87,7 +91,8 @@ export class Telemetry {
87
91
  client_name: this.clientInfo?.name,
88
92
  client_version: this.clientInfo?.version,
89
93
  tool: fields.tool,
90
- reason: fields.reason,
94
+ reason: wireReason(event, fields.reason),
95
+ error_detail: event === "tool_call" ? fields.error_detail : undefined,
91
96
  node_version: process.version,
92
97
  os: process.platform,
93
98
  });
@@ -104,17 +109,221 @@ export class Telemetry {
104
109
  }
105
110
  }
106
111
  }
112
+ /** How a tool call ended; only these constants leave the machine. */
113
+ export const TOOL_OUTCOMES = [
114
+ "ok",
115
+ "error_auth",
116
+ "error_permission",
117
+ "error_not_found",
118
+ "error_rate_limit",
119
+ "error_invalid_request",
120
+ "error_upstream",
121
+ "error_timeout",
122
+ "error_network",
123
+ "error_internal",
124
+ "error_other",
125
+ ];
126
+ /** Drops a tool_call reason that is not in TOOL_OUTCOMES. */
127
+ function wireReason(event, reason) {
128
+ if (event !== "tool_call" || reason === undefined)
129
+ return reason;
130
+ return TOOL_OUTCOMES.includes(reason) ? reason : undefined;
131
+ }
132
+ // First match wins. Direct answers "no access to this client" with auth code 53, so that
133
+ // permission line goes before auth.
134
+ const OUTCOME_PATTERNS = [
135
+ ["error_timeout", /timed?[ _-]?out|таймаут|ETIMEDOUT|AbortError|не был готов|not ready/i],
136
+ ["error_network", /ECONNRESET|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|EPIPE|fetch failed|socket hang up/i],
137
+ ["error_rate_limit", /\b429\b|rate[ _-]?limit|too many requests|quota|квот|лимит|\[(?:56|152|506|9000)\]/i],
138
+ ["error_permission", /нет доступа к кабинету|не подключ[её]н к аккаунту/i],
139
+ [
140
+ "error_auth",
141
+ /\b401\b|unauthori[sz]ed|unauthenticated|invalid[ _-]?(?:token|grant|credentials)|token (?:expired|revoked)|login required|AuthRequired|авториз|не подключ|\[53\]/i,
142
+ ],
143
+ ["error_permission", /\b403\b|forbidden|access[ _-]?denied|permission|insufficient[ _-]?scope|нет доступа|\[(?:54|3228)\]/i],
144
+ ["error_not_found", /\b404\b|not[ _-]?found|не найден|не существует|\[8800\]/i],
145
+ ["error_upstream", /\b5\d\d\b|\b204\b|unavailable|недоступ|internal server error|bad gateway|\[(?:52|1000|1001|1002)\]/i],
146
+ ["error_invalid_request", /\b400\b|\b422\b|bad request|invalid|syntax|некоррект|неверн|недопустим|required|обязател|expected|must (?:be|contain|have)|\[(?:4000|4001|4003|5000|8000)\]/i],
147
+ ];
148
+ // An API code at the head of the message wins over the text, which may quote field names
149
+ // ("ForbiddenPlatform" in a [8000] list of allowed values). 53 is absent: the text tells a
150
+ // dead token from no access to a client.
151
+ const CODE_OUTCOMES = new Map([
152
+ ...["56", "152", "506", "9000"].map((c) => [c, "error_rate_limit"]),
153
+ ...["54", "3228"].map((c) => [c, "error_permission"]),
154
+ ["8800", "error_not_found"],
155
+ ...["52", "1000", "1001", "1002"].map((c) => [c, "error_upstream"]),
156
+ ...["4000", "4001", "4003", "5000", "8000"].map((c) => [c, "error_invalid_request"]),
157
+ ]);
158
+ const LEADING_CODE = /^[^[\n]{0,60}\[(\d{1,5})\]/;
159
+ // Inputs are cut before any regex runs: a long argument echoed in an error must not stall the call.
160
+ const TEXT_MAX = 4000;
161
+ function resultText(value) {
162
+ if (value instanceof Error)
163
+ return `${value.name} ${value.message}`.slice(0, TEXT_MAX);
164
+ const content = value?.content;
165
+ if (!Array.isArray(content))
166
+ return "";
167
+ return content
168
+ .map((part) => (part && typeof part === "object" && typeof part.text === "string" ? part.text : ""))
169
+ .join("\n")
170
+ .slice(0, TEXT_MAX);
171
+ }
172
+ /** `toolOutcome(result)` for a returned result, `toolOutcome(undefined, error)` for a thrown one. */
173
+ export function toolOutcome(result, ...thrown) {
174
+ const didThrow = thrown.length > 0;
175
+ if (!didThrow && !result?.isError)
176
+ return "ok";
177
+ const text = resultText(didThrow ? thrown[0] : result);
178
+ const byCode = CODE_OUTCOMES.get(LEADING_CODE.exec(text)?.[1] ?? "");
179
+ if (byCode)
180
+ return byCode;
181
+ for (const [outcome, pattern] of OUTCOME_PATTERNS)
182
+ if (pattern.test(text))
183
+ return outcome;
184
+ return didThrow ? "error_internal" : "error_other";
185
+ }
186
+ /** Error excerpt: allowlisted fragments of the error text, masked (port of the Ask Ads gateway's). */
187
+ export const DETAIL_MAX = 200;
188
+ const PICK = /\bHTTP (?<http>\d{3})\b(?::\s*(?<htext>[^{[]{1,200}))?|^(?:Ошибка: )?\[(?<bcode>\d{1,5})\]\s*(?<btext>[^;(]{1,200})|\[(?<tag>[A-Za-z][A-Za-z_]{2,})\]\s*(?<ttext>[^;(]{0,200})|\berror_code["']?\s*[:=]\s*["']?(?<code>\d{1,5})\b|\b(?<key>error_string|error_detail|error_type|message)["']?\s*[:=]\s*["']?(?<value>[^"'}\]]{1,80})|\b(?<net>ECONNRESET|ECONNREFUSED|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|timed out|fetch failed|socket hang up|connection closed)\b|(?<netru>превысил таймаут)/gi;
189
+ const SCRUB = /(?<key>(?:login|password|secret|token|api[_-]?key|authorization)\s*[:=]\s*["']?|(?:bearer|basic)\s+)(?<val>[^,;]+)|[^\s,;]*(?:@|:\/\/|%3A|\p{L}\.\p{L})[^\s,;]*|(?<key2>\b(?:token|secret|password|api[_-]?key|access_token|refresh_token|client_secret)\s+)(?!(?:expired|invalid|is|was|for|has|not|missing|required|revoked|provided|type)\b)\S+|\b(?:y0_|AQAA|AQVN|t1\.|sk-|vk1\.|vk_|ghp_|ya29\.)\S+|\b(?=[\w-]*\d)(?=[\w-]*[A-Za-z])[\w-]{20,}\b|\+?\d(?:[\s().-]*\d){3,}/giu;
190
+ const QUOTED = /(?<!\p{L})'[^'\n]+(?:'(?!\p{L})|$)|"[^"\n]+(?:"|$)|«[^»]+(?:»|$)/gu;
191
+ function scrub(value, quoted = true) {
192
+ return (quoted ? value.replace(QUOTED, "#") : value)
193
+ .replace(SCRUB, (...args) => {
194
+ const groups = args[args.length - 1];
195
+ return (groups.key ?? groups.key2 ?? "") + "#";
196
+ })
197
+ .replace(/^[ ;:,.]+|[ ;:,.]+$/g, "");
198
+ }
199
+ export function errorDetail(text) {
200
+ const flat = text.slice(0, 2000).split(/\s+/).filter(Boolean).join(" ");
201
+ const parts = [];
202
+ PICK.lastIndex = 0;
203
+ for (let m = PICK.exec(flat); m; m = PICK.exec(flat)) {
204
+ const g = m.groups ?? {};
205
+ let token;
206
+ if (g.http)
207
+ token = `HTTP ${g.http} ${scrub(g.htext ?? "")}`;
208
+ else if (g.bcode)
209
+ token = `code=${g.bcode} ${scrub(g.btext ?? "")}`;
210
+ else if (g.tag) {
211
+ // Tags are upper-case only; the rest of PICK is case-insensitive.
212
+ if (!/^[A-Z][A-Z_]{2,}$/.test(g.tag)) {
213
+ PICK.lastIndex = m.index + 1;
214
+ continue;
215
+ }
216
+ token = `${g.tag} ${scrub(g.ttext ?? "")}`;
217
+ }
218
+ else if (g.code)
219
+ token = `code=${g.code}`;
220
+ else if (g.key)
221
+ token = `${g.key.toLowerCase()}=${scrub(g.value ?? "")}`;
222
+ else
223
+ token = (g.net ?? g.netru ?? "").toLowerCase();
224
+ token = token.trim();
225
+ if (!parts.includes(token))
226
+ parts.push(token);
227
+ }
228
+ return parts.join("; ").slice(0, DETAIL_MAX);
229
+ }
230
+ /** Set by fail(), never serialized: our own refusal ("local"), a bug in our code ("internal") or a failed fetch ("network"). */
231
+ const FAILURE_ORIGIN = new WeakMap();
232
+ const JS_ERRORS = new Set(["TypeError", "ReferenceError", "RangeError", "SyntaxError", "EvalError", "URIError"]);
233
+ function jsBug(err) {
234
+ return err instanceof Error && JS_ERRORS.has(err.name) ? `${err.name}: ${err.message.split("\n")[0]}` : undefined;
235
+ }
236
+ /**
237
+ * Node's fetch rejects a network failure as TypeError("fetch failed") with the socket/DNS/TLS error
238
+ * in `cause`. Only cause.code leaves the machine: cause.message names hosts and addresses.
239
+ */
240
+ function fetchFailure(err) {
241
+ if (!(err instanceof Error) || err.name !== "TypeError" || err.message !== "fetch failed")
242
+ return undefined;
243
+ const cause = err.cause;
244
+ if (!cause || typeof cause !== "object")
245
+ return undefined;
246
+ const raw = cause.code;
247
+ const code = typeof raw === "string" && /^[A-Z][A-Z0-9_]{2,40}$/.test(raw) ? raw : "";
248
+ return {
249
+ reason: /TIMEOUT|TIMEDOUT/.test(code) ? "error_timeout" : "error_network",
250
+ text: code ? `fetch failed; ${code.toLowerCase()}` : "fetch failed",
251
+ };
252
+ }
253
+ export function noteFailure(result, err) {
254
+ try {
255
+ if (result && typeof result === "object") {
256
+ const net = fetchFailure(err);
257
+ if (typeof err === "string")
258
+ FAILURE_ORIGIN.set(result, { origin: "local", text: err });
259
+ else if (net)
260
+ FAILURE_ORIGIN.set(result, { origin: "network", ...net });
261
+ else {
262
+ const bug = jsBug(err);
263
+ if (bug)
264
+ FAILURE_ORIGIN.set(result, { origin: "internal", text: bug });
265
+ }
266
+ }
267
+ }
268
+ catch {
269
+ // never affects the result
270
+ }
271
+ return result;
272
+ }
273
+ /** A JS error quotes identifiers of our code, not user data, so its quotes are kept. */
274
+ function maskedOwnText(prefix, text, quoted = true) {
275
+ return (prefix + scrub(text.slice(0, 2 * DETAIL_MAX).split(/\s+/).filter(Boolean).join(" "), quoted)).slice(0, DETAIL_MAX);
276
+ }
277
+ /** Best effort: classifying or sending must never change what the tool returns or throws. */
278
+ function reportCall(telemetry, tool, value, thrown) {
279
+ if (!telemetry.isEnabled())
280
+ return;
281
+ try {
282
+ let reason = thrown ? toolOutcome(undefined, value) : toolOutcome(value);
283
+ let detail = "";
284
+ if (reason !== "ok") {
285
+ const noted = value && typeof value === "object" ? FAILURE_ORIGIN.get(value) : undefined;
286
+ const net = noted?.origin === "network" ? noted : thrown ? fetchFailure(value) : undefined;
287
+ const bug = noted?.origin === "internal" ? noted.text : thrown ? jsBug(value) : undefined;
288
+ if (net) {
289
+ reason = net.reason;
290
+ detail = net.text;
291
+ }
292
+ else if (bug) {
293
+ reason = "error_internal";
294
+ detail = maskedOwnText("internal: ", bug, false);
295
+ }
296
+ else if (noted?.origin === "local") {
297
+ reason = "error_invalid_request";
298
+ detail = maskedOwnText("local: ", noted.text);
299
+ }
300
+ else
301
+ detail = errorDetail(resultText(value));
302
+ }
303
+ telemetry.send("tool_call", { tool, reason, error_detail: detail || undefined });
304
+ }
305
+ catch {
306
+ // never affects the call
307
+ }
308
+ }
107
309
  /**
108
- * Count every tool invocation by name. Wraps registerTool once, before the
109
- * domain modules register their tools, so no per-tool wiring is needed.
110
- * Only the tool *name* is recorded — arguments never reach telemetry.
310
+ * Counts every tool call by name and outcome. Wraps registerTool once, before the domain
311
+ * modules register their tools. Calls rejected by SDK input validation are not counted.
111
312
  */
112
313
  export function instrumentToolCalls(server, telemetry) {
113
314
  const original = server.registerTool.bind(server);
114
315
  // registerTool's generic signature does not survive a wrapper; the runtime
115
316
  // shape (name, config, callback) is stable per SDK contract.
116
- server.registerTool = ((name, config, callback) => original(name, config, ((...args) => {
117
- telemetry.send("tool_call", { tool: name });
118
- return callback(...args);
317
+ server.registerTool = ((name, config, callback) => original(name, config, (async (...args) => {
318
+ let result;
319
+ try {
320
+ result = await callback(...args);
321
+ }
322
+ catch (e) {
323
+ reportCall(telemetry, name, e, true);
324
+ throw e;
325
+ }
326
+ reportCall(telemetry, name, result, false);
327
+ return result;
119
328
  })));
120
329
  }
@@ -0,0 +1,114 @@
1
+ import { OAuthError, registerGoogleAuth, TokenProvider, unconfiguredPrefix, USERINFO_URL, } from "@a1-x-tech/mcp-google-auth";
2
+ import { probeApi } from "../client.js";
3
+ import { TagManagerError } from "../types.js";
4
+ /**
5
+ * The scopes an in-chat login requests (the per-task table lives in
6
+ * docs/TOOLS.md). The component always adds the identity scopes on top. Tag Manager splits editing and publishing: the edit scope covers workspaces, tags and versions, the publish scope is what actually pushes a version live.
7
+ */
8
+ export const LOGIN_SCOPES = [
9
+ "https://www.googleapis.com/auth/tagmanager.edit.containers",
10
+ "https://www.googleapis.com/auth/tagmanager.publish",
11
+ ];
12
+ /**
13
+ * True when a Google API error body says the API itself is switched off in the
14
+ * caller's Cloud project. Google reports this two ways at once and has been
15
+ * migrating between them: the legacy `error.errors[].reason` is
16
+ * `accessNotConfigured`, the newer `error.details[].reason` is
17
+ * `SERVICE_DISABLED`. Either spelling means the same fix, so both are matched.
18
+ */
19
+ function isApiDisabled(body) {
20
+ if (typeof body !== "object" || body === null)
21
+ return false;
22
+ const error = body.error;
23
+ if (typeof error !== "object" || error === null)
24
+ return false;
25
+ const reasons = new Set();
26
+ for (const key of ["errors", "details"]) {
27
+ const list = error[key];
28
+ if (Array.isArray(list)) {
29
+ for (const entry of list) {
30
+ if (typeof entry === "object" && entry !== null) {
31
+ reasons.add(entry.reason);
32
+ }
33
+ }
34
+ }
35
+ }
36
+ return reasons.has("accessNotConfigured") || reasons.has("SERVICE_DISABLED");
37
+ }
38
+ /**
39
+ * `verifyIdentity` for the component: one cheap Google Tag Manager read, plus the
40
+ * translation the component cannot do itself. An API that is not enabled in the
41
+ * user's Cloud project answers the first call with HTTP 403 — the most likely
42
+ * failure right after a login — as a bare error reading "PERMISSION_DENIED",
43
+ * which sends the user to check permissions they cannot fix. Re-thrown as
44
+ * `OAuthError("accessNotConfigured")` it becomes the real advice: enable the
45
+ * API in the SAME project as the OAuth client.
46
+ *
47
+ * Checking the product API (rather than the component's default OIDC userinfo)
48
+ * is the point: OIDC answers even when Tag Manager API is switched off, so a
49
+ * login would look successful and the first real tool call would fail instead.
50
+ */
51
+ async function verifyIdentity(accessToken) {
52
+ try {
53
+ await probeApi(accessToken);
54
+ }
55
+ catch (error) {
56
+ if (error instanceof TagManagerError && error.status === 403 && isApiDisabled(error.body)) {
57
+ throw new OAuthError("accessNotConfigured", "Tag Manager API", error.status);
58
+ }
59
+ throw error;
60
+ }
61
+ return { email: await accountEmail(accessToken) };
62
+ }
63
+ /**
64
+ * The account label shown after a login. Best-effort on purpose: the connection
65
+ * is already proven by the probe above, and failing the whole login over a
66
+ * cosmetic label would be wrong.
67
+ */
68
+ async function accountEmail(accessToken) {
69
+ try {
70
+ const res = await fetch(USERINFO_URL, {
71
+ headers: { Authorization: `Bearer ${accessToken}` },
72
+ signal: AbortSignal.timeout(10_000),
73
+ });
74
+ if (!res.ok)
75
+ return undefined;
76
+ const data = await res.json();
77
+ const email = data.email;
78
+ return typeof email === "string" ? email : undefined;
79
+ }
80
+ catch {
81
+ return undefined;
82
+ }
83
+ }
84
+ /**
85
+ * The single source of the auth wiring: serverName "tagmanager" puts the stored
86
+ * login in ~/.config/mcp-google-tagmanager/credentials.json (the component
87
+ * prefixes "mcp-google-"), envPrefix keeps the provider reading the exact
88
+ * GOOGLE_TAGMANAGER_* variables config.ts documents — which is what preserves the
89
+ * env-beats-stored priority for existing installs.
90
+ */
91
+ export const AUTH_OPTIONS = {
92
+ serverName: "tagmanager",
93
+ envPrefix: "GOOGLE_TAGMANAGER",
94
+ scopes: LOGIN_SCOPES,
95
+ verifyIdentity,
96
+ };
97
+ /**
98
+ * Registers the six onboarding tools (auth_status, setup_instructions,
99
+ * set_client, start_login, finish_login, logout) and returns the TokenProvider
100
+ * the client plugs in as its fallback token source — the same instance, so a
101
+ * login finished mid-session is visible to the very next API call without a
102
+ * restart.
103
+ */
104
+ export function registerAuthTools(server) {
105
+ return registerGoogleAuth(server, AUTH_OPTIONS);
106
+ }
107
+ /** True when any token exists — env variables or a stored in-chat login. */
108
+ export function hasAuthToken() {
109
+ return new TokenProvider(AUTH_OPTIONS).hasToken();
110
+ }
111
+ /** The "NOT CONNECTED" prefix for the initialize instructions (names both fixes). */
112
+ export function authUnconfiguredPrefix() {
113
+ return unconfiguredPrefix(AUTH_OPTIONS);
114
+ }
@@ -1,10 +1,15 @@
1
1
  import { z } from "zod";
2
+ import { noteFailure } from "../telemetry.js";
2
3
  /** Wraps a value as a compact-JSON tool result (compact: the consumer is an LLM). */
3
4
  export function ok(data) {
4
5
  const text = typeof data === "string" ? data : JSON.stringify(data);
5
6
  return { content: [{ type: "text", text: text ?? "null" }] };
6
7
  }
8
+ /** The failed result; also notes, off the wire, whether it is our own refusal or a JS bug (telemetry). */
7
9
  export function fail(err) {
10
+ return noteFailure(failText(err), err);
11
+ }
12
+ function failText(err) {
8
13
  let message = err instanceof Error ? err.message : String(err);
9
14
  // Surface the underlying cause (e.g. the network error behind a timeout) — no
10
15
  // secrets live in cause, and it makes failures far easier to diagnose.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mcp-google-tagmanager",
3
- "version": "1.1.0",
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.",
3
+ "version": "1.3.0",
4
+ "description": "MCP server for the Google Tag Manager API v2 \u2014 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",
7
7
  "bin": {
@@ -51,6 +51,7 @@
51
51
  "url": "https://github.com/A1-x-Tech/mcp-google-tagmanager/issues"
52
52
  },
53
53
  "dependencies": {
54
+ "@a1-x-tech/mcp-google-auth": "^0.1.0",
54
55
  "@modelcontextprotocol/sdk": "^1.29.0",
55
56
  "zod": "^3.25.0"
56
57
  },
@@ -1,6 +1,9 @@
1
1
  // Tests the built artifact in dist/ — the exact files that ship to npm.
2
2
  // Plain JS on purpose: no tsx loader between the test and the artifact.
3
3
  import assert from "node:assert/strict";
4
+ import { mkdtempSync, rmSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
4
7
  import { fileURLToPath } from "node:url";
5
8
  import test from "node:test";
6
9
 
@@ -9,12 +12,19 @@ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
9
12
 
10
13
  import { TagManagerClient } from "../dist/client.js";
11
14
 
15
+ /**
16
+ * Sorted, because every assertion compares it against a sorted tool list. The
17
+ * six onboarding tools come from @a1-x-tech/mcp-google-auth, so this list is
18
+ * also the check that the component is wired into the published binary.
19
+ */
12
20
  const ALL_TOOLS = [
21
+ "auth_status",
13
22
  "create_container",
14
23
  "create_entity",
15
24
  "create_version",
16
25
  "create_workspace",
17
26
  "delete_entity",
27
+ "finish_login",
18
28
  "get_account",
19
29
  "get_container",
20
30
  "get_resource",
@@ -25,13 +35,30 @@ const ALL_TOOLS = [
25
35
  "list_triggers",
26
36
  "list_variables",
27
37
  "list_workspaces",
38
+ "logout",
28
39
  "manage_built_in_variables",
29
40
  "publish_version",
30
41
  "raw_request",
42
+ "set_client",
43
+ "setup_instructions",
44
+ "start_login",
31
45
  "update_entity",
32
46
  ];
33
47
 
34
- test("dist binary completes a real MCP handshake over stdio and lists every tool", async () => {
48
+ /**
49
+ * A throwaway $XDG_CONFIG_HOME for the spawned server. The auth component
50
+ * re-reads $XDG_CONFIG_HOME/mcp-google-tagmanager/credentials.json per call, so
51
+ * without this a real login on the developer's machine would make the
52
+ * "unconfigured" case pass for the wrong reason.
53
+ */
54
+ function isolatedConfigDir(t) {
55
+ const dir = mkdtempSync(join(tmpdir(), "mcp-tagmanager-dist-smoke-"));
56
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
57
+ return dir;
58
+ }
59
+
60
+
61
+ test("dist binary completes a real MCP handshake over stdio and lists every tool", async (t) => {
35
62
  const transport = new StdioClientTransport({
36
63
  command: process.execPath,
37
64
  args: [fileURLToPath(new URL("../dist/index.js", import.meta.url))],
@@ -73,13 +100,14 @@ test("dist binary completes a real MCP handshake over stdio and lists every tool
73
100
  * answer a tool call with the actionable error — offline: the CredentialsError
74
101
  * fires before any fetch, so this test never touches the network.
75
102
  */
76
- test("dist binary starts without credentials: handshake, tool list, actionable call error", async () => {
103
+ test("dist binary starts without credentials: handshake, tool list, actionable call error", async (t) => {
77
104
  const env = Object.fromEntries(
78
105
  Object.entries(process.env).filter(
79
106
  ([key, value]) => value !== undefined && !key.startsWith("GOOGLE_TAGMANAGER_"),
80
107
  ),
81
108
  );
82
109
  env.ASKADS_TELEMETRY = "0"; // keep the suite offline
110
+ env.XDG_CONFIG_HOME = isolatedConfigDir(t); // ignore any real login on this machine
83
111
  const transport = new StdioClientTransport({
84
112
  command: process.execPath,
85
113
  args: [fileURLToPath(new URL("../dist/index.js", import.meta.url))],
@@ -91,7 +119,8 @@ test("dist binary starts without credentials: handshake, tool list, actionable c
91
119
  try {
92
120
  // The model must read the fix before it picks a tool.
93
121
  const instructions = client.getInstructions() ?? "";
94
- assert.match(instructions, /not connected/);
122
+ assert.match(instructions, /NOT CONNECTED/);
123
+ assert.match(instructions, /start_login/);
95
124
  assert.match(instructions, /GOOGLE_TAGMANAGER_CLIENT_ID/);
96
125
  assert.match(instructions, /restart/);
97
126
 
@@ -102,7 +131,11 @@ test("dist binary starts without credentials: handshake, tool list, actionable c
102
131
  const result = await client.callTool({ name: "list_accounts", arguments: {} });
103
132
  assert.equal(result.isError, true);
104
133
  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\)\./);
134
+ // Both fixes must be named: the in-chat login (no restart) and the
135
+ // environment variables (restart).
136
+ assert.match(text, /not connected/i);
137
+ assert.match(text, /start_login/);
138
+ assert.match(text, /GOOGLE_TAGMANAGER_CLIENT_ID/);
106
139
  assert.match(text, /restart the server/);
107
140
  } finally {
108
141
  await client.close();