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.
@@ -0,0 +1,52 @@
1
+ import { z } from "zod";
2
+ /** Wraps a value as a compact-JSON tool result (compact: the consumer is an LLM). */
3
+ export function ok(data) {
4
+ const text = typeof data === "string" ? data : JSON.stringify(data);
5
+ return { content: [{ type: "text", text: text ?? "null" }] };
6
+ }
7
+ export function fail(err) {
8
+ let message = err instanceof Error ? err.message : String(err);
9
+ // Surface the underlying cause (e.g. the network error behind a timeout) — no
10
+ // secrets live in cause, and it makes failures far easier to diagnose.
11
+ if (err instanceof Error && err.cause instanceof Error)
12
+ message += ` (${err.cause.message})`;
13
+ return { content: [{ type: "text", text: `Error: ${message}` }], isError: true };
14
+ }
15
+ /**
16
+ * MCP tool annotations — hints the consuming client can use to gate or label a
17
+ * tool. All four hints are set explicitly on every tool: some clients (OpenAI
18
+ * Apps review) require readOnlyHint, destructiveHint and openWorldHint each time.
19
+ */
20
+ export const READ_ONLY = {
21
+ readOnlyHint: true,
22
+ destructiveHint: false,
23
+ idempotentHint: true,
24
+ openWorldHint: true,
25
+ };
26
+ /** Creates a new resource: not read-only, but nothing existing is overwritten. */
27
+ export const WRITE = {
28
+ readOnlyHint: false,
29
+ destructiveHint: false,
30
+ idempotentHint: false,
31
+ openWorldHint: true,
32
+ };
33
+ /** Overwrites or deletes existing state (PUT full-replace, DELETE, publish). */
34
+ export const DESTRUCTIVE = {
35
+ readOnlyHint: false,
36
+ destructiveHint: true,
37
+ idempotentHint: false,
38
+ openWorldHint: true,
39
+ };
40
+ /**
41
+ * zod FACTORIES (not shared consts) for fields that repeat within one tool's
42
+ * inputSchema: reusing one zod object across two fields makes zod-to-json-schema
43
+ * dedupe them into a `$ref`, which some tool-schema consumers don't dereference
44
+ * and flag as `any`. A fresh object per field keeps each one inlined.
45
+ */
46
+ export const idString = (what) => z.string().min(1).describe(what);
47
+ /** An API-relative resource path, as returned in every resource's `path` field. */
48
+ export const resourcePath = (example) => z
49
+ .string()
50
+ .regex(/^accounts\//, 'Must be an API-relative path starting with "accounts/"')
51
+ .describe(`API-relative resource path as returned in the resource's own "path" field, e.g. "${example}".`);
52
+ export const pageToken = () => z.string().optional().describe("Pagination token from a previous response's nextPageToken. Omit for the first page.");
@@ -0,0 +1,78 @@
1
+ import { z } from "zod";
2
+ import { DESTRUCTIVE, fail, idString, ok } from "./util.js";
3
+ /**
4
+ * Both :create_version and :publish can fail at the compiler level while
5
+ * returning HTTP 200 — the failure signal is compilerError=true in the body.
6
+ * Surface that as a tool error so the model does not mistake it for success.
7
+ */
8
+ function okUnlessCompilerError(res) {
9
+ if (res && typeof res === "object" && res.compilerError === true) {
10
+ return {
11
+ content: [
12
+ {
13
+ type: "text",
14
+ text: `Error: the container failed to compile (compilerError=true; HTTP 200). Full response: ${JSON.stringify(res)}`,
15
+ },
16
+ ],
17
+ isError: true,
18
+ };
19
+ }
20
+ return ok(res);
21
+ }
22
+ export function registerVersionTools(server, client) {
23
+ server.registerTool("create_version", {
24
+ title: "Create a container version from a workspace",
25
+ // Destructive on purpose: the source workspace is deleted by the API.
26
+ annotations: DESTRUCTIVE,
27
+ description: "Compiles a workspace into an immutable Container Version (the unit that gets published). SIDE EFFECT: the source workspace is DELETED and replaced by a fresh one — the response's newWorkspacePath points to the replacement; use it for any further edits, or old workspace paths will 404. Returns { containerVersion (with containerVersionId and full tag/trigger/variable snapshots), syncStatus, newWorkspacePath }. A compile failure comes back as compilerError=true with HTTP 200 and is reported as an error. Requires the tagmanager.edit.containerversions scope (edit.containers is NOT sufficient).",
28
+ inputSchema: {
29
+ account_id: idString("GTM account id (string)."),
30
+ container_id: idString("Container id (string)."),
31
+ workspace_id: idString("Workspace id (string) to compile. This workspace is deleted afterwards."),
32
+ name: z.string().optional().describe("Version display name."),
33
+ notes: z.string().optional().describe("Version notes (changelog entry)."),
34
+ },
35
+ }, async ({ account_id, container_id, workspace_id, name, notes }) => {
36
+ try {
37
+ return okUnlessCompilerError(await client.createVersion(account_id, container_id, workspace_id, { name, notes }));
38
+ }
39
+ catch (e) {
40
+ return fail(e);
41
+ }
42
+ });
43
+ server.registerTool("publish_version", {
44
+ title: "Publish, inspect or fetch the live container version",
45
+ // publish replaces what is live in production — destructive; get/live are reads.
46
+ annotations: DESTRUCTIVE,
47
+ description: 'Container-version operations. action "publish" pushes a version live (replacing the currently published one; requires the tagmanager.publish scope; version_id required, fingerprint recommended). action "get" fetches one version by version_id. action "live" fetches the currently published version of the container (no version_id needed). Publish responses can carry compilerError=true with HTTP 200 — reported as an error. Returns the ContainerVersion (publish wraps it as { containerVersion, compilerError }).',
48
+ inputSchema: {
49
+ account_id: idString("GTM account id (string)."),
50
+ container_id: idString("Container id (string)."),
51
+ action: z.enum(["publish", "get", "live"]).describe("What to do."),
52
+ version_id: z
53
+ .string()
54
+ .optional()
55
+ .describe('Container version id (string). Required for "publish" and "get"; ignored for "live".'),
56
+ fingerprint: z
57
+ .string()
58
+ .optional()
59
+ .describe('The version\'s last-seen fingerprint ("publish" only), for optimistic-concurrency safety.'),
60
+ },
61
+ }, async ({ account_id, container_id, action, version_id, fingerprint }) => {
62
+ try {
63
+ if (action === "live") {
64
+ return ok(await client.liveVersion(account_id, container_id));
65
+ }
66
+ if (!version_id) {
67
+ return fail(new Error(`action "${action}" requires \`version_id\`.`));
68
+ }
69
+ if (action === "get") {
70
+ return ok(await client.getVersion(account_id, container_id, version_id));
71
+ }
72
+ return okUnlessCompilerError(await client.publishVersion(account_id, container_id, version_id, fingerprint));
73
+ }
74
+ catch (e) {
75
+ return fail(e);
76
+ }
77
+ });
78
+ }
@@ -0,0 +1,56 @@
1
+ import { z } from "zod";
2
+ import { fail, idString, ok, pageToken, READ_ONLY, WRITE } from "./util.js";
3
+ export function registerWorkspaceTools(server, client) {
4
+ server.registerTool("list_workspaces", {
5
+ title: "List workspaces",
6
+ annotations: READ_ONLY,
7
+ description: "Lists the workspaces of a container. Returns { workspace: [{ workspaceId, name, description, path, fingerprint }], nextPageToken }. Workspaces are mandatory in GTM v2: every tag/trigger/variable operation needs a workspaceId, and a \"Default Workspace\" always exists — call this first.",
8
+ inputSchema: {
9
+ account_id: idString("GTM account id (string)."),
10
+ container_id: idString("Container id (string)."),
11
+ page_token: pageToken(),
12
+ },
13
+ }, async ({ account_id, container_id, page_token }) => {
14
+ try {
15
+ return ok(await client.listWorkspaces(account_id, container_id, page_token));
16
+ }
17
+ catch (e) {
18
+ return fail(e);
19
+ }
20
+ });
21
+ server.registerTool("get_workspace", {
22
+ title: "Get a workspace",
23
+ annotations: READ_ONLY,
24
+ description: "Gets one workspace by account id + container id + workspace id. Returns the Workspace resource with its fingerprint.",
25
+ inputSchema: {
26
+ account_id: idString("GTM account id (string)."),
27
+ container_id: idString("Container id (string)."),
28
+ workspace_id: idString("Workspace id (string), e.g. from list_workspaces."),
29
+ },
30
+ }, async ({ account_id, container_id, workspace_id }) => {
31
+ try {
32
+ return ok(await client.getResource(`accounts/${account_id}/containers/${container_id}/workspaces/${workspace_id}`));
33
+ }
34
+ catch (e) {
35
+ return fail(e);
36
+ }
37
+ });
38
+ server.registerTool("create_workspace", {
39
+ title: "Create a workspace",
40
+ annotations: WRITE,
41
+ description: "Creates a new workspace in a container — an isolated draft where tags, triggers and variables are edited before being compiled into a version. Returns the created Workspace with its server-assigned workspaceId. Requires the tagmanager.edit.containers scope.",
42
+ inputSchema: {
43
+ account_id: idString("GTM account id (string)."),
44
+ container_id: idString("Container id (string)."),
45
+ name: z.string().min(1).describe("Display name of the new workspace."),
46
+ description: z.string().optional().describe("Optional description of what this workspace changes."),
47
+ },
48
+ }, async ({ account_id, container_id, name, description }) => {
49
+ try {
50
+ return ok(await client.createWorkspace(account_id, container_id, { name, description }));
51
+ }
52
+ catch (e) {
53
+ return fail(e);
54
+ }
55
+ });
56
+ }
package/dist/types.js ADDED
@@ -0,0 +1,86 @@
1
+ /**
2
+ * The server talks to the Google Tag Manager API v2
3
+ * (https://tagmanager.googleapis.com/tagmanager/v2/...). Auth is Google OAuth 2.0:
4
+ * either a ready-made access token, or a client-id/client-secret/refresh-token
5
+ * trio that the server exchanges for short-lived access tokens itself.
6
+ *
7
+ * GTM v2 addresses every resource through a single relative `path`
8
+ * (accounts/{a}/containers/{c}/workspaces/{w}/tags/{t}, ...). All ids are
9
+ * strings, and every resource carries `path` and `fingerprint` fields —
10
+ * the fingerprint is the API's optimistic-concurrency token.
11
+ */
12
+ /**
13
+ * The API reports failures with the standard Google JSON error envelope
14
+ * ({ error: { code, message, errors: [{ reason, ... }], status } }). The parsed
15
+ * body is kept alongside the HTTP status and a short readable message is derived.
16
+ */
17
+ export class TagManagerError extends Error {
18
+ status;
19
+ body;
20
+ constructor(status, body) {
21
+ super(`HTTP ${status}: ${formatErrorBody(body)}`);
22
+ this.name = "TagManagerError";
23
+ this.status = status;
24
+ this.body = body;
25
+ }
26
+ }
27
+ /** Turns a parsed Google API error body into a short, readable message. */
28
+ function formatErrorBody(body) {
29
+ if (body == null)
30
+ return "(no body)";
31
+ if (typeof body === "string")
32
+ return body.slice(0, 500);
33
+ if (typeof body !== "object")
34
+ return String(body);
35
+ const obj = body;
36
+ // Google envelope: { error: { code, message, errors, status } }
37
+ const err = obj.error;
38
+ if (err && typeof err === "object") {
39
+ const e = err;
40
+ if (typeof e.message === "string") {
41
+ const status = typeof e.status === "string" ? `[${e.status}] ` : "";
42
+ const reason = firstReason(e.errors);
43
+ return `${status}${e.message}${reason ? ` (reason: ${reason})` : ""}`.slice(0, 500);
44
+ }
45
+ }
46
+ // OAuth token endpoint style: { error: "invalid_grant", error_description: "..." }
47
+ if (typeof obj.error === "string") {
48
+ const desc = typeof obj.error_description === "string" ? `: ${obj.error_description}` : "";
49
+ return `${obj.error}${desc}`.slice(0, 500);
50
+ }
51
+ if (typeof obj.message === "string")
52
+ return obj.message.slice(0, 500);
53
+ return JSON.stringify(obj).slice(0, 500);
54
+ }
55
+ /** Extracts the first `reason` from the envelope's errors[] list, if any. */
56
+ function firstReason(errors) {
57
+ if (!Array.isArray(errors))
58
+ return undefined;
59
+ const first = errors[0];
60
+ if (first && typeof first === "object" && typeof first.reason === "string") {
61
+ return first.reason;
62
+ }
63
+ return undefined;
64
+ }
65
+ /**
66
+ * True when a 403 body is a quota/rate-limit rejection (retryable) rather than
67
+ * a permissions problem (not retryable). GTM documents quota overruns as
68
+ * HTTP 403; 429 rateLimitExceeded is also observed across Google APIs.
69
+ */
70
+ export function isQuotaError(body) {
71
+ if (!body || typeof body !== "object")
72
+ return false;
73
+ const err = body.error;
74
+ if (!err || typeof err !== "object")
75
+ return false;
76
+ const e = err;
77
+ const reasons = Array.isArray(e.errors)
78
+ ? e.errors
79
+ .map((item) => item && typeof item === "object" ? item.reason : undefined)
80
+ .filter((r) => typeof r === "string")
81
+ : [];
82
+ const quotaReasons = ["rateLimitExceeded", "userRateLimitExceeded", "quotaExceeded", "dailyLimitExceeded"];
83
+ if (reasons.some((r) => quotaReasons.includes(r)))
84
+ return true;
85
+ return typeof e.message === "string" && /quota|rate limit/i.test(e.message);
86
+ }
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "mcp-google-tagmanager",
3
+ "version": "0.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.",
5
+ "mcpName": "io.github.A1-x-Tech/mcp-google-tagmanager",
6
+ "type": "module",
7
+ "bin": {
8
+ "mcp-google-tagmanager": "dist/index.js"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "test"
13
+ ],
14
+ "engines": {
15
+ "node": ">=20"
16
+ },
17
+ "scripts": {
18
+ "build": "rm -rf dist && tsc",
19
+ "start": "node dist/index.js",
20
+ "dev": "tsx watch src/index.ts",
21
+ "typecheck": "tsc -p tsconfig.check.json",
22
+ "smoke": "node --import tsx src/smoke.ts",
23
+ "test": "npm run test:src && npm run test:dist",
24
+ "test:src": "node --import tsx --test $(find src -name '*.test.ts')",
25
+ "test:dist": "npm run build && node --test test/dist-smoke.test.js",
26
+ "prepare": "npm run build",
27
+ "prepublishOnly": "npm run typecheck && npm test"
28
+ },
29
+ "keywords": [
30
+ "mcp",
31
+ "model-context-protocol",
32
+ "google",
33
+ "google-tag-manager",
34
+ "gtm",
35
+ "tagmanager",
36
+ "tags",
37
+ "triggers",
38
+ "analytics",
39
+ "claude",
40
+ "cursor",
41
+ "codex"
42
+ ],
43
+ "license": "MIT",
44
+ "author": "gistrec <gistrec@gmail.com>",
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/A1-x-Tech/mcp-google-tagmanager.git"
48
+ },
49
+ "homepage": "https://github.com/A1-x-Tech/mcp-google-tagmanager#readme",
50
+ "bugs": {
51
+ "url": "https://github.com/A1-x-Tech/mcp-google-tagmanager/issues"
52
+ },
53
+ "dependencies": {
54
+ "@modelcontextprotocol/sdk": "^1.29.0",
55
+ "zod": "^3.25.0"
56
+ },
57
+ "devDependencies": {
58
+ "@types/node": "^25.9.3",
59
+ "tsx": "^4.22.4",
60
+ "typescript": "^5.7.0"
61
+ }
62
+ }
@@ -0,0 +1,94 @@
1
+ // Tests the built artifact in dist/ — the exact files that ship to npm.
2
+ // Plain JS on purpose: no tsx loader between the test and the artifact.
3
+ import assert from "node:assert/strict";
4
+ import { fileURLToPath } from "node:url";
5
+ import test from "node:test";
6
+
7
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
8
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
9
+
10
+ import { TagManagerClient } from "../dist/client.js";
11
+
12
+ const ALL_TOOLS = [
13
+ "create_container",
14
+ "create_entity",
15
+ "create_version",
16
+ "create_workspace",
17
+ "delete_entity",
18
+ "get_account",
19
+ "get_container",
20
+ "get_resource",
21
+ "get_workspace",
22
+ "list_accounts",
23
+ "list_containers",
24
+ "list_tags",
25
+ "list_triggers",
26
+ "list_variables",
27
+ "list_workspaces",
28
+ "manage_built_in_variables",
29
+ "publish_version",
30
+ "raw_request",
31
+ "update_entity",
32
+ ];
33
+
34
+ test("dist binary completes a real MCP handshake over stdio and lists every tool", async () => {
35
+ const transport = new StdioClientTransport({
36
+ command: process.execPath,
37
+ args: [fileURLToPath(new URL("../dist/index.js", import.meta.url))],
38
+ env: { ...process.env, GOOGLE_TAGMANAGER_ACCESS_TOKEN: "smoke-test-token" },
39
+ stderr: "ignore",
40
+ });
41
+ const client = new Client({ name: "dist-smoke", version: "0.0.0" });
42
+ try {
43
+ await client.connect(transport);
44
+ const serverInfo = client.getServerVersion();
45
+ assert.equal(serverInfo.name, "mcp-google-tagmanager");
46
+ assert.notEqual(serverInfo.version, "0.0.0"); // real version read from package.json
47
+
48
+ const { tools } = await client.listTools();
49
+ assert.deepEqual(tools.map((t) => t.name).sort(), ALL_TOOLS);
50
+ for (const tool of tools) {
51
+ assert.ok(tool.annotations, `${tool.name} is missing annotations in dist`);
52
+ assert.equal(typeof tool.annotations.readOnlyHint, "boolean", `${tool.name} readOnlyHint`);
53
+ }
54
+ } finally {
55
+ await client.close();
56
+ }
57
+ });
58
+
59
+ test("dist binary exits with an error when unconfigured", async () => {
60
+ const { spawn } = await import("node:child_process");
61
+ const env = { ...process.env };
62
+ delete env.GOOGLE_TAGMANAGER_ACCESS_TOKEN;
63
+ delete env.GOOGLE_TAGMANAGER_CLIENT_ID;
64
+ delete env.GOOGLE_TAGMANAGER_CLIENT_SECRET;
65
+ delete env.GOOGLE_TAGMANAGER_REFRESH_TOKEN;
66
+ const child = spawn(process.execPath, [fileURLToPath(new URL("../dist/index.js", import.meta.url))], { env });
67
+ let stderr = "";
68
+ child.stderr.on("data", (chunk) => (stderr += chunk));
69
+ const code = await new Promise((resolve) => child.on("close", resolve));
70
+ assert.equal(code, 1);
71
+ assert.match(stderr, /GOOGLE_TAGMANAGER_CLIENT_ID is required/);
72
+ });
73
+
74
+ test("dist client rejects foreign-origin paths before sending the token", async () => {
75
+ let called = false;
76
+ const orig = globalThis.fetch;
77
+ globalThis.fetch = async () => {
78
+ called = true;
79
+ return new Response("{}", { status: 200 });
80
+ };
81
+ try {
82
+ const client = new TagManagerClient({
83
+ accessToken: "SECRET",
84
+ apiBase: "https://tagmanager.googleapis.com",
85
+ timeoutMs: 1000,
86
+ maxRetries: 0,
87
+ minIntervalMs: 0,
88
+ });
89
+ await assert.rejects(() => client.request("GET", "https://example.invalid/steal"), /foreign origin/);
90
+ assert.equal(called, false);
91
+ } finally {
92
+ globalThis.fetch = orig;
93
+ }
94
+ });