mcp-google-tagmanager 1.0.0 → 1.2.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/dist/index.js CHANGED
@@ -3,7 +3,7 @@ import { readFileSync } from "node:fs";
3
3
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
4
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
5
  import { TagManagerClient } from "./client.js";
6
- import { ConfigError, loadConfig } from "./config.js";
6
+ import { ConfigError, DEFAULT_BASE, hasCredentials, loadConfig } from "./config.js";
7
7
  import { instrumentToolCalls, Telemetry } from "./telemetry.js";
8
8
  import { registerAccountTools } from "./tools/accounts.js";
9
9
  import { registerBuiltInVariableTools } from "./tools/builtins.js";
@@ -12,6 +12,32 @@ 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";
17
+ /**
18
+ * The prose the calling model receives in the initialize result, before it sees
19
+ * a single tool. It carries only what the tool list cannot: what this API is
20
+ * not, where the live-site danger sits, what the quota costs, and which errors
21
+ * mean something other than what they say.
22
+ */
23
+ const INSTRUCTIONS = "Google Tag Manager API v2 configures what a container deploys — tags, triggers, variables, " +
24
+ "versions. It is not Google Analytics: no visits, conversions or reporting exist here. Tag, " +
25
+ "trigger and variable edits land in a workspace draft and change nothing on real sites until " +
26
+ "create_version compiles it; compiling consumes the workspace, so a workspace id from before a " +
27
+ "create_version is dead. Quota binds everything: 0.25 QPS per project (25 calls/100 s) and 10k a " +
28
+ "day, so requests are spaced 4.2 s apart by default — auditing a container takes minutes by " +
29
+ "design; plan the fewest calls, never poll. 429 and quota-403 are already retried with backoff; " +
30
+ "retrying by hand only burns quota. A 403 is as often a missing OAuth scope (readonly, " +
31
+ "edit.containers, edit.containerversions and publish are granted separately) as a real permission " +
32
+ "problem, an empty list_accounts means the authorized Google account sees no GTM account, not " +
33
+ "that none exists, and with a direct access token (no refresh trio) a 401 after an hour is just " +
34
+ "expiry. publish_version replaces production on every site with the container.";
35
+ /**
36
+ * Prepended to INSTRUCTIONS when no credentials are configured. The model reads
37
+ * this before it picks a tool, so an unconfigured session opens with the fix
38
+ * rather than with a failed call. There is no in-chat login here: credentials
39
+ * come only from the environment, so the fix is an operator action + restart.
40
+ */
15
41
  /** Reads the package version so the server reports its real version to MCP clients. */
