Skip to main content
Glama
@mgcrea/mcp-google-search-console

@mgcrea/mcp-google-search-console

by mgcrea
README.md
# @mgcrea/mcp-google-search-console

A [Model Context Protocol](https://modelcontextprotocol.io) server for
[Google Search Console](https://search.google.com/search-console): search performance (clicks,
impressions, CTR, position), period-over-period comparisons, URL Inspection (index status,
canonicals, rich results) and sitemaps.

The server is **read-only by default**. Submitting and deleting sitemaps are not merely refused
when writes are off: those tools are never registered, so an agent cannot call them at all.

## Features

- **Property resolution.** `site` accepts `example.com`, `https://example.com`,
  `https://example.com/` or `sc-domain:example.com`, and resolves it against the properties the
  account can see. A bare domain prefers the domain property; every response says which
  property was read (`site`) and, when it was not the exact id you passed, why
  (`resolved_site`). An unknown property fails with the list of accessible ones.
- **The account is always visible.** The Google account that signed in decides which
  properties exist. Every response carries `account` (its email), and so do
  `gsc_auth_status` and the startup banner.
- **Shaped analytics.** Rows come back as `{query, page, clicks, impressions, ctr, position}`
  instead of positional `keys`, with ratios rounded, `returned_totals` (of the returned rows only), the request
  echoed, and `next_start_row` for paging. Dates default to the 28 days ending 3 days ago in
  Pacific time, Search Console's own day boundary.
- **"What dropped?" in one call.** `gsc_compare_periods` runs both periods and joins them by
  key: top gainers, losers, new and lost queries or pages, and each period's `returned_totals`.
  It fetches 1,000 rows per period by default (`depth`, up to 5,000).
- **URL Inspection that answers the question.** Verdict, coverage, robots/noindex state, last
  crawl, and `canonical_mismatch` when Google chose a different canonical than the page
  declares. `gsc_inspect_urls` does up to 20 at a time, reports `quota_used`, and stops instead
  of burning quota after a quota error.
- **Remedies, not just errors.** 403 permission errors name the signed-in account and how to
  get access; quota errors explain the right quota (load quota vs. inspection quota) and how long
  to wait; `invalid_grant` explains the 7-day Testing expiry.

## Security

- **Read-only by default.** `GSC_ALLOW_WRITES=1` adds `gsc_submit_sitemap` and
  `gsc_delete_sitemap` (which also requires `confirm: true`), and widens `gsc_request` past GET.
- **Least scope.** A read-only install asks only for `webmasters.readonly` (plus `openid email`
  to name the account). Writes ask for `webmasters`.
- **Two runtime dependencies**: the MCP SDK and Zod. Native `fetch` throughout.
- **Your credentials** stay on your machine: the refresh token is stored with mode 600 in
  `~/.config/google-search-console/tokens.json`, and logout revokes it at Google. The API host
  is fixed (`searchconsole.googleapis.com`) and `gsc_request` only reaches `/webmasters/v3/` and
  `/v1/urlInspection/`, so the Google token cannot be pointed at another API.
- Google's **Indexing API** is deliberately not implemented: Google allows it only for
  JobPosting and BroadcastEvent pages.

## Setup

Search Console needs an OAuth client from a Google Cloud project you own. This takes about five
minutes, once.

1. [Create a project](https://console.cloud.google.com/projectcreate). Use a dedicated one,
   e.g. `mcp-search-console`: the consent screen shows its app name.
2. Enable the
   [Google Search Console API](https://console.cloud.google.com/apis/library/searchconsole.googleapis.com).
3. Configure the consent screen in **Google Auth Platform**:
   - **Branding**: an app name and your email.
   - **Audience**: External, then **Publish app**. While the app is in _Testing_, Google expires
     refresh tokens after 7 days. An unverified app in production is fine for your own account;
     you click past one warning at login.
4. Go to **Clients → Create client** and choose application type **Desktop app**. You don't
   register a redirect URI, because Desktop clients accept any loopback port.
5. Set `GSC_CLIENT_ID` and `GSC_CLIENT_SECRET`, and start the server.
6. Ask the agent to call `gsc_auth_login`. It opens the consent screen. Sign in with the Google
   account that has access to your properties in Search Console (an owner can add it under
   **Settings → Users and permissions**).

You don't need to restart afterwards.

## Configure

Environment first, then `~/.config/google-search-console/config.json` (camelCase keys, strict),
field by field.

| Variable            | Required | Description                                                                           |
| ------------------- | -------- | ------------------------------------------------------------------------------------- |
| `GSC_CLIENT_ID`     | yes      | Desktop-app OAuth client id (`….apps.googleusercontent.com`).                         |
| `GSC_CLIENT_SECRET` | yes      | Its secret. Google requires it even with PKCE.                                        |
| `GSC_ALLOW_WRITES`  | no       | `1` to register the sitemap write tools and ask for the `webmasters` scope.           |
| `GSC_REFRESH_TOKEN` | no       | Use this refresh token (memory only) instead of the token file.                       |
| `GSC_TOKEN_FILE`    | no       | Where the login is stored. Defaults to `~/.config/google-search-console/tokens.json`. |
| `GSC_CONFIG`        | no       | Config file path.                                                                     |
| `GSC_MAX_RETRIES`   | no       | Retry budget for 429 / 5xx. Default 3.                                                |
| `GSC_TIMEOUT_MS`    | no       | Per-request timeout. Default 30000.                                                   |
| `GSC_DEBUG`         | no       | `1` to log requests to stderr.                                                        |

If you turn writes on after logging in, `gsc_auth_status` reports the missing scope; log in
again.

A bad setting never stops the server from starting. An out-of-range `GSC_MAX_RETRIES` (0-10) or
`GSC_TIMEOUT_MS` (1000-600000) is clamped, and a non-numeric one falls back to its default. A
malformed config file (invalid JSON, an unknown key such as `clientID`, a wrong type) is ignored
as a whole. Each of these is listed under `config_issues` in `gsc_auth_status` and printed to
stderr at startup.

**The account email** comes from the `email` claim of the `id_token` Google returns at login
(and on refresh), not from a separate userinfo call. With `GSC_REFRESH_TOKEN`, it appears after
the first refresh if that token was granted with `openid email`; otherwise responses say
`account: unknown`.

There is deliberately **no expected-account setting**: every data tool takes an explicit `site`,
so a login with the wrong Google account fails with "no property matches" and the list of what
that account can see, rather than answering with another tenant's data.

## Quotas

From [Google's limits page](https://developers.google.com/webmaster-tools/limits). Quota is free.

- **Search Analytics**: 1,200 queries per minute per property and per user, plus short-term
  (10-minute) and long-term (daily) **load** quotas. Grouping or filtering by `page` or `query`,
  and long date ranges, cost the most. When a load quota is exceeded, wait about 15 minutes.
- **URL Inspection**: 2,000 inspections per day and 600 per minute, per property.
- **Everything else** (sites, sitemaps): 20 per second and 200 per minute per user.

Search Analytics data lags 2-3 days and is kept for 16 months. Hourly data (`hour` dimension,
`data_state: hourly_all`) covers about the last 10 days.

## Tools

| Tool                         | What it does                                                               | Writes |
| ---------------------------- | -------------------------------------------------------------------------- | ------ |
| `gsc_auth_status`            | Configured? Signed in? Which account, how many properties, setup steps     | no     |
| `gsc_auth_login`             | Google consent in the browser, then stores the refresh token               | no     |
| `gsc_auth_logout`            | Revokes the token at Google and deletes it locally                         | no     |
| `gsc_list_sites`             | Properties the account can see: `site_url`, kind, permission level         | no     |
| `gsc_query_search_analytics` | Clicks/impressions/CTR/position by date, hour, query, page, country, ...   | no     |
| `gsc_compare_periods`        | Two periods joined by one dimension: gainers, losers, new, lost            | no     |
| `gsc_inspect_url`            | Index status, canonicals, crawl and rich results for one URL               | no     |
| `gsc_inspect_urls`           | The same for up to 20 URLs, with `quota_used`                              | no     |
| `gsc_list_sitemaps`          | Submitted sitemaps (or the children of a sitemap index)                    | no     |
| `gsc_get_sitemap`            | One sitemap's processing status, warnings and errors                       | no     |
| `gsc_request`                | Any `/webmasters/v3/` or `/v1/urlInspection/` endpoint (GET unless writes) | gated  |
| `gsc_submit_sitemap`         | Submit or resubmit a sitemap (idempotent)                                  | yes    |
| `gsc_delete_sitemap`         | Remove a submitted sitemap, requires `confirm: true`                       | yes    |

The read tools are registered as soon as `GSC_CLIENT_ID` and `GSC_CLIENT_SECRET` are set, before
login, so `gsc_auth_login` can complete without a restart.

### Things worth knowing

- `http://`, `https://`, `www` and the trailing slash each make a different URL-prefix property
  with separate data. A domain property (`sc-domain:`) covers all of them.
- A URL with a scheme is never widened to a domain property: `https://shop.example.com/` with
  only `sc-domain:example.com` available fails and names the domain property, because reading the
  whole domain would change what the numbers mean. A bare `shop.example.com` does resolve to it,
  with a note.
- `returned_totals` are the sum of the returned rows, not the property's totals: query-grouped rows omit
  anonymized queries, and rows are capped by `row_limit`.
- `discover` and `googleNews` have no `query` dimension and no position.
- The sitemap `indexed` count is deprecated by Google and always 0, so it is not returned. Use
  `gsc_inspect_url` for a page's index status.
- URL Inspection reports Google's indexed view, not a live test.
- A search analytics 429 is not retried: it is almost always the load quota, which clears in
  about 15 minutes. Other endpoints retry a 429 up to `GSC_MAX_RETRIES` times.
- `gsc_request` refuses PUT and DELETE on `/webmasters/v3/sites` and `/webmasters/v3/sites/{site}`
  (adding or removing a property), even with writes on. Sitemap paths below a property work.

## Quick start

```bash
pnpm install
pnpm build
```

Then copy `.mcp.json.example` to `.mcp.json` and fill it in.

### Inspect the tools

```bash
printf '%s\n' \
  '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"cli","version":"0"}}}' \
  '{"jsonrpc":"2.0","method":"notifications/initialized"}' \
  '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' \
| node dist/cli.js 2>/dev/null | jq -r '.result.tools[]?.name'
```

## Verify live

Everything above is tested against mocked responses only. Nothing has been called against the
real API yet. Check these on the first live run:

- Login: that the `id_token` carries `email`, that the granted scope echo is
  `.../auth/userinfo.email`, and whether a refresh response also carries an `id_token` (the
  `GSC_REFRESH_TOKEN` path depends on it).
- `searchconsole.googleapis.com/webmasters/v3/...` serves the same resources as the
  documented `www.googleapis.com/webmasters/v3/...`.
- sites.list returns `{siteEntry: [{siteUrl, permissionLevel}]}`, and the exact `siteUrl`
  strings (trailing slash, host case).
- sitemaps.list returns `{sitemap: [...]}`, with `warnings`, `errors` and `submitted` as
  int64 strings; whether `indexed` is still sent.
- The error envelope and `reason` for: a property the account cannot read (assumed 403
  `forbidden`), the Search Analytics load quota (assumed 429, which is no longer retried; if it arrives as a 403 `rateLimitExceeded` it still is), the URL Inspection daily quota,
  and an inspection URL outside the property.
- Whether a 429 carries `Retry-After`.
- `hour` dimension: the request shape (`dimensions: ["hour"]`, `dataState: "hourly_all"`),
  the row key format, `metadata.first_incomplete_hour`, and how far back it really goes.
- `brandedClassification` and `webMultimodal`, which are new (2026) and only documented.
- A URL Inspection result with rich results and with a Google-chosen canonical, against the
  shaping, and which errors actually count against the 2,000/day (`quota_used` is an estimate:
  it counts every call Google answered other than 429, 401 and 403).
- Whether sites.list returns an internationalised domain as punycode (`xn--…`, assumed) or
  unicode.

## Develop

```bash
pnpm dev            # tsdown --watch
pnpm test           # vitest
pnpm typecheck
pnpm lint
pnpm format
```

### Publish

```bash
pnpm dlx release-it       # bump, commit, tag
git push --follow-tags    # CI publishes to npm + GHCR from the tag
```

## License

MIT

TDQS

A4.4/5.0

Scored across 11 tools

Disambiguation5/5

Each tool targets a clearly distinct resource and action: auth status/login/logout, site listing, analytics querying, period comparison, single/batch URL inspection, and sitemap listing/retrieval. The only near-overlaps (gsc_inspect_url vs gsc_inspect_urls, gsc_query_search_analytics vs gsc_compare_periods) are explicitly disambiguated by their descriptions, and gsc_request clearly labels itself as a fallback to be avoided when dedicated tools exist.

Naming Consistency5/5

All tools use a consistent gsc_ prefix followed by snake_case verb_noun names, e.g. gsc_list_sites, gsc_list_sitemaps, gsc_get_sitemap, gsc_inspect_url. The batch variant gsc_inspect_urls and the auth_* group follow the same predictable convention throughout.

Tool Count5/5

11 tools is well within the typical 3-15 range and each tool maps to a distinct Search Console operation. The auth trio, analytics pair, inspection pair, and sitemaps pair are all justified and no tool feels redundant.

Completeness4/5

The read-only surface covers authentication, property discovery, search analytics, period comparison, URL inspection, and sitemaps, and gsc_request fills any remaining endpoint gaps. Write operations such as submitting/deleting sitemaps or managing properties are absent, though the server explicitly disables writes by default, making this a minor gap for the intended scope.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues