GA4 and GTM remote MCP server
by manish31-oss
README.md
# GA4 and GTM remote MCP server
A self-hosted [MCP](https://modelcontextprotocol.io) server that gives an AI assistant access to **Google Analytics 4** and **Google Tag Manager** through your own Google account. It runs on Vercel and sign-in is with Google.
It serves two endpoints, one per connector:
| Endpoint | Connector |
|---|---|
| `https://<your-domain>/mcp/ga` | Google Analytics 4: reports and property settings, optional writes |
| `https://<your-domain>/mcp/gtm` | Google Tag Manager: accounts, containers, workspaces, tags, triggers, variables, versions and more |
Both endpoints use stateless Streamable HTTP with the MCP authorization flow (OAuth 2.1). They are tested as claude.ai custom connectors: in claude.ai go to **Settings → Connectors → Add custom connector**, paste the endpoint URL and leave the OAuth client fields empty.
## How sign-in works
1. The MCP client finds the login by itself: a `401` response, `.well-known` metadata, dynamic client registration, and PKCE (S256).
2. The server's consent page shows which client is asking and which host you will be sent back to. Continue only if you started the connection yourself.
3. On the consent page you pick an **access level** for that connection: **Read-only** (the default) or **Read and write**.
4. **Continue with Google** opens Google's account picker. The server accepts the sign-in only if all three hold:
- the email is verified and is on `ALLOWED_GOOGLE_EMAILS`;
- the browser is the one that clicked Continue;
- Google granted **every** scope for the chosen level.
Anything else is rejected, and any Google grant that was made is revoked.
5. Each connection keeps its own Google refresh token, encrypted (AES-256-GCM) in the store. Google tokens never leave the server, and the server's own tokens are never sent to Google.
**Switching Google accounts or access level:** remove the connector in your MCP client and add it again.
### Google scopes per connection
Every connection also asks for `openid email`.
| Connector | Read-only | Read and write |
|---|---|---|
| GA | `analytics.readonly` | `analytics.readonly` + `analytics.edit` |
| GTM | `tagmanager.readonly` | `tagmanager.readonly`, `edit.containers`, `edit.containerversions`, `publish`, `delete.containers`, `manage.accounts`, `manage.users` |
Read-only is enforced twice:
- Google refuses writes for read-only tokens.
- The server doesn't offer writes on a read-only connection. GA doesn't register its write tools, and GTM rejects every action that isn't a read.
On **Read and write**, the tool list is the only limit. For example, an `analytics.edit` token could do more than the 11 GA write tools allow.
## Tools
### GA (34 tools)
Every GA connection gets 23 read tools. **Read and write** connections get 11 more (**W**).
**alpha** means the tool uses Google's v1alpha API. Its description starts with "(alpha, may change)".
| Tools | Level | Notes |
|---|---|---|
| `get_account_summaries`, `get_property_details`, `list_google_ads_links`, `list_key_events`, `get_custom_dimensions_and_metrics` | read | Lists accept `page_token` |
| `run_report`, `run_realtime_report` | read | Totals, min and max; keep empty rows; quota; filters; realtime minute ranges |
| `get_metadata`, `check_compatibility` | read | Find valid field names and check combinations before running a report |
| `run_pivot_report`, `batch_run_reports` (max 5) | read | |
| `run_funnel_report`, `get_property_quotas_snapshot` | read, alpha | Data API v1alpha |
| `run_access_report` | read | Property or account level. Google returns data only for GA4 360 properties |
| `list_data_streams`, `list_firebase_links`, `get_data_retention_settings` | read | |
| `list_bigquery_links`, `list_audiences`, `list_channel_groups`, `list_calculated_metrics`, `list_annotations`, `get_enhanced_measurement_settings` | read, alpha | |
| `create_key_event`, `update_key_event`, `delete_key_event` | W | |
| `create_custom_dimension`, `update_custom_dimension`, `create_custom_metric`, `update_custom_metric` | W | No archive tool. `disallow_ads_personalization` can be set only at creation (Google rejects it in an update) |
| `create_annotation`, `update_annotation`, `delete_annotation` | W, alpha | |
| `search_change_history_events` | W | A read, but Google requires `analytics.edit` |
Every successful GA write logs one `GA_WRITE` audit line with the tool, property, resource and connection. It contains no values and no emails.
### GTM (18 tools)
There is one tool per resource, and each takes an `action`:
`gtm_account`, `gtm_container`, `gtm_workspace`, `gtm_tag`, `gtm_trigger`, `gtm_variable`, `gtm_built_in_variable`, `gtm_folder`, `gtm_template`, `gtm_client`, `gtm_transformation`, `gtm_zone`, `gtm_gtag_config`, `gtm_destination`, `gtm_environment`, `gtm_version`, `gtm_version_header`, `gtm_user_permission`.
- **Read-only connections** allow only these actions: `get`, `list`, `latest`, `live`, `lookup`, `snippet`, `getStatus` and `entities`.
- Listing user permissions needs `manage.users`, so it fails on read-only connections.
## Deploy your own (Vercel)
What you need: a Vercel account, an Upstash Redis database (the free tier is enough), and a Google Cloud project. Vercel's Hobby plan is for non-commercial use.
1. **Fork** this repo and import it into Vercel. It needs no build settings, because `vercel.json` sets up the routes.
2. **Store:** add the Upstash integration in Vercel, or set `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` yourself.
3. **Google Cloud**, in your project:
1. Enable the **Google Analytics Data API**, the **Google Analytics Admin API** and the **Tag Manager API**.
2. Create an OAuth client of type **Web application**. Its authorized redirect URI is `https://<your-domain>/oauth/google/callback`.
3. Set up the OAuth consent screen (**Google Auth Platform**): user type **External**, publishing status **In production**.
- Testing status expires refresh tokens after 7 days.
- An unverified app shows Google's "unverified app" warning on each new sign-in, and is limited to 100 users over its lifetime.
- Google says to list every scope you request on the Data Access page.
4. **Environment variables** go in the Vercel dashboard (see the table below and `.env.example`), then deploy.
5. **Add the connector** in claude.ai: `https://<your-domain>/mcp/ga` and/or `/mcp/gtm`.
**Custom domain:** `*.vercel.app` hosts are allowed by default. Add your own domain to `ALLOWED_HOSTS`.
**Staging (optional):** use a Vercel Preview environment with its own `OAUTH_SECRET`, plus a second redirect URI on the same Google client.
- Store keys are prefixed per environment (`prd:`, `stg:`, `dev:`), so one Upstash database can serve both.
- Both environments share the Google client. Revoking the app at myaccount.google.com therefore cuts that account off in both.
### Environment variables
Never commit these.
| Var | Rule |
|---|---|
| `OAUTH_SECRET` | Random, 32 characters or more. It signs the server's tokens. Use a different value per environment. |
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | The Google **Web application** OAuth client. The ID ends with `.apps.googleusercontent.com`. |
| `TOKEN_ENC_KEY` | Generate with `openssl rand -base64 32`: base64 of exactly 32 bytes. It encrypts the stored Google credentials. |
| `ALLOWED_GOOGLE_EMAILS` | Comma-separated; case and spaces are ignored. Empty means every sign-in is rejected. |
| `UPSTASH_REDIS_REST_URL` / `UPSTASH_REDIS_REST_TOKEN` | The token store. `KV_REST_API_URL` / `KV_REST_API_TOKEN` from Vercel's integration also work. |
| `ALLOWED_HOSTS` | Optional. Comma-separated extra hosts, for example a custom domain. |
| `OAUTH_PASSPHRASE` | Optional, 12 to 256 characters. If set, the consent page also asks for it. |
If the Google client, secret or key is missing or invalid, **Continue with Google** shows a "not configured" page. On Vercel without a store, the token endpoint returns `503` and MCP calls fail closed.
## Security and limits
- **Tokens:**
- Access tokens last 1 hour.
- Refresh tokens last 30 days, sliding, with a 90-day absolute cap, and rotate on every use.
- Presenting an old refresh token revokes the whole connection, including its live access tokens.
- Auth codes are single-use, and a replayed code revokes what the first use issued.
- **Audience:** a token's audience is the exact resource URL (`https://<host>/mcp/<route>`). A token for one route or host is rejected on another.
- **Rate limits:**
- 10 login submissions per minute per IP. This fails closed if the store is down.
- 20 client registrations per hour per IP.
- 60 OAuth requests per minute per IP.
- 60 MCP requests per minute per route.
- 3,000 refreshes per connection.
- **Rotating and revoking:**
- Change `OAUTH_SECRET` to revoke every connection.
- Changing `TOKEN_ENC_KEY` makes stored Google credentials unreadable, so every connector must be re-added.
- To revoke Google access, go to myaccount.google.com/permissions, then re-add the connector.
## Local development
```bash
npm install
cp .env.example .env # fill in values; without Upstash an in-memory store is used locally
npm run dev # http://127.0.0.1:8799/mcp/ga and /mcp/gtm
npm run typecheck
npx tsx scripts/check-google.mts # unit checks: config, crypto, scopes
npx tsx scripts/check-ga.mts # GA tools against a stubbed Google
npm run smoke # end-to-end OAuth and tool checks against a mock Google and store
```
To test by hand, use the MCP Inspector (`npx @modelcontextprotocol/inspector`) with Streamable HTTP and its OAuth flow.
## Limitations
- Only Vercel with Upstash is supported. Away from Vercel, the server falls back to an in-memory store and the dev server listens on localhost only.
- Alpha (v1alpha) tools can change or break when Google changes them.
- GA: custom dimensions and metrics can't be archived through the server. Archive them in the GA UI.
- GA: the `COUNT` aggregation is offered only on `run_pivot_report`, because Google rejects it on `run_report` and `run_realtime_report`.
## License and credits
Licensed under the [Apache License 2.0](LICENSE). See [NOTICE](NOTICE).
- The GTM tools are derived from [stape-io/google-tag-manager-mcp-server](https://github.com/stape-io/google-tag-manager-mcp-server) (Apache-2.0, Copyright 2025 Stape).
- The original GA read tools are based on [googleanalytics/google-analytics-mcp](https://github.com/googleanalytics/google-analytics-mcp) (Apache-2.0).
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues