search-console-mcp 1.9.1 → 1.9.3

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/README.md CHANGED
@@ -1,297 +1,176 @@
1
1
  # Google Search Console MCP Server
2
2
 
3
- A Model Context Protocol (MCP) server that provides AI agents with access to Google Search Console data.
3
+ A Model Context Protocol (MCP) server that transforms how you interact with Google Search Console. Stop exporting CSVs and start asking questions.
4
4
 
5
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
-
7
- [![Tests](https://github.com/saurabhsharma2u/search-console-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/saurabhsharma2u/search-console-mcp/actions/workflows/ci.yml)
8
-
9
- ## Quick Start
5
+ [📚 View Documentation](https://searchconsolemcp.mintlify.app/)
10
6
 
11
- For users with an MCP-compatible client (like Claude Desktop):
7
+ ---
12
8
 
13
- ```bash
14
- npx search-console-mcp
15
- ```
9
+ ### [🏠 Overview](#) | [🎯 Prompts](#-magic-prompts) | [🚀 Quick Start](#-quick-start) | [🛠️ Tools](#-tools-reference)
16
10
 
17
11
  ---
18
12
 
19
- ## Table of Contents
20
-
21
- - [Features](#features)
22
- - [Installation](#installation)
23
- - [Google Cloud Setup](#google-cloud-setup)
24
- - [MCP Client Configuration](#mcp-client-configuration)
25
- - [Local Development](#local-development)
26
- - [Tools Reference](#tools-reference)
27
- - [Resources](#resources)
28
- - [Prompts](#prompts)
13
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
14
+ [![Tests](https://github.com/saurabhsharma2u/search-console-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/saurabhsharma2u/search-console-mcp/actions/workflows/ci.yml)
29
15
 
30
- ---
16
+ ## Why use this?
31
17
 
32
- ## Features
18
+ ### ❌ The Old Way
19
+ 1. Open Search Console -> Performance Tab
20
+ 2. Filter by "Last 28 days"
21
+ 3. Export to CSV
22
+ 4. Open in Excel/Sheets
23
+ 5. Create a filter for "Position > 10" AND "Impressions > 1000"
24
+ 6. Analyze manually to find opportunities
33
25
 
34
- - **Sites Management**: List, add, and delete sites
35
- - **Sitemaps**: List, submit, get, and delete sitemaps
36
- - **Search Analytics**: Query performance data with advanced filtering and pagination
37
- - **Period Comparison**: Compare metrics between two date ranges
38
- - **Top Queries/Pages**: Get top performing queries and pages
39
- - **URL Inspection**: Check indexing status of specific URLs
40
- - **AI Documentation**: Built-in docs for AI agents to understand GSC concepts
26
+ ### The New Way
27
+ **Just ask:**
28
+ > "Find low-hanging fruit keywords (positions 11-20) with high impressions that I should optimize."
41
29
 
42
30
  ---
43
31
 
44
- ## Installation
32
+ ## 🎯 Magic Prompts
45
33
 
46
- ### Option 1: Use with npx (Recommended)
34
+ Copy and paste these into your MCP client (Claude Desktop, etc.) to see the intelligence engine in action:
47
35
 
48
- No installation needed. Configure your MCP client to run:
36
+ #### �️ The Traffic Detective
37
+ > "My traffic dropped this week compared to last. Use the anomaly detection and time-series tools to find exactly when the drop started and which pages are responsible."
49
38
 
50
- ```bash
51
- npx search-console-mcp
52
- ```
39
+ #### 🎯 The "Striking Distance" Hunter
40
+ > "Find keywords for https://example.com where I'm ranking in positions 8-15 but have at least 1,000 impressions. These are my best opportunities for a quick traffic boost."
53
41
 
54
- ### Option 2: Global Install
42
+ #### ⚔️ The Cannibalization Cleaner
43
+ > "Check for keyword cannibalization. Are there any queries where two or more of my pages are competing and splitting the traffic? Suggest which one should be the primary authority."
55
44
 
56
- ```bash
57
- npm install -g search-console-mcp
58
- search-console-mcp
59
- ```
45
+ #### 📈 The SEO Opportunity Scoreboard
46
+ > "Analyze my top 50 keywords for the last 90 days. Rank them by a custom 'Opportunity Score' (Impressions / Position). Give me the top 5 specific pages to focus on."
60
47
 
61
- ### Option 3: Clone for Development
48
+ #### 📊 The Executive Health Check
49
+ > "Run a full SEO health check for my site. Segment the results by Brand vs. Non-Brand and give me 3 high-impact actions for the upcoming week."
62
50
 
63
- ```bash
64
- git clone https://github.com/saurabhsharma2u/search-console-mcp.git
65
- cd search-console-mcp
66
- npm install
67
- npm run build
68
- node dist/index.js
69
- ```
51
+ #### ⚡ The Speed vs. Ranking Correlator
52
+ > "Fetch the top 5 pages by impressions. For these pages, run a PageSpeed audit. Is there any correlation between low performance scores and recently declining positions?"
70
53
 
71
54
  ---
72
55
 
73
- ## Google Cloud Setup
56
+ ## 🔒 Security & Privacy
74
57
 
75
- ### Step 1: Create a Google Cloud Project
58
+ We take your data security seriously. This tool is designed to be **local-first** and **secure by default**.
76
59
 
77
- 1. Go to [Google Cloud Console](https://console.cloud.google.com/)
78
- 2. Create a new project or select an existing one
79
- 3. Enable the **Google Search Console API**:
80
- - Go to **APIs & Services** > **Library**
81
- - Search for "Google Search Console API"
82
- - Click **Enable**
60
+ * **Credentials Never Logged**: Your Google Service Account keys are used *only* in memory to authenticate with Google APIs. They are never written to disk, logs, or sent to any third-party server.
61
+ * **Local Execution**: The code runs entirely on your local machine (or wherever you host your MCP server).
62
+ * **Path Traversal Protection**: The setup wizard implements strict validation for file paths, including null-byte removal, extension enforcement (.json), and size limits (1MB) to prevent unauthorized file access.
63
+ * **Direct Communication**: All API calls go directly from your machine to Google's servers (`googleapis.com`). There is no middleman or proxy server.
64
+ * **Open Source**: The code is fully open source. You can audit exactly how your credentials are used in `src/google-client.ts`.
83
65
 
84
- ### Step 2: Create a Service Account
85
-
86
- 1. Go to **APIs & Services** > **Credentials**
87
- 2. Click **Create Credentials** > **Service Account**
88
- 3. Fill in the details and click **Create**
89
- 4. Skip the optional steps and click **Done**
90
- 5. Click on the service account email to open it
91
- 6. Go to the **Keys** tab > **Add Key** > **Create new key**
92
- 7. Select **JSON** and download the key file
93
-
94
- ### Step 3: Grant Access in Search Console
66
+ ---
95
67
 
96
- 1. Go to [Google Search Console](https://search.google.com/search-console/)
97
- 2. Select your property
98
- 3. Go to **Settings** > **Users and permissions**
99
- 4. Click **Add user**
100
- 5. Enter the service account email (e.g., `my-service@project.iam.gserviceaccount.com`)
101
- 6. Set permission to **Full** (for write operations) or **Restricted** (read-only)
68
+ ## Features
102
69
 
103
- ### Step 4: Configure Credentials
70
+ - **Advanced Analytics**: Query performance data with powerful filters (Regex supported).
71
+ - *New*: Support for 'News', 'Discover', 'Image' search types.
72
+ - *New*: 'Fresh' data support for real-time monitoring.
73
+ - *New*: **Drop Attribution** to identify device-level traffic losses.
74
+ - *New*: **Time Series Insights** with rolling averages and trend forecasting.
75
+ - **Trend Detection**: Automatically identify rising or falling trends in your traffic.
76
+ - **Anomaly Detection**: Spot unusual spikes or drops that need attention.
77
+ - **Sitemaps Management**: List, submit, and validte sitemaps.
78
+ - **URL Inspection**: Check real-time indexing status and mobile usability.
79
+ - **PageSpeed Insights**: Integrated performance and Core Web Vitals analysis.
80
+ - **Schema Validation**: Validate JSON-LD structured data.
104
81
 
105
- **Option A: File-based (Local Development)**
82
+ ---
106
83
 
107
- ```bash
108
- export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/service-account-key.json"
109
- ```
84
+ ## Quick Start
110
85
 
111
- **Option B: Environment Variables (Serverless/Cloudflare)**
86
+ ### 1. Run the Setup Wizard
87
+ First, use the interactive wizard to validate your credentials and get your configuration:
112
88
 
113
89
  ```bash
114
- export GOOGLE_CLIENT_EMAIL="your-service-account@project.iam.gserviceaccount.com"
115
- export GOOGLE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"
90
+ npx -y search-console-mcp setup
116
91
  ```
117
92
 
118
- ---
93
+ The wizard will guide you through:
94
+ - Creating a Google Service Account.
95
+ - Adding the account to Search Console.
96
+ - Validating your JSON key file.
97
+ - Generating the configuration for your MCP client.
119
98
 
120
- ## MCP Client Configuration
99
+ ### 2. Connect to an MCP Client
121
100
 
122
- ### Claude Desktop
101
+ **Note:** The server uses `stdio` to communicate. Do not run `npx search-console-mcp` directly in your terminal; it is meant to be run by an MCP client like Claude Desktop or Cursor.
123
102
 
124
- Add to your `claude_desktop_config.json`:
103
+ #### Claude Desktop Configuration
104
+ Add this to your `claude_desktop_config.json`:
125
105
 
126
106
  ```json
127
107
  {
128
108
  "mcpServers": {
129
109
  "google-search-console": {
130
110
  "command": "npx",
131
- "args": ["search-console-mcp"],
111
+ "args": ["-y", "search-console-mcp"],
132
112
  "env": {
133
- "GOOGLE_APPLICATION_CREDENTIALS": "/path/to/your/service-account-key.json"
113
+ "GOOGLE_APPLICATION_CREDENTIALS": "/absolute/path/to/your/service-account-key.json"
134
114
  }
135
115
  }
136
116
  }
137
117
  }
138
118
  ```
139
119
 
140
- ### Generic MCP Client
141
-
142
- ```json
143
- {
144
- "name": "google-search-console",
145
- "command": "npx",
146
- "args": ["search-console-mcp"],
147
- "env": {
148
- "GOOGLE_APPLICATION_CREDENTIALS": "/path/to/your/service-account-key.json"
149
- }
150
- }
151
- ```
152
-
153
- ---
154
-
155
- ## Local Development
156
-
157
- ### Setup
158
-
159
- ```bash
160
- # Clone the repository
161
- git clone https://github.com/saurabhsharma2u/search-console-mcp.git
162
- cd search-console-mcp
163
-
164
- # Install dependencies
165
- npm install
166
-
167
- # Create .env file
168
- cp .env.example .env
169
- # Edit .env with your credentials
170
-
171
- # Build
172
- npm run build
173
-
174
- # Run tests
175
- npm test
176
-
177
- # Run the server
178
- node dist/index.js
179
- ```
180
-
181
- ### Project Structure
182
-
183
- ```
184
- src/
185
- ├── index.ts # MCP server entry point
186
- ├── google-client.ts # Google API authentication
187
- ├── errors.ts # Error handling utilities
188
- ├── docs/ # Embedded documentation for AI
189
- │ ├── dimensions.ts
190
- │ ├── filters.ts
191
- │ ├── search-types.ts
192
- │ └── patterns.ts
193
- └── tools/ # Tool implementations
194
- ├── sites.ts
195
- ├── sitemaps.ts
196
- ├── analytics.ts
197
- └── inspection.ts
198
- ```
199
-
200
120
  ---
201
121
 
202
122
  ## Tools Reference
203
123
 
204
- ### Sites
205
-
206
- | Tool | Description | Arguments |
207
- |------|-------------|-----------|
208
- | `sites_list` | List all sites | none |
209
- | `sites_add` | Add a site | `siteUrl` |
210
- | `sites_delete` | Delete a site | `siteUrl` |
211
- | `sites_get` | Get site details | `siteUrl` |
212
-
213
- ### Sitemaps
214
-
215
- | Tool | Description | Arguments |
216
- |------|-------------|-----------|
217
- | `sitemaps_list` | List sitemaps | `siteUrl` |
218
- | `sitemaps_get` | Get sitemap details | `siteUrl`, `feedpath` |
219
- | `sitemaps_submit` | Submit sitemap | `siteUrl`, `feedpath` |
220
- | `sitemaps_delete` | Delete sitemap | `siteUrl`, `feedpath` |
221
-
222
124
  ### Analytics
223
-
224
- | Tool | Description | Arguments |
225
- |------|-------------|-----------|
226
- | `analytics_query` | Query search analytics with filters | `siteUrl`, `startDate`, `endDate`, `dimensions?`, `type?`, `limit?`, `startRow?`, `filters?` |
227
- | `analytics_performance_summary` | Get aggregate metrics for N days | `siteUrl`, `days?` |
228
- | `analytics_compare_periods` | Compare two date ranges | `siteUrl`, `period1Start`, `period1End`, `period2Start`, `period2End` |
229
- | `analytics_top_queries` | Get top queries | `siteUrl`, `days?`, `limit?`, `sortBy?` |
230
- | `analytics_top_pages` | Get top pages | `siteUrl`, `days?`, `limit?`, `sortBy?` |
231
-
232
- ### Inspection
233
-
234
- | Tool | Description | Arguments |
235
- |------|-------------|-----------|
236
- | `inspection_inspect` | Inspect URL index status | `siteUrl`, `inspectionUrl`, `languageCode?` |
237
-
238
- ### PageSpeed Insights
239
-
240
- | Tool | Description | Arguments |
241
- |------|-------------|-----------|
242
- | `pagespeed_analyze` | PageSpeed Insights scores (performance, accessibility, SEO) | `url`, `strategy?` (mobile/desktop) |
243
- | `pagespeed_core_web_vitals` | Core Web Vitals for mobile & desktop (LCP, FID, CLS, etc.) | `url` |
244
-
245
- ### SEO Insights
246
-
247
- | Tool | Description | Arguments |
248
- |------|-------------|-----------|
249
- | `seo_recommendations` | Generate actionable SEO recommendations | `siteUrl`, `days?` |
250
- | `seo_low_hanging_fruit` | Find keywords at positions 5-20 with high impressions | `siteUrl`, `days?`, `minImpressions?`, `limit?` |
251
- | `seo_cannibalization` | Detect pages competing for the same keywords | `siteUrl`, `days?`, `minImpressions?`, `limit?` |
252
- | `seo_quick_wins` | Find pages close to page 1 (positions 11-20) | `siteUrl`, `days?`, `minImpressions?`, `limit?` |
253
-
254
- ---
255
-
256
- ## Resources
257
-
258
- AI agents can read these built-in documentation and data resources:
259
-
260
- | URI | Description |
261
- |-----|-------------|
262
- | `sites://list` | List of all sites (JSON) |
263
- | `sitemaps://list/{siteUrl}` | Sitemaps for a specific site (JSON) |
264
- | `analytics://summary/{siteUrl}` | Performance summary for a site (JSON) |
265
- | `docs://dimensions` | Available dimensions reference |
266
- | `docs://filters` | Filter operators and examples |
267
- | `docs://search-types` | Search types (web, image, video, etc.) |
268
- | `docs://patterns` | Common usage patterns and recipes |
269
-
270
- ---
271
-
272
- ## Prompts
273
-
274
- Pre-configured analysis workflows for AI agents:
275
-
276
- | Prompt | Description | Arguments |
277
- |--------|-------------|-----------|
278
- | `analyze-site-performance` | Analyze site's 28-day performance | `siteUrl` |
279
- | `compare-performance` | Compare this week vs last week | `siteUrl` |
280
- | `find-declining-pages` | Find pages losing traffic | `siteUrl` |
281
- | `keyword-opportunities` | Find low-CTR high-impression queries | `siteUrl` |
282
- | `new-content-impact` | Analyze new content performance | `siteUrl`, `pageUrl` |
283
- | `mobile-vs-desktop` | Compare device performance | `siteUrl` |
125
+ | Tool | Description |
126
+ |------|-------------|
127
+ | `analytics_query` | Master tool for raw data. Supports `dimensions`, `filters`, `aggregationType` (byPage/byProperty), `dataState` (final/all), and `type` (web/image/news/discover). |
128
+ | `analytics_trends` | Detect trends (rising/falling) for specific queries or pages. |
129
+ | `analytics_anomalies` | Detect statistical anomalies in daily traffic. |
130
+ | `analytics_drop_attribution` | **[NEW]** Attribute traffic drops to mobile/desktop or correlate with known Google Algorithm Updates. |
131
+ | `analytics_time_series` | **[NEW]** Advanced time series with rolling averages, seasonality detection, and forecasting. |
132
+ | `analytics_compare_periods` | Compare two date ranges (e.g., WoW, MoM). |
133
+ | `seo_brand_vs_nonbrand` | **[NEW]** Analyze performance split between Brand vs Non-Brand traffic. |
134
+
135
+ ### SEO Opportunities (Opinionated)
136
+ | Tool | Description |
137
+ |------|-------------|
138
+ | `seo_low_hanging_fruit` | Find keywords ranking in pos 5-20 with high impressions. |
139
+ | `seo_striking_distance` | **[NEW]** Find keywords ranking 8-15 (Quickest ROI wins). |
140
+ | `seo_low_ctr_opportunities` | **[NEW]** Find top ranking queries (pos 1-10) with poor CTR. |
141
+ | `seo_cannibalization` | **[Enhanced]** Detect pages competing for the same query with traffic conflict. |
142
+ | `seo_lost_queries` | **[NEW]** Identify queries that lost all traffic in the last 28 days. |
143
+
144
+ ### SEO Primitives (Atoms for Agents)
145
+ These are low-level tools designed to be used by other AI agents to build complex logic.
146
+ | Tool | Description |
147
+ |------|-------------|
148
+ | `seo_primitive_ranking_bucket` | Categorize a position (e.g. "Top 3", "Page 1", "Unranked"). |
149
+ | `seo_primitive_traffic_delta` | Calculate absolute and % change between two numbers. |
150
+ | `seo_primitive_is_brand` | Check if a query matches a brand regex. |
151
+ | `seo_primitive_is_cannibalized` | Check if two pages are competing for the same query. |
152
+
153
+ ### Sites & Sitemaps
154
+ | Tool | Description |
155
+ |------|-------------|
156
+ | `sites_list` | List all verified sites. |
157
+ | `sites_add` / `sites_delete` | Manage properties. |
158
+ | `sites_health_check` | **[NEW]** Run a health check on one or all sites. Checks WoW performance, sitemaps, and anomalies. |
159
+ | `sitemaps_list` / `sitemaps_submit` | Manage sitemaps. |
160
+
161
+ ### Inspection & Validation
162
+ | Tool | Description |
163
+ |------|-------------|
164
+ | `inspection_inspect` | Google URL Inspection API (Index status, mobile usability). |
165
+ | `pagespeed_analyze` | Lighthouse scores & Core Web Vitals. |
166
+ | `schema_validate` | Validate Structured Data (JSON-LD). |
284
167
 
285
168
  ---
286
169
 
287
170
  ## Contributing
288
171
 
289
- See [CONTRIBUTING.md](./CONTRIBUTING.md) for contribution guidelines.
290
-
291
- ## Roadmap
292
-
293
- See [ROADMAP.md](./ROADMAP.md) for planned features.
172
+ We love contributions! Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for details.
294
173
 
295
174
  ## License
296
175
 
297
- MIT - see [LICENSE](./LICENSE)
176
+ MIT
@@ -0,0 +1,61 @@
1
+ export const algorithmUpdatesDocs = `
2
+ # Google Algorithm Updates Reference
3
+
4
+ The \`analytics_drop_attribution\` tool correlates traffic drops with major known Google Algorithm Updates. The following updates are currently tracked (source: [Search Engine Journal](https://www.searchenginejournal.com/google-algorithm-history/)):
5
+
6
+ ## 2026
7
+
8
+ | Date | Update Name | Impact Area |
9
+ |------|-------------|-------------|
10
+ | 2026-02-05 | February 2026 Discover Core Update | Discover Feed |
11
+
12
+ ## 2025
13
+
14
+ | Date | Update Name | Impact Area |
15
+ |------|-------------|-------------|
16
+ | 2025-12-11 | December 2025 Core Update | General Ranking |
17
+ | 2025-08-26 | August 2025 Spam Update | Spam / Content Quality |
18
+ | 2025-06-30 | June 2025 Core Update | General Ranking |
19
+ | 2025-03-13 | March 2025 Core Update | General Ranking |
20
+
21
+ ## 2024
22
+
23
+ | Date | Update Name | Impact Area |
24
+ |------|-------------|-------------|
25
+ | 2024-12-19 | December 2024 Spam Update | Spam / Content Quality |
26
+ | 2024-12-12 | December 2024 Core Update | General Ranking |
27
+ | 2024-11-11 | November 2024 Core Update | General Ranking |
28
+ | 2024-08-15 | August 2024 Core Update | General Ranking / Quality |
29
+ | 2024-06-20 | June 2024 Spam Update | Content Quality / Spam |
30
+ | 2024-05-14 | AI Overviews Rollout | Search Features / SERP |
31
+ | 2024-05-06 | Site Reputation Abuse (Manual Actions) | Parasite SEO / Spam |
32
+ | 2024-03-05 | March 2024 Core Update | General Ranking / Quality |
33
+
34
+ ## 2023
35
+
36
+ | Date | Update Name | Impact Area |
37
+ |------|-------------|-------------|
38
+ | 2023-11-08 | November 2023 Reviews Update | Review Content |
39
+ | 2023-11-02 | November 2023 Core Update | General Ranking |
40
+ | 2023-10-05 | October 2023 Core Update | General Ranking |
41
+ | 2023-10-04 | October 2023 Spam Update | Spam / Multi-language |
42
+ | 2023-09-14 | September 2023 Helpful Content Update | Quality / Value |
43
+ | 2023-08-22 | August 2023 Core Update | General Ranking |
44
+ | 2023-04-12 | April 2023 Reviews Update | Review Content |
45
+ | 2023-03-15 | March 2023 Core Update | General Ranking |
46
+ | 2023-02-21 | February 2023 Product Reviews Update | Product Reviews |
47
+
48
+ ## 2022
49
+
50
+ | Date | Update Name | Impact Area |
51
+ |------|-------------|-------------|
52
+ | 2022-12-14 | December 2022 Link Spam Update | Link Spam / SpamBrain |
53
+ | 2022-12-05 | December 2022 Helpful Content Update | Quality / Value |
54
+ | 2022-10-19 | October 2022 Spam Update | Spam |
55
+ | 2022-09-20 | September 2022 Product Review Update | Product Reviews |
56
+ | 2022-09-12 | September 2022 Core Update | General Ranking |
57
+
58
+ ## How Attribution Works
59
+ When a traffic drop is detected, the system checks if it occurred within **+/- 2 days** of any of these dates. If it matches, the update is flagged as a potential primary cause of the drop.
60
+ `;
61
+ export default algorithmUpdatesDocs;
@@ -5,3 +5,4 @@ export { dimensionsDocs } from './dimensions.js';
5
5
  export { filtersDocs } from './filters.js';
6
6
  export { searchTypesDocs } from './search-types.js';
7
7
  export { patternsDocs } from './patterns.js';
8
+ export { algorithmUpdatesDocs } from './algorithm-updates.js';
@@ -26,6 +26,35 @@ Args: {
26
26
  }
27
27
  \`\`\`
28
28
 
29
+ | Tool | Description |
30
+ |------|-------------|
31
+ | \`analytics_drop_attribution\` | Identify if a traffic drop was device-specific or algorithm-linked. |
32
+ | \`analytics_time_series\` | Get rolling averages, seasonality strength, and trend forecasts. |
33
+
34
+ ---
35
+
36
+ ## Advanced Analytics Patterns
37
+
38
+ ### Attribute a Traffic Drop
39
+ Identify if a recent drop was caused by mobile/desktop devices or correlates with a Google Algorithm Update:
40
+ \`\`\`json
41
+ {
42
+ "siteUrl": "https://example.com",
43
+ "days": 30
44
+ }
45
+ \`\`\`
46
+
47
+ ### Time Series Forecasting
48
+ Get a 14-day rolling average and forecast the next 14 days of traffic:
49
+ \`\`\`json
50
+ {
51
+ "siteUrl": "https://example.com",
52
+ "days": 60,
53
+ "window": 14,
54
+ "forecastDays": 14
55
+ }
56
+ \`\`\`
57
+
29
58
  ---
30
59
 
31
60
  ## Analytics Patterns
@@ -1,11 +1,15 @@
1
1
  import { google } from 'googleapis';
2
2
  const SCOPES = ['https://www.googleapis.com/auth/webmasters'];
3
+ let cachedClient = null;
3
4
  /**
4
5
  * Get an authenticated Google Search Console API client.
5
6
  * Supports both file-based credentials (GOOGLE_APPLICATION_CREDENTIALS)
6
7
  * and environment variable credentials (GOOGLE_CLIENT_EMAIL + GOOGLE_PRIVATE_KEY).
7
8
  */
8
9
  export async function getSearchConsoleClient() {
10
+ if (cachedClient) {
11
+ return cachedClient;
12
+ }
9
13
  // Option 1: Environment variables (for serverless/Cloudflare)
10
14
  if (!process.env.GOOGLE_APPLICATION_CREDENTIALS && process.env.GOOGLE_CLIENT_EMAIL && process.env.GOOGLE_PRIVATE_KEY) {
11
15
  const jwtClient = new google.auth.JWT({
@@ -14,12 +18,14 @@ export async function getSearchConsoleClient() {
14
18
  scopes: SCOPES
15
19
  });
16
20
  await jwtClient.authorize();
17
- return google.searchconsole({ version: 'v1', auth: jwtClient });
21
+ cachedClient = google.searchconsole({ version: 'v1', auth: jwtClient });
22
+ return cachedClient;
18
23
  }
19
24
  // Option 2: File-based credentials (default)
20
25
  const auth = new google.auth.GoogleAuth({
21
26
  scopes: SCOPES,
22
27
  });
23
28
  const client = await auth.getClient();
24
- return google.searchconsole({ version: 'v1', auth: client });
29
+ cachedClient = google.searchconsole({ version: 'v1', auth: client });
30
+ return cachedClient;
25
31
  }