mcp-google-tagmanager 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +222 -0
- package/dist/auth.js +86 -0
- package/dist/builtin-variable-types.js +126 -0
- package/dist/client.js +242 -0
- package/dist/config.js +70 -0
- package/dist/index.js +57 -0
- package/dist/tools/accounts.js +33 -0
- package/dist/tools/builtins.js +39 -0
- package/dist/tools/containers.js +56 -0
- package/dist/tools/entities.js +117 -0
- package/dist/tools/raw.js +31 -0
- package/dist/tools/util.js +52 -0
- package/dist/tools/versions.js +78 -0
- package/dist/tools/workspaces.js +56 -0
- package/dist/types.js +86 -0
- package/package.json +62 -0
- package/test/dist-smoke.test.js +94 -0
package/dist/client.js
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import { TokenProvider } from "./auth.js";
|
|
2
|
+
import { isQuotaError, TagManagerError } from "./types.js";
|
|
3
|
+
const ENTITY_COLLECTION = {
|
|
4
|
+
tag: "tags",
|
|
5
|
+
trigger: "triggers",
|
|
6
|
+
variable: "variables",
|
|
7
|
+
};
|
|
8
|
+
/** Builds the API-relative workspace path GTM v2 uses to address everything inside a workspace. */
|
|
9
|
+
export function workspacePath(accountId, containerId, workspaceId) {
|
|
10
|
+
return `accounts/${accountId}/containers/${containerId}/workspaces/${workspaceId}`;
|
|
11
|
+
}
|
|
12
|
+
export class TagManagerClient {
|
|
13
|
+
config;
|
|
14
|
+
base;
|
|
15
|
+
timeoutMs;
|
|
16
|
+
maxRetries;
|
|
17
|
+
retryBaseMs;
|
|
18
|
+
minIntervalMs;
|
|
19
|
+
tokens;
|
|
20
|
+
/**
|
|
21
|
+
* Rate limiter state. GTM allows 0.25 QPS per project (25 requests / 100 s
|
|
22
|
+
* sliding window), so every API request is serialized through this queue and
|
|
23
|
+
* spaced at least minIntervalMs apart — including retry attempts.
|
|
24
|
+
*/
|
|
25
|
+
queue = Promise.resolve();
|
|
26
|
+
lastStartAt = 0;
|
|
27
|
+
constructor(config, tokens) {
|
|
28
|
+
this.config = config;
|
|
29
|
+
const root = config.apiBase.endsWith("/") ? config.apiBase : config.apiBase + "/";
|
|
30
|
+
this.base = root + "tagmanager/v2/";
|
|
31
|
+
this.timeoutMs = config.timeoutMs ?? 60_000;
|
|
32
|
+
this.maxRetries = config.maxRetries ?? 3;
|
|
33
|
+
this.retryBaseMs = config.retryBaseMs ?? 1_000;
|
|
34
|
+
this.minIntervalMs = config.minIntervalMs ?? 4_200;
|
|
35
|
+
this.tokens = tokens ?? new TokenProvider(config);
|
|
36
|
+
}
|
|
37
|
+
/** Backoff before a retry: honors Retry-After when present, else exponential (capped at 30s). */
|
|
38
|
+
backoffMs(attempt, res) {
|
|
39
|
+
const retryAfter = res ? Number(res.headers.get("Retry-After")) : NaN;
|
|
40
|
+
if (Number.isFinite(retryAfter) && retryAfter > 0)
|
|
41
|
+
return Math.min(retryAfter, 30) * 1000;
|
|
42
|
+
return Math.min(this.retryBaseMs * 2 ** attempt, 30_000);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Waits until the previous request started at least minIntervalMs ago. Only
|
|
46
|
+
* ever runs inside the serialized queue, so there is no race on lastStartAt.
|
|
47
|
+
*/
|
|
48
|
+
async throttle() {
|
|
49
|
+
const wait = this.lastStartAt + this.minIntervalMs - Date.now();
|
|
50
|
+
if (wait > 0)
|
|
51
|
+
await delay(wait);
|
|
52
|
+
this.lastStartAt = Date.now();
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* fetch with an AbortController timeout. Reads the response body inside the
|
|
56
|
+
* guarded zone so the timeout also covers a slow or drip-feeding body, not
|
|
57
|
+
* just the initial headers.
|
|
58
|
+
*/
|
|
59
|
+
async fetchWithTimeout(url, init, label) {
|
|
60
|
+
const controller = new AbortController();
|
|
61
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
62
|
+
try {
|
|
63
|
+
const res = await fetch(url, { ...init, signal: controller.signal });
|
|
64
|
+
const text = await res.text();
|
|
65
|
+
return { res, text };
|
|
66
|
+
}
|
|
67
|
+
catch (err) {
|
|
68
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
69
|
+
throw new Error(`Request to "${label}" timed out after ${this.timeoutMs}ms`);
|
|
70
|
+
}
|
|
71
|
+
throw err;
|
|
72
|
+
}
|
|
73
|
+
finally {
|
|
74
|
+
clearTimeout(timer);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Low-level request to a GTM v2 path relative to /tagmanager/v2/
|
|
79
|
+
* (e.g. "accounts/1/containers/2/workspaces/3/tags"). All requests are
|
|
80
|
+
* serialized and spaced ≥ minIntervalMs apart (0.25 QPS quota). Retries
|
|
81
|
+
* 429 and quota-403 for every method; 5xx and network errors/timeouts only
|
|
82
|
+
* for GET (a write that already committed must not be replayed). Any other
|
|
83
|
+
* non-2xx throws a {@link TagManagerError}.
|
|
84
|
+
*/
|
|
85
|
+
async request(method, path, opts = {}) {
|
|
86
|
+
// Resolve the path against the API base, then reject anything that escaped
|
|
87
|
+
// to a foreign origin (an absolute "https://evil/x" or a "\\evil/x" slipped
|
|
88
|
+
// through raw_request) so the Bearer token can never leak to another host.
|
|
89
|
+
const url = new URL(path.replace(/^\//, ""), this.base);
|
|
90
|
+
if (url.origin !== new URL(this.base).origin) {
|
|
91
|
+
throw new Error(`raw_request path must be a relative API path (resolved to foreign origin ${url.origin})`);
|
|
92
|
+
}
|
|
93
|
+
for (const [key, value] of Object.entries(opts.query ?? {})) {
|
|
94
|
+
if (value === undefined)
|
|
95
|
+
continue;
|
|
96
|
+
for (const v of Array.isArray(value) ? value : [value])
|
|
97
|
+
url.searchParams.append(key, v);
|
|
98
|
+
}
|
|
99
|
+
const target = url.toString();
|
|
100
|
+
// Serialize through the rate-limiter queue; a failed request must not wedge it.
|
|
101
|
+
const run = this.queue.then(() => this.perform(method, target, path, opts.body));
|
|
102
|
+
this.queue = run.then(() => undefined, () => undefined);
|
|
103
|
+
return run;
|
|
104
|
+
}
|
|
105
|
+
async perform(method, target, label, body) {
|
|
106
|
+
// Guard method !== "GET" keeps undici from crashing on a GET-with-body.
|
|
107
|
+
const hasBody = body !== undefined && method !== "GET";
|
|
108
|
+
const idempotent = method === "GET";
|
|
109
|
+
for (let attempt = 0;; attempt++) {
|
|
110
|
+
// The token exchange happens outside the throttle window: it goes to
|
|
111
|
+
// oauth2.googleapis.com and does not count against the GTM quota.
|
|
112
|
+
const token = await this.tokens.getAccessToken();
|
|
113
|
+
await this.throttle();
|
|
114
|
+
const headers = { Authorization: `Bearer ${token}` };
|
|
115
|
+
if (hasBody)
|
|
116
|
+
headers["Content-Type"] = "application/json";
|
|
117
|
+
let res;
|
|
118
|
+
let text;
|
|
119
|
+
try {
|
|
120
|
+
({ res, text } = await this.fetchWithTimeout(target, { method, headers, body: hasBody ? JSON.stringify(body) : undefined }, label));
|
|
121
|
+
}
|
|
122
|
+
catch (err) {
|
|
123
|
+
// Network error or timeout: retry reads with backoff; a write may have
|
|
124
|
+
// reached the server, so rethrow it as-is.
|
|
125
|
+
if (idempotent && attempt < this.maxRetries) {
|
|
126
|
+
await delay(this.backoffMs(attempt));
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
throw err;
|
|
130
|
+
}
|
|
131
|
+
let data = undefined;
|
|
132
|
+
if (text) {
|
|
133
|
+
try {
|
|
134
|
+
data = JSON.parse(text);
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
data = text;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
// 429 and quota-403 mean "not executed, slow down" — retryable for every
|
|
141
|
+
// method. 5xx is retried only for reads.
|
|
142
|
+
const rateLimited = res.status === 429 || (res.status === 403 && isQuotaError(data));
|
|
143
|
+
const transient = rateLimited || (idempotent && res.status >= 500 && res.status < 600);
|
|
144
|
+
if (transient && attempt < this.maxRetries) {
|
|
145
|
+
await delay(this.backoffMs(attempt, res));
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
if (!res.ok)
|
|
149
|
+
throw new TagManagerError(res.status, data);
|
|
150
|
+
return data;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
// --- Accounts ---
|
|
154
|
+
/** Lists all GTM accounts the authorized user can access. */
|
|
155
|
+
async listAccounts(pageToken) {
|
|
156
|
+
return this.request("GET", "accounts", { query: { pageToken } });
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Generic GET of any resource by its API-relative path — accounts, containers,
|
|
160
|
+
* workspaces, tags, triggers, variables and versions all share this shape.
|
|
161
|
+
*/
|
|
162
|
+
async getResource(path) {
|
|
163
|
+
return this.request("GET", path);
|
|
164
|
+
}
|
|
165
|
+
// --- Containers ---
|
|
166
|
+
async listContainers(accountId, pageToken) {
|
|
167
|
+
return this.request("GET", `accounts/${accountId}/containers`, { query: { pageToken } });
|
|
168
|
+
}
|
|
169
|
+
async createContainer(accountId, body) {
|
|
170
|
+
return this.request("POST", `accounts/${accountId}/containers`, { body });
|
|
171
|
+
}
|
|
172
|
+
// --- Workspaces ---
|
|
173
|
+
async listWorkspaces(accountId, containerId, pageToken) {
|
|
174
|
+
return this.request("GET", `accounts/${accountId}/containers/${containerId}/workspaces`, {
|
|
175
|
+
query: { pageToken },
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
async createWorkspace(accountId, containerId, body) {
|
|
179
|
+
return this.request("POST", `accounts/${accountId}/containers/${containerId}/workspaces`, {
|
|
180
|
+
body: compact(body),
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
// --- Tags / triggers / variables ---
|
|
184
|
+
async listEntities(accountId, containerId, workspaceId, kind, pageToken) {
|
|
185
|
+
const parent = workspacePath(accountId, containerId, workspaceId);
|
|
186
|
+
return this.request("GET", `${parent}/${ENTITY_COLLECTION[kind]}`, { query: { pageToken } });
|
|
187
|
+
}
|
|
188
|
+
async createEntity(accountId, containerId, workspaceId, kind, body) {
|
|
189
|
+
const parent = workspacePath(accountId, containerId, workspaceId);
|
|
190
|
+
return this.request("POST", `${parent}/${ENTITY_COLLECTION[kind]}`, { body });
|
|
191
|
+
}
|
|
192
|
+
/** Full replace (PUT, not PATCH): send the complete resource back. */
|
|
193
|
+
async updateEntity(path, body, fingerprint) {
|
|
194
|
+
return this.request("PUT", path, { query: { fingerprint }, body });
|
|
195
|
+
}
|
|
196
|
+
async deleteEntity(path) {
|
|
197
|
+
return this.request("DELETE", path);
|
|
198
|
+
}
|
|
199
|
+
// --- Built-in variables ---
|
|
200
|
+
async listBuiltInVariables(accountId, containerId, workspaceId) {
|
|
201
|
+
const parent = workspacePath(accountId, containerId, workspaceId);
|
|
202
|
+
return this.request("GET", `${parent}/built_in_variables`);
|
|
203
|
+
}
|
|
204
|
+
/** Enable: POST with repeated ?type= query params and an empty body. */
|
|
205
|
+
async enableBuiltInVariables(accountId, containerId, workspaceId, types) {
|
|
206
|
+
const parent = workspacePath(accountId, containerId, workspaceId);
|
|
207
|
+
return this.request("POST", `${parent}/built_in_variables`, { query: { type: types } });
|
|
208
|
+
}
|
|
209
|
+
/** Disable: DELETE with repeated ?type= query params. */
|
|
210
|
+
async disableBuiltInVariables(accountId, containerId, workspaceId, types) {
|
|
211
|
+
const parent = workspacePath(accountId, containerId, workspaceId);
|
|
212
|
+
return this.request("DELETE", `${parent}/built_in_variables`, { query: { type: types } });
|
|
213
|
+
}
|
|
214
|
+
// --- Versions & publishing ---
|
|
215
|
+
/**
|
|
216
|
+
* Compiles the workspace into a Container Version. Mind the side effect: the
|
|
217
|
+
* workspace is DELETED and replaced (response carries newWorkspacePath), and
|
|
218
|
+
* a compile failure arrives as compilerError=true with HTTP 200.
|
|
219
|
+
*/
|
|
220
|
+
async createVersion(accountId, containerId, workspaceId, body) {
|
|
221
|
+
const path = workspacePath(accountId, containerId, workspaceId);
|
|
222
|
+
return this.request("POST", `${path}:create_version`, { body: compact(body) });
|
|
223
|
+
}
|
|
224
|
+
async publishVersion(accountId, containerId, versionId, fingerprint) {
|
|
225
|
+
const path = `accounts/${accountId}/containers/${containerId}/versions/${versionId}`;
|
|
226
|
+
return this.request("POST", `${path}:publish`, { query: { fingerprint } });
|
|
227
|
+
}
|
|
228
|
+
async getVersion(accountId, containerId, versionId) {
|
|
229
|
+
return this.request("GET", `accounts/${accountId}/containers/${containerId}/versions/${versionId}`);
|
|
230
|
+
}
|
|
231
|
+
/** The currently published (live) version of a container. */
|
|
232
|
+
async liveVersion(accountId, containerId) {
|
|
233
|
+
return this.request("GET", `accounts/${accountId}/containers/${containerId}/versions:live`);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
/** Drops keys whose value is `undefined` so they are not sent to the API. */
|
|
237
|
+
function compact(obj) {
|
|
238
|
+
return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined));
|
|
239
|
+
}
|
|
240
|
+
function delay(ms) {
|
|
241
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
242
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/** Default Google Tag Manager API host. */
|
|
2
|
+
const DEFAULT_BASE = "https://tagmanager.googleapis.com";
|
|
3
|
+
/**
|
|
4
|
+
* GTM enforces 0.25 QPS per project (25 requests / 100 s sliding window), so
|
|
5
|
+
* requests are spaced at least this far apart by default: 100_000 ms / 25 = 4_000,
|
|
6
|
+
* plus a small safety margin.
|
|
7
|
+
*/
|
|
8
|
+
const DEFAULT_MIN_INTERVAL_MS = 4_200;
|
|
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).
|
|
13
|
+
*/
|
|
14
|
+
export class ConfigError extends Error {
|
|
15
|
+
reason;
|
|
16
|
+
constructor(message, reason) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = "ConfigError";
|
|
19
|
+
this.reason = reason;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function die(message, reason) {
|
|
23
|
+
throw new ConfigError(message, reason);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Builds the client config from environment variables, throwing ConfigError if
|
|
27
|
+
* a required one is missing.
|
|
28
|
+
*
|
|
29
|
+
* Two auth modes:
|
|
30
|
+
* GOOGLE_TAGMANAGER_ACCESS_TOKEN ready-made OAuth access token (quick sessions;
|
|
31
|
+
* expires in ~1 hour, no auto-refresh)
|
|
32
|
+
* GOOGLE_TAGMANAGER_CLIENT_ID / _CLIENT_SECRET / refresh-token flow: the server exchanges the
|
|
33
|
+
* GOOGLE_TAGMANAGER_REFRESH_TOKEN refresh token for access tokens itself (recommended)
|
|
34
|
+
*
|
|
35
|
+
* Optional:
|
|
36
|
+
* GOOGLE_TAGMANAGER_API_BASE API root override (default https://tagmanager.googleapis.com)
|
|
37
|
+
* GOOGLE_TAGMANAGER_TIMEOUT_MS per-request timeout (default 60000)
|
|
38
|
+
* GOOGLE_TAGMANAGER_MAX_RETRIES retries on transient errors (default 3)
|
|
39
|
+
* GOOGLE_TAGMANAGER_MIN_INTERVAL_MS min spacing between API requests (default 4200)
|
|
40
|
+
*/
|
|
41
|
+
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) {
|
|
47
|
+
if (!clientId) {
|
|
48
|
+
die("GOOGLE_TAGMANAGER_CLIENT_ID is required (OAuth client id; or set GOOGLE_TAGMANAGER_ACCESS_TOKEN directly).", "missing_client_id");
|
|
49
|
+
}
|
|
50
|
+
if (!clientSecret) {
|
|
51
|
+
die("GOOGLE_TAGMANAGER_CLIENT_SECRET is required (OAuth client secret).", "missing_client_secret");
|
|
52
|
+
}
|
|
53
|
+
if (!refreshToken) {
|
|
54
|
+
die("GOOGLE_TAGMANAGER_REFRESH_TOKEN is required (OAuth refresh token).", "missing_refresh_token");
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const timeoutMs = Number(process.env.GOOGLE_TAGMANAGER_TIMEOUT_MS);
|
|
58
|
+
const maxRetries = Number(process.env.GOOGLE_TAGMANAGER_MAX_RETRIES);
|
|
59
|
+
const minIntervalMs = Number(process.env.GOOGLE_TAGMANAGER_MIN_INTERVAL_MS);
|
|
60
|
+
return {
|
|
61
|
+
accessToken,
|
|
62
|
+
clientId,
|
|
63
|
+
clientSecret,
|
|
64
|
+
refreshToken,
|
|
65
|
+
apiBase: process.env.GOOGLE_TAGMANAGER_API_BASE || DEFAULT_BASE,
|
|
66
|
+
timeoutMs: Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 60_000,
|
|
67
|
+
maxRetries: Number.isFinite(maxRetries) && maxRetries >= 0 ? maxRetries : 3,
|
|
68
|
+
minIntervalMs: Number.isFinite(minIntervalMs) && minIntervalMs >= 0 ? minIntervalMs : DEFAULT_MIN_INTERVAL_MS,
|
|
69
|
+
};
|
|
70
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
5
|
+
import { TagManagerClient } from "./client.js";
|
|
6
|
+
import { ConfigError, loadConfig } from "./config.js";
|
|
7
|
+
import { registerAccountTools } from "./tools/accounts.js";
|
|
8
|
+
import { registerBuiltInVariableTools } from "./tools/builtins.js";
|
|
9
|
+
import { registerContainerTools } from "./tools/containers.js";
|
|
10
|
+
import { registerEntityTools } from "./tools/entities.js";
|
|
11
|
+
import { registerRawTool } from "./tools/raw.js";
|
|
12
|
+
import { registerVersionTools } from "./tools/versions.js";
|
|
13
|
+
import { registerWorkspaceTools } from "./tools/workspaces.js";
|
|
14
|
+
/** Reads the package version so the server reports its real version to MCP clients. */
|
|
15
|
+
function readVersion() {
|
|
16
|
+
try {
|
|
17
|
+
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
18
|
+
return typeof pkg.version === "string" ? pkg.version : "0.0.0";
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return "0.0.0";
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function loadConfigOrExit() {
|
|
25
|
+
try {
|
|
26
|
+
return loadConfig();
|
|
27
|
+
}
|
|
28
|
+
catch (err) {
|
|
29
|
+
if (!(err instanceof ConfigError))
|
|
30
|
+
throw err;
|
|
31
|
+
console.error(`Error: ${err.message}`);
|
|
32
|
+
process.exit(1);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
async function main() {
|
|
36
|
+
const config = loadConfigOrExit();
|
|
37
|
+
const client = new TagManagerClient(config);
|
|
38
|
+
const server = new McpServer({
|
|
39
|
+
name: "mcp-google-tagmanager",
|
|
40
|
+
version: readVersion(),
|
|
41
|
+
});
|
|
42
|
+
registerAccountTools(server, client);
|
|
43
|
+
registerContainerTools(server, client);
|
|
44
|
+
registerWorkspaceTools(server, client);
|
|
45
|
+
registerEntityTools(server, client);
|
|
46
|
+
registerBuiltInVariableTools(server, client);
|
|
47
|
+
registerVersionTools(server, client);
|
|
48
|
+
registerRawTool(server, client);
|
|
49
|
+
const transport = new StdioServerTransport();
|
|
50
|
+
await server.connect(transport);
|
|
51
|
+
// stderr: stdout is reserved for the MCP protocol.
|
|
52
|
+
console.error("mcp-google-tagmanager running on stdio");
|
|
53
|
+
}
|
|
54
|
+
main().catch((err) => {
|
|
55
|
+
console.error("Fatal error starting mcp-google-tagmanager:", err);
|
|
56
|
+
process.exit(1);
|
|
57
|
+
});
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { fail, idString, ok, pageToken, READ_ONLY } from "./util.js";
|
|
2
|
+
export function registerAccountTools(server, client) {
|
|
3
|
+
server.registerTool("list_accounts", {
|
|
4
|
+
title: "List GTM accounts",
|
|
5
|
+
annotations: READ_ONLY,
|
|
6
|
+
description: "Lists all Google Tag Manager accounts the authorized user can access. Returns { account: [{ accountId, name, path, fingerprint }], nextPageToken }. All ids are strings. This is the entry point: every other tool needs an accountId (or a path) from here.",
|
|
7
|
+
inputSchema: {
|
|
8
|
+
page_token: pageToken(),
|
|
9
|
+
},
|
|
10
|
+
}, async ({ page_token }) => {
|
|
11
|
+
try {
|
|
12
|
+
return ok(await client.listAccounts(page_token));
|
|
13
|
+
}
|
|
14
|
+
catch (e) {
|
|
15
|
+
return fail(e);
|
|
16
|
+
}
|
|
17
|
+
});
|
|
18
|
+
server.registerTool("get_account", {
|
|
19
|
+
title: "Get a GTM account",
|
|
20
|
+
annotations: READ_ONLY,
|
|
21
|
+
description: "Gets one Google Tag Manager account by id. Returns the Account resource: { accountId, name, path, fingerprint, shareData }.",
|
|
22
|
+
inputSchema: {
|
|
23
|
+
account_id: idString("GTM account id (string), e.g. from list_accounts."),
|
|
24
|
+
},
|
|
25
|
+
}, async ({ account_id }) => {
|
|
26
|
+
try {
|
|
27
|
+
return ok(await client.getResource(`accounts/${account_id}`));
|
|
28
|
+
}
|
|
29
|
+
catch (e) {
|
|
30
|
+
return fail(e);
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { BUILT_IN_VARIABLE_TYPES } from "../builtin-variable-types.js";
|
|
3
|
+
import { fail, idString, ok, WRITE } from "./util.js";
|
|
4
|
+
export function registerBuiltInVariableTools(server, client) {
|
|
5
|
+
server.registerTool("manage_built_in_variables", {
|
|
6
|
+
title: "List/enable/disable built-in variables",
|
|
7
|
+
// list is read-only, but enable/disable write; toggles are non-destructive
|
|
8
|
+
// (re-enabling restores them) and idempotent (enabling twice is a no-op).
|
|
9
|
+
annotations: { ...WRITE, idempotentHint: true },
|
|
10
|
+
description: "Manages a workspace's built-in variables (pageUrl, clickText, event, ...). These are toggles, not records: action \"list\" returns the currently enabled ones ({ builtInVariable: [...] }), \"enable\" and \"disable\" take `types` (BuiltInVariableType enum values) and switch them on/off. Enable/disable require the tagmanager.edit.containers scope.",
|
|
11
|
+
inputSchema: {
|
|
12
|
+
account_id: idString("GTM account id (string)."),
|
|
13
|
+
container_id: idString("Container id (string)."),
|
|
14
|
+
workspace_id: idString("Workspace id (string)."),
|
|
15
|
+
action: z.enum(["list", "enable", "disable"]).describe("What to do."),
|
|
16
|
+
types: z
|
|
17
|
+
.array(z.enum(BUILT_IN_VARIABLE_TYPES))
|
|
18
|
+
.optional()
|
|
19
|
+
.describe('Built-in variable types to enable/disable (required for those actions), e.g. ["pageUrl", "clickText"]. Ignored for "list".'),
|
|
20
|
+
},
|
|
21
|
+
}, async ({ account_id, container_id, workspace_id, action, types }) => {
|
|
22
|
+
try {
|
|
23
|
+
if (action === "list") {
|
|
24
|
+
return ok(await client.listBuiltInVariables(account_id, container_id, workspace_id));
|
|
25
|
+
}
|
|
26
|
+
if (!types || types.length === 0) {
|
|
27
|
+
return fail(new Error(`action "${action}" requires a non-empty \`types\` array.`));
|
|
28
|
+
}
|
|
29
|
+
if (action === "enable") {
|
|
30
|
+
return ok(await client.enableBuiltInVariables(account_id, container_id, workspace_id, types));
|
|
31
|
+
}
|
|
32
|
+
await client.disableBuiltInVariables(account_id, container_id, workspace_id, types);
|
|
33
|
+
return ok({ disabled: types });
|
|
34
|
+
}
|
|
35
|
+
catch (e) {
|
|
36
|
+
return fail(e);
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { fail, idString, ok, pageToken, READ_ONLY, WRITE } from "./util.js";
|
|
3
|
+
export function registerContainerTools(server, client) {
|
|
4
|
+
server.registerTool("list_containers", {
|
|
5
|
+
title: "List containers",
|
|
6
|
+
annotations: READ_ONLY,
|
|
7
|
+
description: "Lists the containers of a GTM account. Returns { container: [{ containerId, name, publicId (e.g. GTM-XXXXXX), usageContext, path, fingerprint, tagManagerUrl }], nextPageToken }.",
|
|
8
|
+
inputSchema: {
|
|
9
|
+
account_id: idString("GTM account id (string)."),
|
|
10
|
+
page_token: pageToken(),
|
|
11
|
+
},
|
|
12
|
+
}, async ({ account_id, page_token }) => {
|
|
13
|
+
try {
|
|
14
|
+
return ok(await client.listContainers(account_id, page_token));
|
|
15
|
+
}
|
|
16
|
+
catch (e) {
|
|
17
|
+
return fail(e);
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
server.registerTool("get_container", {
|
|
21
|
+
title: "Get a container",
|
|
22
|
+
annotations: READ_ONLY,
|
|
23
|
+
description: "Gets one container by account id + container id. Returns the Container resource including publicId (the GTM-XXXXXX snippet id), usageContext and fingerprint.",
|
|
24
|
+
inputSchema: {
|
|
25
|
+
account_id: idString("GTM account id (string)."),
|
|
26
|
+
container_id: idString("Container id (string), e.g. from list_containers."),
|
|
27
|
+
},
|
|
28
|
+
}, async ({ account_id, container_id }) => {
|
|
29
|
+
try {
|
|
30
|
+
return ok(await client.getResource(`accounts/${account_id}/containers/${container_id}`));
|
|
31
|
+
}
|
|
32
|
+
catch (e) {
|
|
33
|
+
return fail(e);
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
server.registerTool("create_container", {
|
|
37
|
+
title: "Create a container",
|
|
38
|
+
annotations: WRITE,
|
|
39
|
+
description: "Creates a new container in a GTM account. usage_context declares the platform, e.g. [\"web\"]; other values include androidSdk5, iosSdk5, server. Returns the created Container with its server-assigned containerId and publicId. Requires the tagmanager.edit.containers scope.",
|
|
40
|
+
inputSchema: {
|
|
41
|
+
account_id: idString("GTM account id (string)."),
|
|
42
|
+
name: z.string().min(1).describe("Display name of the new container."),
|
|
43
|
+
usage_context: z
|
|
44
|
+
.array(z.string().min(1))
|
|
45
|
+
.min(1)
|
|
46
|
+
.describe('Usage contexts, e.g. ["web"]. Other documented values: androidSdk5, iosSdk5, server.'),
|
|
47
|
+
},
|
|
48
|
+
}, async ({ account_id, name, usage_context }) => {
|
|
49
|
+
try {
|
|
50
|
+
return ok(await client.createContainer(account_id, { name, usageContext: usage_context }));
|
|
51
|
+
}
|
|
52
|
+
catch (e) {
|
|
53
|
+
return fail(e);
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { DESTRUCTIVE, fail, idString, ok, pageToken, READ_ONLY, resourcePath, WRITE } from "./util.js";
|
|
3
|
+
/** One list_* tool per collection: same wire shape, different response key. */
|
|
4
|
+
const LISTS = [
|
|
5
|
+
{
|
|
6
|
+
tool: "list_tags",
|
|
7
|
+
kind: "tag",
|
|
8
|
+
title: "List tags",
|
|
9
|
+
description: "Lists the tags of a workspace. Returns { tag: [{ tagId, name, type (e.g. html, gaawe), parameter: [{ type, key, value, list, map }], firingTriggerId, blockingTriggerId, paused, path, fingerprint, tagManagerUrl }], nextPageToken }.",
|
|
10
|
+
},
|
|
11
|
+
{
|
|
12
|
+
tool: "list_triggers",
|
|
13
|
+
kind: "trigger",
|
|
14
|
+
title: "List triggers",
|
|
15
|
+
description: "Lists the triggers of a workspace. Returns { trigger: [{ triggerId, name, type (e.g. pageview, click, customEvent), filter/customEventFilter (conditions of { type, parameter }), path, fingerprint }], nextPageToken }.",
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
tool: "list_variables",
|
|
19
|
+
kind: "variable",
|
|
20
|
+
title: "List variables",
|
|
21
|
+
description: "Lists the user-defined variables of a workspace (built-in variables live in manage_built_in_variables). Returns { variable: [{ variableId, name, type (e.g. v = data layer, jsm = custom JS, c = constant), parameter, path, fingerprint }], nextPageToken }.",
|
|
22
|
+
},
|
|
23
|
+
];
|
|
24
|
+
export function registerEntityTools(server, client) {
|
|
25
|
+
for (const { tool, kind, title, description } of LISTS) {
|
|
26
|
+
server.registerTool(tool, {
|
|
27
|
+
title,
|
|
28
|
+
annotations: READ_ONLY,
|
|
29
|
+
description,
|
|
30
|
+
inputSchema: {
|
|
31
|
+
account_id: idString("GTM account id (string)."),
|
|
32
|
+
container_id: idString("Container id (string)."),
|
|
33
|
+
workspace_id: idString("Workspace id (string), e.g. from list_workspaces."),
|
|
34
|
+
page_token: pageToken(),
|
|
35
|
+
},
|
|
36
|
+
}, async ({ account_id, container_id, workspace_id, page_token }) => {
|
|
37
|
+
try {
|
|
38
|
+
return ok(await client.listEntities(account_id, container_id, workspace_id, kind, page_token));
|
|
39
|
+
}
|
|
40
|
+
catch (e) {
|
|
41
|
+
return fail(e);
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
server.registerTool("get_resource", {
|
|
46
|
+
title: "Get any resource by path",
|
|
47
|
+
annotations: READ_ONLY,
|
|
48
|
+
description: "Generic getter for any GTM resource by its API-relative path — tags, triggers, variables, versions, containers, workspaces. Prefer echoing the `path` field from a previous response over assembling the string yourself. Returns the full resource JSON including its current fingerprint (needed for update_entity).",
|
|
49
|
+
inputSchema: {
|
|
50
|
+
path: resourcePath("accounts/1/containers/2/workspaces/3/tags/4"),
|
|
51
|
+
},
|
|
52
|
+
}, async ({ path }) => {
|
|
53
|
+
try {
|
|
54
|
+
return ok(await client.getResource(path));
|
|
55
|
+
}
|
|
56
|
+
catch (e) {
|
|
57
|
+
return fail(e);
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
server.registerTool("create_entity", {
|
|
61
|
+
title: "Create a tag, trigger or variable",
|
|
62
|
+
annotations: WRITE,
|
|
63
|
+
description: "Creates a tag, trigger or variable in a workspace. `body` is the resource JSON: minimally { name, type } plus type-specific parameter entries; tags also take firingTriggerId (array of trigger id strings). Example tag body: { \"name\": \"GA4 event\", \"type\": \"gaawe\", \"parameter\": [...], \"firingTriggerId\": [\"12\"] }. Returns the created resource with its server-assigned id and fingerprint. Requires the tagmanager.edit.containers scope.",
|
|
64
|
+
inputSchema: {
|
|
65
|
+
account_id: idString("GTM account id (string)."),
|
|
66
|
+
container_id: idString("Container id (string)."),
|
|
67
|
+
workspace_id: idString("Workspace id (string)."),
|
|
68
|
+
entity_type: z.enum(["tag", "trigger", "variable"]).describe("Which collection to create in."),
|
|
69
|
+
body: z
|
|
70
|
+
.record(z.any())
|
|
71
|
+
.describe("The resource JSON to create (name, type, parameter, and for tags firingTriggerId)."),
|
|
72
|
+
},
|
|
73
|
+
}, async ({ account_id, container_id, workspace_id, entity_type, body }) => {
|
|
74
|
+
try {
|
|
75
|
+
return ok(await client.createEntity(account_id, container_id, workspace_id, entity_type, body));
|
|
76
|
+
}
|
|
77
|
+
catch (e) {
|
|
78
|
+
return fail(e);
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
server.registerTool("update_entity", {
|
|
82
|
+
title: "Update a tag, trigger or variable",
|
|
83
|
+
annotations: { ...DESTRUCTIVE, idempotentHint: true },
|
|
84
|
+
description: "Updates a tag, trigger or variable by its API path. PUT semantics: this is a FULL REPLACE, not a patch — fetch the current resource with get_resource, modify it, and send the whole object back. Pass the resource's last-seen fingerprint for optimistic-concurrency safety; a mismatch fails the request. Requires the tagmanager.edit.containers scope.",
|
|
85
|
+
inputSchema: {
|
|
86
|
+
path: resourcePath("accounts/1/containers/2/workspaces/3/triggers/5"),
|
|
87
|
+
body: z.record(z.any()).describe("The complete replacement resource JSON."),
|
|
88
|
+
fingerprint: z
|
|
89
|
+
.string()
|
|
90
|
+
.optional()
|
|
91
|
+
.describe("The fingerprint from the last read of this resource; the update fails if it is stale."),
|
|
92
|
+
},
|
|
93
|
+
}, async ({ path, body, fingerprint }) => {
|
|
94
|
+
try {
|
|
95
|
+
return ok(await client.updateEntity(path, body, fingerprint));
|
|
96
|
+
}
|
|
97
|
+
catch (e) {
|
|
98
|
+
return fail(e);
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
server.registerTool("delete_entity", {
|
|
102
|
+
title: "Delete a tag, trigger or variable",
|
|
103
|
+
annotations: { ...DESTRUCTIVE, idempotentHint: true },
|
|
104
|
+
description: "Deletes a tag, trigger or variable by its API path. The response is empty on success. Requires the tagmanager.edit.containers scope.",
|
|
105
|
+
inputSchema: {
|
|
106
|
+
path: resourcePath("accounts/1/containers/2/workspaces/3/variables/7"),
|
|
107
|
+
},
|
|
108
|
+
}, async ({ path }) => {
|
|
109
|
+
try {
|
|
110
|
+
await client.deleteEntity(path);
|
|
111
|
+
return ok({ deleted: true, path });
|
|
112
|
+
}
|
|
113
|
+
catch (e) {
|
|
114
|
+
return fail(e);
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { DESTRUCTIVE, fail, ok } from "./util.js";
|
|
3
|
+
export function registerRawTool(server, client) {
|
|
4
|
+
server.registerTool("raw_request", {
|
|
5
|
+
title: "Raw Tag Manager API call",
|
|
6
|
+
// The API has write endpoints and this tool can reach all of them,
|
|
7
|
+
// so it carries the most conservative hints.
|
|
8
|
+
annotations: DESTRUCTIVE,
|
|
9
|
+
description: 'Escape hatch to call any Google Tag Manager API v2 path directly, for endpoints without a dedicated tool (environments, folders, templates, zones, workspace :sync / :quick_preview, version_headers, ...). `path` is relative to /tagmanager/v2/, e.g. "accounts/1/containers/2/environments". `query` values may be arrays for repeated params. Requests go through the same OAuth, rate limiter and retries as every other tool.',
|
|
10
|
+
inputSchema: {
|
|
11
|
+
path: z
|
|
12
|
+
.string()
|
|
13
|
+
.min(1)
|
|
14
|
+
.describe('API path relative to /tagmanager/v2/, e.g. "accounts/1/containers/2/version_headers".'),
|
|
15
|
+
method: z.enum(["GET", "POST", "PUT", "DELETE"]).optional().describe("HTTP method. Defaults to GET."),
|
|
16
|
+
query: z
|
|
17
|
+
.record(z.union([z.string(), z.array(z.string())]))
|
|
18
|
+
.optional()
|
|
19
|
+
.describe('Query parameters; use an array for repeated keys, e.g. { "type": ["pageUrl", "event"] }.'),
|
|
20
|
+
body: z.record(z.any()).optional().describe("JSON request body (POST/PUT)."),
|
|
21
|
+
},
|
|
22
|
+
}, async ({ path, method, query, body }) => {
|
|
23
|
+
try {
|
|
24
|
+
const m = (method ?? "GET");
|
|
25
|
+
return ok(await client.request(m, path, { query, body }));
|
|
26
|
+
}
|
|
27
|
+
catch (e) {
|
|
28
|
+
return fail(e);
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
}
|