16
42
  function readVersion() {
17
43
  try {
@@ -23,21 +49,27 @@ function readVersion() {
23
49
  }
24
50
  }
25
51
  /**
26
- * Loads the config, reporting the drop-off if it is missing. An unconfigured
27
- * server dies before the MCP handshake, so this ping is the only trace such an
28
- * install ever leaves — and it has to be awaited, or process.exit() below would
29
- * kill the request in flight.
52
+ * Loads the config without dying on a bad value. A server that exits here never
53
+ * completes the MCP handshake, so the user sees a dead server and no reason.
54
+ * Instead the problem is carried into the session, where the model can read it
55
+ * and relay it: the config degrades to "no credentials" and every tool call
56
+ * fails with the actionable message.
30
57
  */
31
- async function loadConfigOrExit(telemetry) {
58
+ function loadConfigOrDegraded(telemetry) {
32
59
  try {
33
- return loadConfig();
60
+ return { config: loadConfig() };
34
61
  }
35
62
  catch (err) {
36
63
  if (!(err instanceof ConfigError))
37
64
  throw err;
38
65
  console.error(`Error: ${err.message}`);
39
- await telemetry.sendBlocking("startup_failed", { reason: err.reason });
40
- process.exit(1);
66
+ // Fire-and-forget now that the process survives: the historical
67
+ // `startup_failed` funnel stays comparable, but nothing blocks startup.
68
+ telemetry.send("startup_failed", { reason: err.reason });
69
+ return {
70
+ config: { apiBase: process.env.GOOGLE_TAGMANAGER_API_BASE || DEFAULT_BASE },
71
+ problem: err,
72
+ };
41
73
  }
42
74
  }
43
75
  async function main() {
@@ -45,17 +77,35 @@ async function main() {
45
77
  // arguments); opt out with ASKADS_TELEMETRY=0. Built before the config so
46
78
  // missing credentials can be reported; wired to the server before tools register.
47
79
  const telemetry = new Telemetry(readVersion());
48
- const config = await loadConfigOrExit(telemetry);
49
- const client = new TagManagerClient(config);
80
+ const { config, problem } = loadConfigOrDegraded(telemetry);
81
+ // Decided once, at startup: credentials come only from the environment, so
82
+ // "restart after setting the variables" is the accurate advice to give.
83
+ const connected = hasCredentials(config) || hasAuthToken();
84
+ // `instructions` belongs to the SDK's ServerOptions (2nd argument); passed
85
+ // next to name/version it would be silently dropped from the initialize result.
50
86
  const server = new McpServer({
51
87
  name: "mcp-google-tagmanager",
52
88
  version: readVersion(),
89
+ }, {
90
+ instructions: connected
91
+ ? INSTRUCTIONS
92
+ : authUnconfiguredPrefix() + (problem ? `Configuration problem: ${problem.message} ` : "") + INSTRUCTIONS,
53
93
  });
54
94
  instrumentToolCalls(server, telemetry);
55
95
  server.server.oninitialized = () => {
56
96
  telemetry.setClientInfo(server.server.getClientVersion());
57
- telemetry.send("server_start");
97
+ // Split on purpose: `server_start` keeps meaning "a usable install started",
98
+ // so the unconfigured case gets its own event instead of inflating that number.
99
+ if (connected)
100
+ telemetry.send("server_start");
101
+ else
102
+ telemetry.send("unconfigured_start", { reason: problem?.reason ?? "missing_client_id" });
58
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));
59
109
  registerAccountTools(server, client);
60
110
  registerContainerTools(server, client);
61
111
  registerWorkspaceTools(server, client);
@@ -66,7 +116,7 @@ async function main() {
66
116
  const transport = new StdioServerTransport();
67
117
  await server.connect(transport);
68
118
  // stderr: stdout is reserved for the MCP protocol.
69
- console.error("mcp-google-tagmanager running on stdio");
119
+ console.error(`mcp-google-tagmanager running on stdio${connected ? "" : " (no credentials — set the environment variables and restart)"}`);
70
120
  }
71
121
  main().catch((err) => {
72
122
  console.error("Fatal error starting mcp-google-tagmanager:", err);
package/dist/telemetry.js CHANGED
@@ -69,9 +69,9 @@ export class Telemetry {
69
69
  void this.post(event, fields);
70
70
  }
71
71
  /**
72
- * The same ping, awaited. Only for the startup_failed path: that caller
73
- * calls process.exit() immediately after, which would kill an in-flight
74
- * fire-and-forget request before it ever left the machine.
72
+ * The same ping, awaited. Only for a caller that exits right after — a
73
+ * fire-and-forget request would die in flight with the process. No startup
74
+ * path needs it anymore (a config problem degrades instead of exiting).
75
75
  */
76
76
  async sendBlocking(event, fields = {}) {
77
77
  await this.post(event, fields);
@@ -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
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mcp-google-tagmanager",
3
- "version": "1.0.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.2.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))],
@@ -45,6 +72,16 @@ test("dist binary completes a real MCP handshake over stdio and lists every tool
45
72
  assert.equal(serverInfo.name, "mcp-google-tagmanager");
46
73
  assert.notEqual(serverInfo.version, "0.0.0"); // real version read from package.json
47
74
 
75
+ // The only prose the calling model gets before it picks a tool. An empty
76
+ // one means the option was dropped somewhere between src and dist.
77
+ const instructions = client.getInstructions();
78
+ assert.ok(instructions, "initialize must carry instructions");
79
+ assert.ok(instructions.length > 300, `instructions look truncated (${instructions.length} chars)`);
80
+ // Regression guard on the two facts that cost the most to rediscover: GTM
81
+ // configures tags, it does not report data, and the quota is the bottleneck.
82
+ assert.match(instructions, /not Google Analytics/);
83
+ assert.match(instructions, /0\.25 QPS/);
84
+
48
85
  const { tools } = await client.listTools();
49
86
  assert.deepEqual(tools.map((t) => t.name).sort(), ALL_TOOLS);
50
87
  for (const tool of tools) {
@@ -56,20 +93,53 @@ test("dist binary completes a real MCP handshake over stdio and lists every tool
56
93
  }
57
94
  });
58
95
 
59
- test("dist binary exits with an error when unconfigured", async () => {
60
- const { spawn } = await import("node:child_process");
61
- // Opt out so the startup_failed ping never leaves the test machine.
62
- const env = { ...process.env, ASKADS_TELEMETRY: "0" };
63
- delete env.GOOGLE_TAGMANAGER_ACCESS_TOKEN;
64
- delete env.GOOGLE_TAGMANAGER_CLIENT_ID;
65
- delete env.GOOGLE_TAGMANAGER_CLIENT_SECRET;
66
- delete env.GOOGLE_TAGMANAGER_REFRESH_TOKEN;
67
- const child = spawn(process.execPath, [fileURLToPath(new URL("../dist/index.js", import.meta.url))], { env });
68
- let stderr = "";
69
- child.stderr.on("data", (chunk) => (stderr += chunk));
70
- const code = await new Promise((resolve) => child.on("close", resolve));
71
- assert.equal(code, 1);
72
- assert.match(stderr, /GOOGLE_TAGMANAGER_CLIENT_ID is required/);
96
+ /**
97
+ * The degraded-start contract: without any credentials the binary used to
98
+ * exit(1) before the handshake, leaving the client a dead server and no reason.
99
+ * It must now start, list every tool, open the instructions with the fix, and
100
+ * answer a tool call with the actionable error — offline: the CredentialsError
101
+ * fires before any fetch, so this test never touches the network.
102
+ */
103
+ test("dist binary starts without credentials: handshake, tool list, actionable call error", async (t) => {
104
+ const env = Object.fromEntries(
105
+ Object.entries(process.env).filter(
106
+ ([key, value]) => value !== undefined && !key.startsWith("GOOGLE_TAGMANAGER_"),
107
+ ),
108
+ );
109
+ env.ASKADS_TELEMETRY = "0"; // keep the suite offline
110
+ env.XDG_CONFIG_HOME = isolatedConfigDir(t); // ignore any real login on this machine
111
+ const transport = new StdioClientTransport({
112
+ command: process.execPath,
113
+ args: [fileURLToPath(new URL("../dist/index.js", import.meta.url))],
114
+ env,
115
+ stderr: "pipe",
116
+ });
117
+ const client = new Client({ name: "dist-smoke-unconfigured", version: "0.0.0" });
118
+ await client.connect(transport);
119
+ try {
120
+ // The model must read the fix before it picks a tool.
121
+ const instructions = client.getInstructions() ?? "";
122
+ assert.match(instructions, /NOT CONNECTED/);
123
+ assert.match(instructions, /start_login/);
124
+ assert.match(instructions, /GOOGLE_TAGMANAGER_CLIENT_ID/);
125
+ assert.match(instructions, /restart/);
126
+
127
+ const { tools } = await client.listTools();
128
+ assert.deepEqual(tools.map((t) => t.name).sort(), ALL_TOOLS);
129
+
130
+ // A tool call fails with the exact message instead of killing the server.
131
+ const result = await client.callTool({ name: "list_accounts", arguments: {} });
132
+ assert.equal(result.isError, true);
133
+ const text = result.content.map((c) => c.text ?? "").join(" ");
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/);
139
+ assert.match(text, /restart the server/);
140
+ } finally {
141
+ await client.close();
142
+ }
73
143
  });
74
144
 
75
145
  test("dist client rejects foreign-origin paths before sending the token", async () => {