GTM MCP Server
[!IMPORTANT] The hosted instance at
mcp.gtmeditor.comwas shut down during the night of 20–21 November 2026. There is no longer a public endpoint: to keep using the server, self-host it. Removehttps://mcp.gtmeditor.comfrom every MCP client configuration. The domain is not being renewed, so a future owner could serve something else at that address. See #139 for background. Thanks to everyone who used it!
[!NOTE] This project is in maintenance mode. It is feature-complete and will not get new features. Only security fixes will be merged. If you want an actively maintained GTM MCP server, or a hosted endpoint with no setup, use stape-io/google-tag-manager-mcp-server. See Alternatives.
GTM MCP Server connects MCP clients to the Google Tag Manager API. It can inspect containers, create and update workspace entities, create versions, and publish a selected version after explicit confirmation.
The repository also ships gtm-cli, a command-line tool
that gives people and agents direct GTM access with no server to host.
It authenticates either with browser-based Google OAuth (each user acts with their own Google identity and GTM permissions) or with a Google service account (one shared identity, for automation or a single local user).
Contents
- Project status
- Command-line interface
- Choose a deployment mode
- Self-hosting
- Connect an MCP client
- Typical workflow
- Tools
- Safety model
- Resources and Prompts
- Skills
- Configuration reference
- Releases
- Development
- Alternatives
Project status
| Item | Current state |
|---|---|
Version in server.json |
1.15.0 |
| Transport | MCP Streamable HTTP, or stdio for local service-account use |
| Runtime tools | 64 GTM tools by default; 94 with GTM_TOOL_GROUPS=all; plus 2 utility tools in both cases |
| MCP resources | 8 resource definitions (2 resources, 6 URI templates) |
| MCP prompts | 6 prompts |
| Official GTM API coverage | 101 of 106 methods |
| Hosted endpoint | None. mcp.gtmeditor.com was shut down on 20–21 November 2026 |
| Maintenance | Feature-complete. Security fixes only |
The project implements 101 methods from Google's 106-method GTM v2 discovery
surface. The five accounts.user_permissions methods are intentionally
excluded: granting and revoking GTM access is security-sensitive and should not
be managed by an LLM.
Command-line interface
gtm-cli calls the Tag Manager API from your own machine, for shells, scripts and
agents such as Claude Code, Codex and Cursor. There is no server, MCP client
configuration or API key. It covers account, container and workspace discovery,
tag, trigger and variable create, read, update and delete, workspace status, and
version creation and publication. The MCP server covers the rest of the API.
Install
With Go 1.26 or later:
go install github.com/paolobietolini/gtm-mcp-server/cmd/gtm-cli@latest
Releases also attach prebuilt archives named
gtm-cli_<version>_<os>_<arch> to the
release page. From a
clone:
go build -o bin/gtm-cli ./cmd/gtm-cli
Authenticate
Enable the Tag Manager API in a Google
Cloud project. gtm-cli finds credentials as stdio mode does:
GOOGLE_SERVICE_ACCOUNT_KEY_JSON, then Application Default Credentials (the file
in GOOGLE_APPLICATION_CREDENTIALS, then the gcloud login file, then the service
account attached on Google Cloud).
The plain gcloud login is not enough. gcloud auth application-default login
does not request Tag Manager scopes by default. Adding them to --scopes uses
gcloud's own OAuth client, which Google can reject with "This app is blocked"
(troubleshooting).
Use one of these instead.
Option 1: your own OAuth client, to act as yourself. In the Google Cloud project, configure the OAuth consent screen, create an OAuth client of type Desktop app and download its JSON file. While an external consent screen is in Testing, add yourself as a test user; Google expires those logins after 7 days.
SCOPES=https://www.googleapis.com/auth/cloud-platform
SCOPES+=,https://www.googleapis.com/auth/userinfo.email
for s in delete.containers edit.containers edit.containerversions manage.accounts publish; do
SCOPES+=,https://www.googleapis.com/auth/tagmanager.$s
done
gcloud auth application-default login \
--client-id-file=client_secret.json --scopes="$SCOPES"
Request fewer tagmanager scopes to limit what the CLI can do, for example only
tagmanager.readonly for audits.
Option 2: a service account, for automation. Create it and add it to GTM as in step 2b, then either point to its key file:
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/sa.json
or impersonate it without a key. This needs the IAM Service Account Credentials API and the Service Account Token Creator role on that account:
gcloud auth application-default login \
--impersonate-service-account=gtm-mcp@PROJECT_ID.iam.gserviceaccount.com
Check the result:
gtm-cli auth status
It prints the credential source and type, the account email when Google reports one, the quota project, and granted and missing scopes. It exits with code 3 if the credentials have no Tag Manager scope.
If a request fails for lack of a quota project, run
gcloud auth application-default set-quota-project PROJECT_ID.
Use
gtm-cli accounts list --output table
gtm-cli containers list --account 123
gtm-cli workspaces list --account 123 --container 456
export GTM_ACCOUNT_ID=123 GTM_CONTAINER_ID=456 GTM_WORKSPACE_ID=7
gtm-cli tags list
gtm-cli tags create --file tag.json --dry-run
gtm-cli tags create --file tag.json
gtm-cli tags delete --tag-id 12 --confirm
gtm-cli workspaces status
gtm-cli versions create --name "Add sign_up event" --notes "GA4 sign_up on form submit"
gtm-cli versions publish --version-id 9 --confirm
gtm-cli versions get --live
gtm-cli help lists every command and gtm-cli <noun> <verb> --help its flags. A command
gtm-cli <nouns> <verb> matches the MCP tool verb_noun.
Missing --account, --container and --workspace flags are read from the
environment variables above, then from $XDG_CONFIG_HOME/gtm-cli/config.json
(normally ~/.config/gtm-cli/config.json), or from the file named by GTM_CONFIG:
{"accountId": "123", "containerId": "456", "workspaceId": "7"}
No configuration is read from the working directory, including .env.
--file takes a JSON object (- reads stdin):
{
"name": "HTML - Banner",
"type": "html",
"firingTriggerId": ["12"],
"parameter": [{"type": "template", "key": "html", "value": "<script></script>"}]
}
Parameter and condition shapes are in
tool-input-formats.md; the
gtm-cli skill lists the keys for each entity.
Unknown keys are rejected. On update, tags keep every omitted key; triggers and
variables require name and type and keep other omitted keys.
Review a workspace before versioning
gtm-cli workspaces status lists each entity the workspace adds, updates or
deletes, and each merge conflict:
{"status": {"hasChanges": true, "hasConflicts": false, "changeCount": 1, "conflictCount": 0,
"changes": [{"type": "tag", "id": "4", "name": "GA4 - purchase", "changeStatus": "updated"}],
"conflicts": []}}
--entities adds each entity in full, in the shape of the collections that
gtm-cli versions get --latest returns, so the two can be compared field by
field. examples/workspace-diff.sh pairs them and
runs diff -u on each changed entity:
--- tag/4 "GA4 - purchase" in the latest version
+++ tag/4 "GA4 - purchase" in the workspace (updated)
@@ -14,7 +14,7 @@
{
"key": "measurementIdOverride",
"type": "template",
- "value": "G-OLD"
+ "value": "G-NEW"
}
The comparison is with the latest version, which the workspace is based on, not with the live version. Update an out-of-date workspace first.
Output and exit codes
API commands print JSON with the same shape as the matching MCP tool's output;
--output table is for reading. Errors are JSON on stderr:
{"error": {"code": "not_found", "message": "resource not found: ..."}}
| Exit | error.code |
|---|---|
| 0 | success |
| 1 | api_error, cancelled, error |
| 2 | usage, invalid_input, invalid_request |
| 3 | auth |
| 4 | permission_denied |
| 5 | not_found |
| 6 | conflict, precondition_failed |
| 7 | rate_limited |
| 8 | confirmation_required |
A command gives up after two minutes. If a write ends in exit code 1, check the container before retrying: the change may have been applied.
Safeguards
deleteandpublishcommands require--confirm.versions createrefuses a workspace without changes or with merge conflicts.- Every command that writes accepts
--dry-run, which prints the request and sends no write. An update still reads the current entity, to show the full body that would be sent. A dry run needs no--confirm.
Choose a deployment mode
| Mode | Who it is for | Google identity used | How the client authenticates |
|---|---|---|---|
| stdio | One person, on their own machine | A service account | None: the MCP client starts the binary as a local process |
| HTTP + OAuth | Teams and agencies; every user keeps their own GTM permissions | Each user's own Google account | Browser sign-in with Google, handled by the MCP client |
| HTTP + service account | Automation, CI, agents, or a team that deliberately shares one identity | One service account for every caller | Static header Authorization: Bearer <SERVICE_ACCOUNT_API_KEY> |
| HTTP + OAuth + service account | Both of the above on one server | Per request: the API key selects the service account, any other bearer token is an OAuth user | Either of the two above |
Where the client connects from matters for remote (HTTP) deployments:
- Claude Code, Cursor, VS Code, Gemini CLI, Codex CLI and other local clients connect from the user's machine. A hostname reachable only on your corporate network or VPN works.
- Web connectors (Claude on the web, ChatGPT) connect from the provider's cloud. The server must be reachable from the public internet over HTTPS, and these connectors use the OAuth flow, so run OAuth mode for them.
Self-hosting
The steps below describe a production deployment on your own server (VPS,
virtual machine, or on-premises host). Every value written as
gtm-mcp.example.com, PROJECT_ID, or <...> is a placeholder to replace.
Requirements
- One of the following:
- Docker with Docker Compose v2 (recommended), or
- a prebuilt binary from the release page (Linux, macOS, and Windows; amd64 and arm64), or
- Go 1.26 or later to build from source (
go.moddeclaresgo 1.26.0).
- A Google Cloud project in which you can enable APIs and create credentials.
- For OAuth mode: a dedicated hostname (for example
gtm-mcp.example.com) with HTTPS. The server listens on plain HTTP only, so TLS is terminated by a reverse proxy in front of it. - For service-account mode: the right to add a user to the GTM accounts or containers the server should manage.
Constraints that follow from how the server works:
- Serve it at the root of its own hostname. All routes (
/,/authorize,/oauth/callback,/token,/register,/health, and/.well-known/...) are registered at the root. A path prefix such ashttps://example.com/gtmis not supported. - Run a single instance in OAuth mode. MCP HTTP requests are stateless,
but OAuth state, authorization codes, registered clients, and issued tokens
live in the memory of one process (tokens can additionally be persisted to
one local file). A second replica does not know the tokens issued by the
first one, and users get random
401responses. Service-account-only deployments have no such state and can run several replicas. - Persist the token store. Without
TOKEN_STORE_PATH, every restart or redeploy signs all OAuth users out. Platforms with an ephemeral filesystem that scale instances up and down (for example Cloud Run) are therefore a poor fit for OAuth mode; they work for service-account mode.
Step 1: Enable the Tag Manager API
In the Google Cloud console, open APIs & Services → Library, search for Tag Manager API, and click Enable. With the gcloud CLI:
gcloud services enable tagmanager.googleapis.com --project=PROJECT_ID
No Google Cloud IAM role is needed to call the Tag Manager API. What a credential can do in GTM is decided only by GTM's own user management.
Step 2a: Create the OAuth client (OAuth mode)
Skip this step if you use only service-account mode.
In the Google Cloud console, open Google Auth Platform (formerly "OAuth consent screen").
Branding: set the app name users will see on the consent screen, a user support email, and a developer contact email.
Audience: choose who may sign in. This is the server's only sign-in restriction: the server itself has no allowlist of users or domains.
- Internal (available only when the project belongs to a Google Workspace or Cloud Identity organization): only members of your organization can authorize. This is the recommended choice for a company. If your Workspace administrator restricts third-party API access, they may need to allow this app under Security → API controls in the Workspace Admin console.
- External, publishing status "Testing": only the test users you list (at most 100) can authorize, and Google expires their authorization seven days after consent. Users then have to sign in again each week. Suitable only for a trial.
- External, publishing status "In production": any Google account can authorize. Until Google verifies the app, users may see an "unverified app" warning and Google may cap the number of users. Check the Verification Center page for your project's requirements.
Data Access (recommended): declare the scopes the server requests, so the consent screen and any verification request match what users see:
https://www.googleapis.com/auth/tagmanager.delete.containers https://www.googleapis.com/auth/tagmanager.edit.containers https://www.googleapis.com/auth/tagmanager.edit.containerversions https://www.googleapis.com/auth/tagmanager.manage.accounts https://www.googleapis.com/auth/tagmanager.publishThese five scopes are hard-coded in the server and cannot be reduced by configuration. What a user can actually do is still limited by that user's GTM permissions.
Clients → Create client:
Application type: Web application.
Authorized JavaScript origins: leave empty.
Authorized redirect URIs: add exactly one URI,
BASE_URLfollowed by/oauth/callback:https://gtm-mcp.example.com/oauth/callbackFor a server running on your own computer, add
http://localhost:8080/oauth/callbackinstead (or as well).
Click Create and copy the client ID and client secret. Google shows the secret only at creation time. Store both in your secret manager.
Google's rules for the redirect URI, which explain most
redirect_uri_mismatch errors:
- It must match
BASE_URL + /oauth/callbackcharacter for character: scheme, host, port, and path. The server always builds it this way; there is no separate setting for it. - It must use
https://. Onlylocalhostis allowed overhttp://. - The host cannot be a raw IP address, and its top-level domain must be on the
public suffix list. A name such as
gtm-mcp.example.comthat resolves only inside your network is accepted;gtm-mcp.corp.localis not. - Changes in the console can take from a few minutes to a few hours to apply.
Step 2b: Create the service account (service-account mode and stdio)
Skip this step if you use only OAuth mode.
Create the service account:
gcloud iam service-accounts create gtm-mcp \ --display-name="GTM MCP Server" \ --project=PROJECT_IDIts email address is
gtm-mcp@PROJECT_ID.iam.gserviceaccount.com.Give it access in GTM: in Tag Manager open Admin → User Management (account level, or container level for a single container), click Add, enter the service account email, and grant the lowest permission that covers your use: container Read for audits, Edit to change workspaces, Approve to create versions, Publish to publish. Grant account Administrator only if the server must create or delete containers.
Choose how the server obtains the service account credentials:
On Google Cloud (Compute Engine, GKE, Cloud Run): attach the service account to the workload. The server uses Application Default Credentials, and no key file is needed.
Anywhere else: create a JSON key:
gcloud iam service-accounts keys create sa.json \ --iam-account=gtm-mcp@PROJECT_ID.iam.gserviceaccount.comMany organizations block key creation with the organization policy
iam.disableServiceAccountKeyCreation(enforced by default in newer organizations). If the command is refused, ask your Google Cloud administrator for an exception or run the server on Google Cloud with an attached service account. Treatsa.jsonas a password: anyone holding it has the service account's GTM permissions.
For HTTP mode, generate the API key that clients will send:
openssl rand -hex 32Anyone who has this key acts as the service account in GTM. Share it only through a secret manager and rotate it by changing the value and restarting the server.
Step 3: Write the configuration
The server is configured only through environment variables. They can also be
placed in a .env file; the full list is in the
configuration reference.
OAuth mode for a team (.env):
BASE_URL=https://gtm-mcp.example.com
GOOGLE_CLIENT_ID=<client-id>.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=<client-secret>
TOKEN_STORE_PATH=/data/tokens.json
TRUST_PROXY=true
Service-account mode (.env):
BASE_URL=https://gtm-mcp.example.com
SERVICE_ACCOUNT_API_KEY=<output of openssl rand -hex 32>
GOOGLE_APPLICATION_CREDENTIALS=/secrets/sa.json
TRUST_PROXY=true
For both modes on one server, combine the two files. Omit
GOOGLE_APPLICATION_CREDENTIALS when the server runs on Google Cloud with an
attached service account.
Rules that avoid the most common mistakes:
BASE_URLis the public HTTPS URL users and clients reach, with no trailing slash and no path. A trailing slash produces URLs such ashttps://gtm-mcp.example.com//oauth/callback, which do not match the redirect URI registered with Google.- Do not put quotes around values.
docker run --env-filepasses quotes through as part of the value. - Values that cannot be parsed are silently replaced by their defaults:
durations (
ACCESS_TOKEN_TTL,AUTH_AUTO_REFRESH_MAX_AGE) must use Go duration syntax such as8h,90m, or168h(7dis not valid); booleans accepttrue/falseor1/0. An unknown name inGTM_TOOL_GROUPSorMCP_TRANSPORTinstead stops the server at startup. TRUST_PROXY=trueis correct only with exactly one reverse proxy in front of the server that setsX-Forwarded-For(the setups below). Without a proxy, leave itfalse.- When neither OAuth nor an API key is configured, the server starts in
open mode: anyone who can reach it can call the MCP endpoint, and the
log shows
No authentication configured. Never expose open mode beyond your own machine.
Step 4: Run the server
Pick one of the three options.
Option A: Docker Compose with Caddy (recommended)
Caddy terminates HTTPS and obtains certificates automatically. On the server:
git clone https://github.com/paolobietolini/gtm-mcp-server.git
cd gtm-mcp-server
git checkout v1.15.0 # use the latest tag from the release page
Create .env as in step 3 (with TOKEN_STORE_PATH=/data/tokens.json for
OAuth mode). The repository's .gitignore already excludes .env,
docker-compose.yml, and Caddyfile.
Create docker-compose.yml:
services:
gtm-mcp:
build: .
image: gtm-mcp-server:local
restart: unless-stopped
env_file: .env
volumes:
- gtm-mcp-data:/data
# Service-account mode with a key file only:
# - ./secrets/sa.json:/secrets/sa.json:ro
caddy:
image: caddy:2
restart: unless-stopped
depends_on:
- gtm-mcp
ports:
- "80:80"
- "443:443"
- "443:443/udp"
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
- caddy-data:/data
- caddy-config:/config
volumes:
gtm-mcp-data:
caddy-data:
caddy-config:
Create Caddyfile:
gtm-mcp.example.com {
reverse_proxy gtm-mcp:8080
}
Start it:
docker compose up -d --build
docker compose logs -f gtm-mcp
Notes for this setup:
- The
gtm-mcpservice publishes no port; only Caddy is reachable from outside. - Caddy can obtain a public certificate only when
gtm-mcp.example.comresolves publicly to this machine and ports 80 and 443 are reachable from the internet. For a host reachable only internally, replace the site block's automatic certificate with your organization's certificate (tls /path/to/cert.pem /path/to/key.pem, mounted into the Caddy container) or use a Caddy DNS-challenge plugin. - Keep
PORTunset (8080) inside the container: the image'sHEALTHCHECKalways probeshttp://localhost:8080/health. - The image runs as the non-root user
appuserand creates/dataowned by that user with mode700. A named volume, as above, inherits that ownership on first use. If you bind-mount a host directory to/datainstead, make it owned by the container user's UID. - A mounted
sa.jsonmust be readable by the container user. Find its UID withdocker compose run --rm --no-deps --entrypoint id gtm-mcp, then runsudo chown <uid> secrets/sa.json && chmod 400 secrets/sa.json. - To upgrade:
git fetch --tags && git checkout <new tag> && docker compose up -d --build. Tokens survive in thegtm-mcp-datavolume.
If you already run a reverse proxy on the host, skip Caddy and publish the server on the loopback interface only:
docker build -t gtm-mcp-server:local .
docker run -d \
--name gtm-mcp-server \
--restart unless-stopped \
-p 127.0.0.1:8080:8080 \
--env-file .env \
-v gtm-mcp-data:/data \
gtm-mcp-server:local
Option B: Prebuilt binary with systemd
VERSION=1.15.0 # latest version from the release page
ARCH=amd64 # or arm64
curl -fsSLO "https://github.com/paolobietolini/gtm-mcp-server/releases/download/v${VERSION}/gtm-mcp-server_${VERSION}_linux_${ARCH}.tar.gz"
curl -fsSLO "https://github.com/paolobietolini/gtm-mcp-server/releases/download/v${VERSION}/gtm-mcp-server_${VERSION}_checksums.txt"
sha256sum --check --ignore-missing "gtm-mcp-server_${VERSION}_checksums.txt"
tar -xzf "gtm-mcp-server_${VERSION}_linux_${ARCH}.tar.gz"
sudo install -m 0755 gtm-mcp-server /usr/local/bin/gtm-mcp-server
Create a system user, a data directory, and the configuration file:
sudo useradd --system --home-dir /var/lib/gtm-mcp --shell /usr/sbin/nologin gtm-mcp
sudo install -d -o gtm-mcp -g gtm-mcp -m 0700 /var/lib/gtm-mcp
sudo install -d -o root -g gtm-mcp -m 0750 /etc/gtm-mcp
sudoedit /etc/gtm-mcp/gtm-mcp.env
sudo chown root:gtm-mcp /etc/gtm-mcp/gtm-mcp.env
sudo chmod 0640 /etc/gtm-mcp/gtm-mcp.env
Use the content from step 3 in /etc/gtm-mcp/gtm-mcp.env, with
TOKEN_STORE_PATH=/var/lib/gtm-mcp/tokens.json and, for a key file,
GOOGLE_APPLICATION_CREDENTIALS=/etc/gtm-mcp/sa.json (owner root:gtm-mcp,
mode 0640).
Create /etc/systemd/system/gtm-mcp.service:
[Unit]
Description=GTM MCP Server
After=network-online.target
Wants=network-online.target
[Service]
User=gtm-mcp
Group=gtm-mcp
WorkingDirectory=/var/lib/gtm-mcp
EnvironmentFile=/etc/gtm-mcp/gtm-mcp.env
ExecStart=/usr/local/bin/gtm-mcp-server
Restart=on-failure
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/lib/gtm-mcp
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now gtm-mcp
journalctl -u gtm-mcp -f
The binary listens on PORT (default 8080) on all interfaces. Put a reverse
proxy in front of it (see below) and block direct access to that port with
your firewall.
Option C: From source
Requires Go 1.26 or later.
git clone https://github.com/paolobietolini/gtm-mcp-server.git
cd gtm-mcp-server
git checkout v1.15.0 # or stay on main for unreleased changes
go build -o gtm-mcp-server .
./gtm-mcp-server
The server reads .env from the current working directory, then
.env.local. Variables already set in the process environment take
precedence over .env, and .env.local overrides both. Both files are ignored
by Git. For quick local testing, go run . with this .env is enough:
BASE_URL=http://localhost:8080
GOOGLE_CLIENT_ID=<client-id>.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=<client-secret>
TOKEN_STORE_PATH=./data/tokens.json
Reverse proxy requirements
Any reverse proxy works if it:
- forwards every path of the hostname to the server unchanged;
- passes the
Authorizationheader through; - does not buffer responses: the MCP endpoint can answer with a
text/event-stream(Server-Sent Events) response; - allows request bodies up to 5 MiB, the server's own limit;
- sets
X-Forwarded-For(required for per-client rate limits withTRUST_PROXY=true).
Caddy does all of this with the two-line reverse_proxy configuration above.
For nginx:
server {
listen 443 ssl;
server_name gtm-mcp.example.com;
ssl_certificate /etc/ssl/gtm-mcp/fullchain.pem;
ssl_certificate_key /etc/ssl/gtm-mcp/privkey.pem;
client_max_body_size 5m;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 1h;
}
}
X-Forwarded-For $remote_addr overwrites any value sent by the client, which
is what the server expects with one proxy hop. If a load balancer or CDN sits
in front of this proxy, the rightmost X-Forwarded-For entry is that
intermediary's address, so all users share one rate-limit bucket: configure
your proxy to restore the real client address first.
Step 5: Verify the deployment
Health check, which needs no authentication:
curl -sS https://gtm-mcp.example.com/healthExpected:
{"service":"gtm-mcp-server","status":"healthy","version":"1.15.0"}.OAuth metadata (OAuth mode):
curl -sS https://gtm-mcp.example.com/.well-known/oauth-protected-resourceresourcemust behttps://gtm-mcp.example.com/andauthorization_serversmust containhttps://gtm-mcp.example.com. If they showhttp://or another host,BASE_URLis wrong.Unauthenticated MCP request:
curl -sS -i -X POST https://gtm-mcp.example.com/Expected:
HTTP/... 401with the headerWWW-Authenticate: Bearer resource_metadata="https://gtm-mcp.example.com/.well-known/oauth-protected-resource". Any other status means the server is running in open mode.API key (service-account mode):
curl -sS https://gtm-mcp.example.com/ \ -H "Authorization: Bearer $SERVICE_ACCOUNT_API_KEY" \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"curl","version":"1.0"}}}'Expected: a JSON-RPC result containing
"serverInfo":{"name":"gtm-mcp-server",...}, possibly wrapped in an SSEdata:line. This checks the API key only, not the Google credentials.Startup log lines to look for (JSON on stderr):
OAuth configuredandtoken persistence enabledin OAuth mode;s2s_mode_enabledwithcredential_sourcekey_jsonorworkload_identity(the latter also coversGOOGLE_APPLICATION_CREDENTIALS) in service-account mode. If the credentials cannot be loaded, the server logss2s_mode_failedand exits.
End-to-end: connect a client (next section) and ask it to "List my GTM accounts. Do not make changes." An empty list means the authenticated Google identity has no GTM access yet (step 2b, item 2, for a service account). An error saying the Tag Manager API is disabled or has not been used in the project means step 1 was skipped for the project that owns the OAuth client or service account.
Operating notes
- Token file.
TOKEN_STORE_PATHholds every user's MCP tokens and Google OAuth tokens, including Google refresh tokens, as plain JSON (file mode0600, written atomically). Treat it like a password database: restrict access to the host, and exclude it from unencrypted backups. Deleting it signs everyone out. - Revoking a user. A user can revoke the app's access at https://myaccount.google.com/permissions. The server can then no longer refresh that user's Google token, so their GTM calls fail and they must sign in again. Removing a user from GTM's User Management removes their GTM access regardless of what the server holds.
- Session lifetime. MCP access tokens last
ACCESS_TOKEN_TTL(8 hours by default). After expiry the server renews them silently while the Google refresh token is valid, for at mostAUTH_AUTO_REFRESH_MAX_AGE(7 days) after issue; then the client must complete a refresh, or a new sign-in. - Rate limits.
/authorize,/oauth/callback, and/tokenallow 10 requests per second per client IP (burst 20);/registerallows 2 per second (burst 5). - Logs. Set
LOG_LEVEL=debugfor per-request authentication details. Authentication logs identify tokens by a fingerprint, not by their value.
Stdio mode (single local user)
For one person on their own machine, the MCP client can start the server as a
local process over stdin/stdout. No HTTP server, OAuth client, reverse proxy,
or API key is involved. Stdio mode always uses service-account credentials
(step 2b): GOOGLE_SERVICE_ACCOUNT_KEY_JSON, or a key file named by
GOOGLE_APPLICATION_CREDENTIALS, or Application Default Credentials.
Install the binary (Option B above, first block only), then test it:
GOOGLE_APPLICATION_CREDENTIALS=/path/to/sa.json gtm-mcp-server --stdio
The process waits for MCP messages on stdin; stop it with Ctrl+C.
Claude Code example (.mcp.json):
{
"mcpServers": {
"gtm": {
"command": "/usr/local/bin/gtm-mcp-server",
"args": ["--stdio"],
"env": {
"GOOGLE_APPLICATION_CREDENTIALS": "/path/to/sa.json",
"GTM_TOOL_GROUPS": "all"
}
}
}
}
MCP_TRANSPORT=stdio is equivalent to the --stdio argument. Logs go to
stderr; stdout carries only MCP messages. The server also reads .env from the
directory the client starts it in.
Optional setup dashboard
Set DASHBOARD_ENABLED=true and restart the server to expose /dashboard/.
The page shows the canonical MCP endpoint, server version, authentication setup
status, and connection instructions. It is disabled by default.
The dashboard is public when enabled. It deliberately excludes tokens, sessions, account names, container data, and other GTM content. It reports server configuration only and does not verify the visitor's Google session.
Connect an MCP client
The MCP endpoint is your BASE_URL itself, for example
https://gtm-mcp.example.com. In OAuth mode the client discovers the OAuth
metadata, opens Google sign-in in the browser, and reconnects with the issued
bearer token. In service-account mode the client sends the API key in the
Authorization header on every request.
Claude Code
# OAuth mode
claude mcp add --transport http gtm https://gtm-mcp.example.com
# Service-account mode
claude mcp add --transport http gtm https://gtm-mcp.example.com \
--header "Authorization: Bearer <SERVICE_ACCOUNT_API_KEY>"
Gemini CLI
gemini mcp add --transport http gtm https://gtm-mcp.example.com
Or in settings.json (remove headers for OAuth mode):
{
"mcpServers": {
"gtm": {
"httpUrl": "https://gtm-mcp.example.com",
"headers": {
"Authorization": "Bearer <SERVICE_ACCOUNT_API_KEY>"
}
}
}
}
Cursor
Add the following to .cursor/mcp.json (remove headers for OAuth mode):
{
"mcpServers": {
"gtm": {
"url": "https://gtm-mcp.example.com",
"headers": {
"Authorization": "Bearer <SERVICE_ACCOUNT_API_KEY>"
}
}
}
}
VS Code
Add the following to .vscode/mcp.json (OAuth mode):
{
"servers": {
"gtm": {
"type": "http",
"url": "https://gtm-mcp.example.com"
}
}
}
ChatGPT, Codex, and Claude on the web
Add a custom or remote MCP connection in the client and use your BASE_URL as
the server URL. Web connectors require a server reachable from the public
internet and OAuth mode. Product menus change more often than this server, so
refer to the client's current MCP connection instructions if the label
differs.
After connecting, try:
List my GTM accounts, containers, and workspaces. Do not make changes.
The Google identity used (the account chosen at sign-in, or the service account) determines which GTM accounts the server can access.
Typical workflow
- Call
list_accounts,list_containers, andlist_workspacesto discover IDs. Do not guess IDs. - Inspect the workspace with list/get tools or the
audit_containerprompt. - Create or update tags, triggers, variables, templates, clients, or transformations in the selected workspace.
- Call
get_workspace_statusand resolve conflicts before versioning. - Call
create_versionto snapshot the workspace. - Inspect the saved version with
get_version. - Call
publish_versionwithconfirm: trueonly when the selected version is ready to go live. - Verify the published state with
get_live_version.
Example requests:
- "Audit this workspace for duplicate tags and unused triggers."
- "Create a GA4 purchase event tag, but do not publish it."
- "Show the difference between the latest saved version and the live version."
- "Generate a Markdown tracking plan from this workspace."
- "Import the iubenda template from the Community Template Gallery."
Tools
All GTM tools use the authenticated Google identity from the current MCP request. Inputs and outputs are structured JSON.
Tools marked opt-in belong to a tool group that is not enabled by default.
Enable it through GTM_TOOL_GROUPS (see Tool groups).
Utility
Always available, regardless of GTM_TOOL_GROUPS.
| Tool | Purpose |
|---|---|
ping |
Test MCP connectivity |
auth_status |
Check whether the current request is authenticated |