mcp-google-contacts 0.1.0 → 1.0.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/README.md +36 -43
- package/README.ru.md +35 -42
- package/dist/client.js +57 -6
- package/dist/index.js +8 -8
- package/dist/tools/auth.js +114 -0
- package/package.json +2 -1
- package/test/dist-smoke.test.js +37 -4
package/README.md
CHANGED
|
@@ -3,15 +3,16 @@
|
|
|
3
3
|
**English** | [Русский](./README.ru.md)
|
|
4
4
|
|
|
5
5
|
[](https://www.npmjs.com/package/mcp-google-contacts)
|
|
6
|
-
[](https://github.com/A1-x-Tech/mcp-google-contacts/actions/workflows/ci.yml)
|
|
7
6
|
[](https://glama.ai/mcp/servers/A1-x-Tech/mcp-google-contacts)
|
|
7
|
+
[](https://github.com/A1-x-Tech/mcp-google-contacts/actions/workflows/ci.yml)
|
|
8
8
|
[](./LICENSE)
|
|
9
9
|
|
|
10
10
|
**A1 Google Contacts MCP** lets an AI app manage your Google address book in plain language. Find a contact, create or update one, organize contacts with labels, run batch imports and clean-ups, and turn auto-saved "Other contacts" into real ones.
|
|
11
11
|
|
|
12
12
|
It uses the Google People API — the API behind Google Contacts — with your Google account. It guards every update against concurrent edits, keeps reads compact with explicit field masks and makes the limits of the People API explicit instead of implying that every contacts task is possible.
|
|
13
13
|
|
|
14
|
-
- **
|
|
14
|
+
- **25 tools.** List, search and read contacts, create, update and delete them one at a time or in batches, manage contact groups and membership, and reach "Other contacts".
|
|
15
|
+
- **Connects from the conversation.** Say "connect Google Contacts": the server walks you through the OAuth client, catches Google's redirect on `127.0.0.1` with PKCE and keeps the tokens itself — no config files, no restart.
|
|
15
16
|
- **Updates don't clobber.** Every update is etag-guarded: if a contact changed elsewhere since it was read, the write fails instead of silently overwriting the concurrent edit.
|
|
16
17
|
- **Deletes are real.** The People API has no trash; deleting a contact or group is permanent, and the server marks those tools destructive so your AI app can ask first.
|
|
17
18
|
- **Minimal Google scopes.** It uses `contacts` for read/write — `contacts.readonly` is enough for a read-only setup — plus `contacts.other.readonly` only for "Other contacts", without broad account access.
|
|
@@ -52,10 +53,10 @@ Start with a read-only question:
|
|
|
52
53
|
|
|
53
54
|
## Quick start
|
|
54
55
|
|
|
55
|
-
You need Node.js 20
|
|
56
|
+
You need Node.js 20+ and a Google account. Credentials are not required at install time — the server connects from the conversation.
|
|
56
57
|
|
|
57
|
-
1.
|
|
58
|
-
2.
|
|
58
|
+
1. Add the server to your AI app.
|
|
59
|
+
2. Say "connect Google Contacts": the assistant walks you through [creating the OAuth client and approving access](#getting-access) without editing config files.
|
|
59
60
|
3. Ask the read-only question above.
|
|
60
61
|
|
|
61
62
|
<details open>
|
|
@@ -63,15 +64,12 @@ You need Node.js 20+, a Google account and OAuth credentials from a Google Cloud
|
|
|
63
64
|
|
|
64
65
|
<br>
|
|
65
66
|
|
|
66
|
-
**In the app:** open **Settings →
|
|
67
|
+
**In the app:** open **Settings → MCP servers**, select **Add server**, choose **STDIO**, enter the command `npx -y mcp-google-contacts@latest` and environment variables `GOOGLE_CONTACTS_CLIENT_ID`, `GOOGLE_CONTACTS_CLIENT_SECRET`, `GOOGLE_CONTACTS_REFRESH_TOKEN`, then select **Save** and **Restart**.
|
|
67
68
|
|
|
68
69
|
**From the command line:**
|
|
69
70
|
|
|
70
71
|
```bash
|
|
71
72
|
codex mcp add google-contacts \
|
|
72
|
-
--env GOOGLE_CONTACTS_CLIENT_ID=your_client_id \
|
|
73
|
-
--env GOOGLE_CONTACTS_CLIENT_SECRET=your_client_secret \
|
|
74
|
-
--env GOOGLE_CONTACTS_REFRESH_TOKEN=your_refresh_token \
|
|
75
73
|
-- npx -y mcp-google-contacts@latest
|
|
76
74
|
```
|
|
77
75
|
|
|
@@ -90,9 +88,6 @@ codex mcp list
|
|
|
90
88
|
|
|
91
89
|
```bash
|
|
92
90
|
claude mcp add \
|
|
93
|
-
--env GOOGLE_CONTACTS_CLIENT_ID=your_client_id \
|
|
94
|
-
--env GOOGLE_CONTACTS_CLIENT_SECRET=your_client_secret \
|
|
95
|
-
--env GOOGLE_CONTACTS_REFRESH_TOKEN=your_refresh_token \
|
|
96
91
|
--transport stdio --scope user google-contacts \
|
|
97
92
|
-- npx -y mcp-google-contacts@latest
|
|
98
93
|
```
|
|
@@ -110,25 +105,22 @@ claude mcp list
|
|
|
110
105
|
|
|
111
106
|
<br>
|
|
112
107
|
|
|
113
|
-
|
|
108
|
+
The current official path is **Settings → Extensions**. For a custom desktop extension, open **Advanced settings → Extension Developer → Install Extension…**, select a `.mcpb` file and follow the prompts.
|
|
109
|
+
|
|
110
|
+
This repository currently publishes an npm stdio package and does not contain a `.mcpb` bundle. For Claude Desktop builds that still support local configuration, use the following JSON stdio configuration as a fallback:
|
|
114
111
|
|
|
115
112
|
```json
|
|
116
113
|
{
|
|
117
114
|
"mcpServers": {
|
|
118
115
|
"google-contacts": {
|
|
119
116
|
"command": "npx",
|
|
120
|
-
"args": ["-y", "mcp-google-contacts@latest"]
|
|
121
|
-
"env": {
|
|
122
|
-
"GOOGLE_CONTACTS_CLIENT_ID": "your_client_id",
|
|
123
|
-
"GOOGLE_CONTACTS_CLIENT_SECRET": "your_client_secret",
|
|
124
|
-
"GOOGLE_CONTACTS_REFRESH_TOKEN": "your_refresh_token"
|
|
125
|
-
}
|
|
117
|
+
"args": ["-y", "mcp-google-contacts@latest"]
|
|
126
118
|
}
|
|
127
119
|
}
|
|
128
120
|
}
|
|
129
121
|
```
|
|
130
122
|
|
|
131
|
-
|
|
123
|
+
In those builds, save it to `~/Library/Application Support/Claude/claude_desktop_config.json` on macOS or `%APPDATA%\Claude\claude_desktop_config.json` on Windows.
|
|
132
124
|
|
|
133
125
|
[Claude Desktop MCP documentation](https://support.claude.com/en/articles/10949351-getting-started-with-local-mcp-servers-on-claude-desktop)
|
|
134
126
|
|
|
@@ -147,12 +139,7 @@ Add this to `~/.cursor/mcp.json` on macOS/Linux or `%USERPROFILE%\.cursor\mcp.js
|
|
|
147
139
|
"google-contacts": {
|
|
148
140
|
"type": "stdio",
|
|
149
141
|
"command": "npx",
|
|
150
|
-
"args": ["-y", "mcp-google-contacts@latest"]
|
|
151
|
-
"env": {
|
|
152
|
-
"GOOGLE_CONTACTS_CLIENT_ID": "your_client_id",
|
|
153
|
-
"GOOGLE_CONTACTS_CLIENT_SECRET": "your_client_secret",
|
|
154
|
-
"GOOGLE_CONTACTS_REFRESH_TOKEN": "your_refresh_token"
|
|
155
|
-
}
|
|
142
|
+
"args": ["-y", "mcp-google-contacts@latest"]
|
|
156
143
|
}
|
|
157
144
|
}
|
|
158
145
|
}
|
|
@@ -175,19 +162,9 @@ Run **MCP: Open User Configuration** and add:
|
|
|
175
162
|
"google-contacts": {
|
|
176
163
|
"type": "stdio",
|
|
177
164
|
"command": "npx",
|
|
178
|
-
"args": ["-y", "mcp-google-contacts@latest"]
|
|
179
|
-
"env": {
|
|
180
|
-
"GOOGLE_CONTACTS_CLIENT_ID": "${input:contacts_client_id}",
|
|
181
|
-
"GOOGLE_CONTACTS_CLIENT_SECRET": "${input:contacts_client_secret}",
|
|
182
|
-
"GOOGLE_CONTACTS_REFRESH_TOKEN": "${input:contacts_refresh_token}"
|
|
183
|
-
}
|
|
165
|
+
"args": ["-y", "mcp-google-contacts@latest"]
|
|
184
166
|
}
|
|
185
|
-
}
|
|
186
|
-
"inputs": [
|
|
187
|
-
{ "type": "promptString", "id": "contacts_client_id", "description": "Google OAuth client ID" },
|
|
188
|
-
{ "type": "promptString", "id": "contacts_client_secret", "description": "Google OAuth client secret", "password": true },
|
|
189
|
-
{ "type": "promptString", "id": "contacts_refresh_token", "description": "Google OAuth refresh token", "password": true }
|
|
190
|
-
]
|
|
167
|
+
}
|
|
191
168
|
}
|
|
192
169
|
```
|
|
193
170
|
|
|
@@ -247,7 +224,20 @@ The AI client controls confirmation prompts. The server marks reads, writes and
|
|
|
247
224
|
|
|
248
225
|
## Getting access
|
|
249
226
|
|
|
250
|
-
Google Contacts requires OAuth 2.0; an API key is not enough.
|
|
227
|
+
Google Contacts requires OAuth 2.0; an API key is not enough. There are two ways in, and the first one needs no configuration files.
|
|
228
|
+
|
|
229
|
+
### Connect from the chat (recommended)
|
|
230
|
+
|
|
231
|
+
Say "connect Google Contacts" and the assistant runs the flow with you:
|
|
232
|
+
|
|
233
|
+
1. `setup_instructions` prints the checklist: create or select a Google Cloud project, enable **Google People API**, configure the consent screen and create a **Desktop app** OAuth client.
|
|
234
|
+
2. Download that client's JSON ("Download JSON") and give the assistant its **path** — `set_client` stores it owner-only. The secret never goes through the conversation.
|
|
235
|
+
3. `start_login` returns a Google consent link. Open it **on this machine** and approve; the code comes back to a one-shot listener on `127.0.0.1` (PKCE), never through the chat.
|
|
236
|
+
4. `finish_login` exchanges the code and saves the tokens to `~/.config/mcp-google-contacts/credentials.json` (mode 0600) and verifies them with a real Google People API call — so an API that is still switched off is caught right there.
|
|
237
|
+
|
|
238
|
+
The tokens are re-read on every call, so the connection works immediately — no restart of the AI app. `auth_status` shows what is connected, `logout` revokes and deletes it.
|
|
239
|
+
|
|
240
|
+
### Environment variables (CI, unattended installs)
|
|
251
241
|
|
|
252
242
|
1. Create or select a Google Cloud project and enable **People API**.
|
|
253
243
|
2. Configure the OAuth consent screen and create a **Desktop app** OAuth client.
|
|
@@ -265,12 +255,15 @@ Testing-mode OAuth refresh tokens can expire after seven days. Publish the OAuth
|
|
|
265
255
|
|
|
266
256
|
## Configuration
|
|
267
257
|
|
|
258
|
+
Every variable is optional — with none of them the server connects [from the chat](#connect-from-the-chat-recommended).
|
|
259
|
+
|
|
268
260
|
| Variable | Required | Description |
|
|
269
261
|
|---|---|---|
|
|
270
|
-
| `GOOGLE_CONTACTS_CLIENT_ID` |
|
|
271
|
-
| `GOOGLE_CONTACTS_CLIENT_SECRET` |
|
|
272
|
-
| `GOOGLE_CONTACTS_REFRESH_TOKEN` |
|
|
273
|
-
| `GOOGLE_CONTACTS_ACCESS_TOKEN` |
|
|
262
|
+
| `GOOGLE_CONTACTS_CLIENT_ID` | No* | OAuth client ID. |
|
|
263
|
+
| `GOOGLE_CONTACTS_CLIENT_SECRET` | No* | OAuth client secret. |
|
|
264
|
+
| `GOOGLE_CONTACTS_REFRESH_TOKEN` | No* | OAuth refresh token. |
|
|
265
|
+
| `GOOGLE_CONTACTS_ACCESS_TOKEN` | No* | Short-lived alternative to the OAuth trio (~1 h). |
|
|
266
|
+
| `GOOGLE_CONTACTS_OAUTH_PORT` | No | Fixed loopback port for the in-chat login; useful over SSH port forwarding. |
|
|
274
267
|
| `GOOGLE_CONTACTS_API_BASE` | No | Google People API base URL override. |
|
|
275
268
|
| `GOOGLE_CONTACTS_TIMEOUT_MS` | No | Per-request timeout; default `60000` ms. |
|
|
276
269
|
| `GOOGLE_CONTACTS_MAX_RETRIES` | No | Temporary-error retries; default `3`. |
|
package/README.ru.md
CHANGED
|
@@ -11,7 +11,8 @@
|
|
|
11
11
|
|
|
12
12
|
Сервер работает с Google People API — API, на котором построены Google Контакты, — через ваш Google-аккаунт. Он защищает каждое обновление от параллельных правок, делает чтение компактным за счёт явных масок полей и явно показывает ограничения People API, а не создаёт впечатление, что с контактами можно сделать всё.
|
|
13
13
|
|
|
14
|
-
- **
|
|
14
|
+
- **25 инструментов.** Список, поиск и чтение контактов, создание, обновление и удаление по одному или пакетами, управление группами контактов и их составом, доступ к «Другим контактам».
|
|
15
|
+
- **Подключение из диалога.** Скажите «подключи Google Контакты»: сервер проведёт через создание OAuth-клиента, поймает редирект Google на `127.0.0.1` с PKCE и сам сохранит токены — без конфигов и перезапуска.
|
|
15
16
|
- **Обновления не затирают чужие правки.** Каждое обновление защищено etag: если контакт изменился где-то ещё после чтения, запись завершится ошибкой, а не молча перезапишет параллельную правку.
|
|
16
17
|
- **Удаление — настоящее.** В People API нет корзины; удаление контакта или группы необратимо, и сервер помечает эти инструменты как разрушительные, чтобы AI-приложение спросило заранее.
|
|
17
18
|
- **Минимальные scope Google.** Используется `contacts` для чтения и записи — для read-only-установки достаточно `contacts.readonly` — плюс `contacts.other.readonly` только для «Других контактов», без широкого доступа к аккаунту.
|
|
@@ -52,10 +53,10 @@
|
|
|
52
53
|
|
|
53
54
|
## Быстрый старт
|
|
54
55
|
|
|
55
|
-
Нужны Node.js 20
|
|
56
|
+
Нужны Node.js 20+ и Google-аккаунт. Учётные данные при установке не нужны: сервер подключается прямо в диалоге.
|
|
56
57
|
|
|
57
|
-
1.
|
|
58
|
-
2.
|
|
58
|
+
1. Добавьте сервер в AI-приложение.
|
|
59
|
+
2. Скажите «подключи Google Контакты» — ассистент проведёт [создание OAuth-клиента и выдачу доступа](#как-получить-доступ), не трогая конфиги.
|
|
59
60
|
3. Отправьте запрос, который только читает данные.
|
|
60
61
|
|
|
61
62
|
<details open>
|
|
@@ -63,15 +64,12 @@
|
|
|
63
64
|
|
|
64
65
|
<br>
|
|
65
66
|
|
|
66
|
-
**В приложении:** откройте **Settings →
|
|
67
|
+
**В приложении:** откройте **Settings → MCP servers**, нажмите **Add server**, выберите **STDIO**, укажите команду `npx -y mcp-google-contacts@latest` и переменные окружения `GOOGLE_CONTACTS_CLIENT_ID`, `GOOGLE_CONTACTS_CLIENT_SECRET`, `GOOGLE_CONTACTS_REFRESH_TOKEN`, затем нажмите **Save**, потом **Restart**.
|
|
67
68
|
|
|
68
69
|
**В командной строке:**
|
|
69
70
|
|
|
70
71
|
```bash
|
|
71
72
|
codex mcp add google-contacts \
|
|
72
|
-
--env GOOGLE_CONTACTS_CLIENT_ID=your_client_id \
|
|
73
|
-
--env GOOGLE_CONTACTS_CLIENT_SECRET=your_client_secret \
|
|
74
|
-
--env GOOGLE_CONTACTS_REFRESH_TOKEN=your_refresh_token \
|
|
75
73
|
-- npx -y mcp-google-contacts@latest
|
|
76
74
|
```
|
|
77
75
|
|
|
@@ -90,9 +88,6 @@ codex mcp list
|
|
|
90
88
|
|
|
91
89
|
```bash
|
|
92
90
|
claude mcp add \
|
|
93
|
-
--env GOOGLE_CONTACTS_CLIENT_ID=your_client_id \
|
|
94
|
-
--env GOOGLE_CONTACTS_CLIENT_SECRET=your_client_secret \
|
|
95
|
-
--env GOOGLE_CONTACTS_REFRESH_TOKEN=your_refresh_token \
|
|
96
91
|
--transport stdio --scope user google-contacts \
|
|
97
92
|
-- npx -y mcp-google-contacts@latest
|
|
98
93
|
```
|
|
@@ -110,25 +105,22 @@ claude mcp list
|
|
|
110
105
|
|
|
111
106
|
<br>
|
|
112
107
|
|
|
113
|
-
|
|
108
|
+
Актуальный официальный путь — **Settings → Extensions**. Для пользовательского desktop extension откройте **Advanced settings → Extension Developer → Install Extension…**, выберите файл `.mcpb` и следуйте подсказкам.
|
|
109
|
+
|
|
110
|
+
Этот репозиторий сейчас публикует npm-пакет со stdio и пока не содержит `.mcpb`. Поэтому используйте приведённый ниже JSON stdio-конфиг как fallback только в сборках Claude Desktop, где ещё поддерживается локальная конфигурация:
|
|
114
111
|
|
|
115
112
|
```json
|
|
116
113
|
{
|
|
117
114
|
"mcpServers": {
|
|
118
115
|
"google-contacts": {
|
|
119
116
|
"command": "npx",
|
|
120
|
-
"args": ["-y", "mcp-google-contacts@latest"]
|
|
121
|
-
"env": {
|
|
122
|
-
"GOOGLE_CONTACTS_CLIENT_ID": "your_client_id",
|
|
123
|
-
"GOOGLE_CONTACTS_CLIENT_SECRET": "your_client_secret",
|
|
124
|
-
"GOOGLE_CONTACTS_REFRESH_TOKEN": "your_refresh_token"
|
|
125
|
-
}
|
|
117
|
+
"args": ["-y", "mcp-google-contacts@latest"]
|
|
126
118
|
}
|
|
127
119
|
}
|
|
128
120
|
}
|
|
129
121
|
```
|
|
130
122
|
|
|
131
|
-
|
|
123
|
+
В таких сборках сохраните его в `~/Library/Application Support/Claude/claude_desktop_config.json` на macOS или `%APPDATA%\Claude\claude_desktop_config.json` на Windows.
|
|
132
124
|
|
|
133
125
|
[Документация Claude Desktop MCP](https://support.claude.com/en/articles/10949351-getting-started-with-local-mcp-servers-on-claude-desktop)
|
|
134
126
|
|
|
@@ -147,12 +139,7 @@ claude mcp list
|
|
|
147
139
|
"google-contacts": {
|
|
148
140
|
"type": "stdio",
|
|
149
141
|
"command": "npx",
|
|
150
|
-
"args": ["-y", "mcp-google-contacts@latest"]
|
|
151
|
-
"env": {
|
|
152
|
-
"GOOGLE_CONTACTS_CLIENT_ID": "your_client_id",
|
|
153
|
-
"GOOGLE_CONTACTS_CLIENT_SECRET": "your_client_secret",
|
|
154
|
-
"GOOGLE_CONTACTS_REFRESH_TOKEN": "your_refresh_token"
|
|
155
|
-
}
|
|
142
|
+
"args": ["-y", "mcp-google-contacts@latest"]
|
|
156
143
|
}
|
|
157
144
|
}
|
|
158
145
|
}
|
|
@@ -175,19 +162,9 @@ claude mcp list
|
|
|
175
162
|
"google-contacts": {
|
|
176
163
|
"type": "stdio",
|
|
177
164
|
"command": "npx",
|
|
178
|
-
"args": ["-y", "mcp-google-contacts@latest"]
|
|
179
|
-
"env": {
|
|
180
|
-
"GOOGLE_CONTACTS_CLIENT_ID": "${input:contacts_client_id}",
|
|
181
|
-
"GOOGLE_CONTACTS_CLIENT_SECRET": "${input:contacts_client_secret}",
|
|
182
|
-
"GOOGLE_CONTACTS_REFRESH_TOKEN": "${input:contacts_refresh_token}"
|
|
183
|
-
}
|
|
165
|
+
"args": ["-y", "mcp-google-contacts@latest"]
|
|
184
166
|
}
|
|
185
|
-
}
|
|
186
|
-
"inputs": [
|
|
187
|
-
{ "type": "promptString", "id": "contacts_client_id", "description": "Google OAuth client ID" },
|
|
188
|
-
{ "type": "promptString", "id": "contacts_client_secret", "description": "Google OAuth client secret", "password": true },
|
|
189
|
-
{ "type": "promptString", "id": "contacts_refresh_token", "description": "Google OAuth refresh token", "password": true }
|
|
190
|
-
]
|
|
167
|
+
}
|
|
191
168
|
}
|
|
192
169
|
```
|
|
193
170
|
|
|
@@ -247,7 +224,20 @@ claude mcp list
|
|
|
247
224
|
|
|
248
225
|
## Как получить доступ
|
|
249
226
|
|
|
250
|
-
Google
|
|
227
|
+
Google Contacts требует OAuth 2.0: одного API-ключа недостаточно. Путей два, и первый не требует править конфигурационные файлы.
|
|
228
|
+
|
|
229
|
+
### Подключение из диалога (рекомендуемый путь)
|
|
230
|
+
|
|
231
|
+
Скажите «подключи Google Контакты», и ассистент пройдёт флоу вместе с вами:
|
|
232
|
+
|
|
233
|
+
1. `setup_instructions` выдаёт чек-лист: создать или выбрать проект Google Cloud, включить **Google People API**, настроить consent screen и создать OAuth-клиент типа **Desktop app**.
|
|
234
|
+
2. Скачайте JSON этого клиента («Download JSON») и передайте ассистенту **путь** к файлу — `set_client` сохранит его с правами только для владельца. Секрет через переписку не проходит.
|
|
235
|
+
3. `start_login` возвращает ссылку на согласие Google. Откройте её **на этой же машине** и подтвердите доступ: код возвращается на одноразовый слушатель `127.0.0.1` (PKCE), а не в чат.
|
|
236
|
+
4. `finish_login` меняет код на токены и кладёт их в `~/.config/mcp-google-contacts/credentials.json` (права 0600) и проверяет их реальным вызовом Google People API — так невключённый API ловится сразу.
|
|
237
|
+
|
|
238
|
+
Токены перечитываются на каждый вызов, поэтому подключение действует немедленно — перезапускать AI-приложение не нужно. `auth_status` показывает состояние, `logout` отзывает токен и удаляет его.
|
|
239
|
+
|
|
240
|
+
### Переменные окружения (CI и автоматические установки)
|
|
251
241
|
|
|
252
242
|
1. Создайте или выберите проект Google Cloud и включите **People API**.
|
|
253
243
|
2. Настройте OAuth consent screen и создайте OAuth-клиент типа **Desktop app**.
|
|
@@ -265,12 +255,15 @@ Refresh token OAuth-приложения в режиме Testing может ис
|
|
|
265
255
|
|
|
266
256
|
## Конфигурация
|
|
267
257
|
|
|
258
|
+
Все переменные необязательные — без единой из них сервер подключается [из диалога](#подключение-из-диалога-рекомендуемый-путь).
|
|
259
|
+
|
|
268
260
|
| Переменная | Обязательна | Описание |
|
|
269
261
|
|---|---|---|
|
|
270
|
-
| `GOOGLE_CONTACTS_CLIENT_ID` |
|
|
271
|
-
| `GOOGLE_CONTACTS_CLIENT_SECRET` |
|
|
272
|
-
| `GOOGLE_CONTACTS_REFRESH_TOKEN` |
|
|
273
|
-
| `GOOGLE_CONTACTS_ACCESS_TOKEN` |
|
|
262
|
+
| `GOOGLE_CONTACTS_CLIENT_ID` | Нет* | OAuth client ID. |
|
|
263
|
+
| `GOOGLE_CONTACTS_CLIENT_SECRET` | Нет* | OAuth client secret. |
|
|
264
|
+
| `GOOGLE_CONTACTS_REFRESH_TOKEN` | Нет* | OAuth refresh token. |
|
|
265
|
+
| `GOOGLE_CONTACTS_ACCESS_TOKEN` | Нет* | Короткоживущая альтернатива OAuth-тройке (~1 ч). |
|
|
266
|
+
| `GOOGLE_CONTACTS_OAUTH_PORT` | Нет | Фиксированный порт loopback-слушателя для входа из диалога; нужен при пробросе портов по SSH. |
|
|
274
267
|
| `GOOGLE_CONTACTS_API_BASE` | Нет | Переопределяет базовый URL Google People API. |
|
|
275
268
|
| `GOOGLE_CONTACTS_TIMEOUT_MS` | Нет | Тайм-аут одного запроса; по умолчанию `60000` мс. |
|
|
276
269
|
| `GOOGLE_CONTACTS_MAX_RETRIES` | Нет | Повторы временных ошибок; по умолчанию `3`. |
|
package/dist/client.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { GoogleContactsError } from "./types.js";
|
|
2
|
-
import { CredentialsError } from "./config.js";
|
|
2
|
+
import { CredentialsError, DEFAULT_BASE } from "./config.js";
|
|
3
3
|
/** Google's OAuth2 token endpoint — refresh tokens are exchanged here. */
|
|
4
4
|
const TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
5
5
|
/**
|
|
@@ -98,6 +98,7 @@ export function buildPerson(f) {
|
|
|
98
98
|
}
|
|
99
99
|
export class GoogleContactsClient {
|
|
100
100
|
config;
|
|
101
|
+
tokenProvider;
|
|
101
102
|
base;
|
|
102
103
|
timeoutMs;
|
|
103
104
|
maxRetries;
|
|
@@ -108,8 +109,16 @@ export class GoogleContactsClient {
|
|
|
108
109
|
refreshInFlight;
|
|
109
110
|
/** Search endpoints whose server-side cache was already warmed this session. */
|
|
110
111
|
warmedSearchPaths = new Set();
|
|
111
|
-
constructor(config
|
|
112
|
+
constructor(config,
|
|
113
|
+
/**
|
|
114
|
+
* Fallback token source (the in-chat login of @a1-x-tech/mcp-google-auth).
|
|
115
|
+
* Consulted only when the env-derived config carries no credentials —
|
|
116
|
+
* env wins (component invariant 3), so existing refresh-triple and
|
|
117
|
+
* access-token installs behave exactly as before.
|
|
118
|
+
*/
|
|
119
|
+
tokenProvider) {
|
|
112
120
|
this.config = config;
|
|
121
|
+
this.tokenProvider = tokenProvider;
|
|
113
122
|
this.base = config.apiBase.endsWith("/") ? config.apiBase : config.apiBase + "/";
|
|
114
123
|
this.timeoutMs = config.timeoutMs ?? 60_000;
|
|
115
124
|
this.maxRetries = config.maxRetries ?? 3;
|
|
@@ -118,6 +127,19 @@ export class GoogleContactsClient {
|
|
|
118
127
|
canRefresh() {
|
|
119
128
|
return Boolean(this.config.refreshToken && this.config.clientId && this.config.clientSecret);
|
|
120
129
|
}
|
|
130
|
+
/**
|
|
131
|
+
* Whether a 401 is worth one re-mint + replay: either the env config can mint
|
|
132
|
+
* from its refresh triple, or the provider holds a refresh token (env or
|
|
133
|
+
* stored login). A static env access token can never be re-minted, so a 401
|
|
134
|
+
* there is final — replaying it would just burn a second request.
|
|
135
|
+
*/
|
|
136
|
+
canReplayOn401() {
|
|
137
|
+
if (this.canRefresh())
|
|
138
|
+
return true;
|
|
139
|
+
if (this.config.accessToken)
|
|
140
|
+
return false;
|
|
141
|
+
return this.tokenProvider?.canRefresh() ?? false;
|
|
142
|
+
}
|
|
121
143
|
/**
|
|
122
144
|
* Returns a valid Bearer token. With the refresh triple configured, mints an
|
|
123
145
|
* access token from the refresh token and caches it until shortly before it
|
|
@@ -129,9 +151,13 @@ export class GoogleContactsClient {
|
|
|
129
151
|
*/
|
|
130
152
|
async accessToken(forceRefresh = false) {
|
|
131
153
|
if (!this.canRefresh()) {
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
154
|
+
// Env wins over the provider (component invariant 3): a static
|
|
155
|
+
// GOOGLE_CONTACTS_ACCESS_TOKEN keeps behaving exactly as before.
|
|
156
|
+
if (this.config.accessToken)
|
|
157
|
+
return this.config.accessToken;
|
|
158
|
+
if (this.tokenProvider)
|
|
159
|
+
return this.tokenProvider.getAccessToken(forceRefresh);
|
|
160
|
+
throw new CredentialsError();
|
|
135
161
|
}
|
|
136
162
|
if (!forceRefresh && this.cachedToken && Date.now() < this.cachedToken.expiresAt) {
|
|
137
163
|
return this.cachedToken.value;
|
|
@@ -276,7 +302,7 @@ export class GoogleContactsClient {
|
|
|
276
302
|
}
|
|
277
303
|
// An expired/revoked access token: re-mint once and replay. The request
|
|
278
304
|
// never executed, so this is safe for writes too.
|
|
279
|
-
if (res.status === 401 && this.
|
|
305
|
+
if (res.status === 401 && this.canReplayOn401() && !refreshedOn401) {
|
|
280
306
|
refreshedOn401 = true;
|
|
281
307
|
await this.accessToken(true);
|
|
282
308
|
continue;
|
|
@@ -559,3 +585,28 @@ function compact(obj) {
|
|
|
559
585
|
function delay(ms) {
|
|
560
586
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
561
587
|
}
|
|
588
|
+
/**
|
|
589
|
+
* One cheap Google Contacts read, used to verify a fresh in-chat login against the
|
|
590
|
+
* API the server actually talks to. Standalone (not a client method) because it
|
|
591
|
+
* runs with a token the client does not hold yet — the login is still being
|
|
592
|
+
* finished. Throws GoogleContactsError exactly like the client does, so the caller
|
|
593
|
+
* can recognize a disabled-API 403 and give the actionable advice.
|
|
594
|
+
*/
|
|
595
|
+
export async function probeApi(accessToken) {
|
|
596
|
+
const base = (process.env.GOOGLE_CONTACTS_API_BASE || DEFAULT_BASE).replace(/\/+$/, "");
|
|
597
|
+
const res = await fetch(`${base}/v1/people/me?personFields=emailAddresses`, {
|
|
598
|
+
headers: { Authorization: `Bearer ${accessToken}` },
|
|
599
|
+
signal: AbortSignal.timeout(10_000),
|
|
600
|
+
});
|
|
601
|
+
const text = await res.text();
|
|
602
|
+
if (res.ok)
|
|
603
|
+
return;
|
|
604
|
+
let data;
|
|
605
|
+
try {
|
|
606
|
+
data = JSON.parse(text);
|
|
607
|
+
}
|
|
608
|
+
catch {
|
|
609
|
+
data = text;
|
|
610
|
+
}
|
|
611
|
+
throw new GoogleContactsError(res.status, data);
|
|
612
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -10,6 +10,7 @@ import { registerGroupTools } from "./tools/groups.js";
|
|
|
10
10
|
import { registerBatchTools } from "./tools/batch.js";
|
|
11
11
|
import { registerOtherContactTools } from "./tools/other.js";
|
|
12
12
|
import { registerRawTool } from "./tools/raw.js";
|
|
13
|
+
import { authUnconfiguredPrefix, hasAuthToken, registerAuthTools } from "./tools/auth.js";
|
|
13
14
|
/**
|
|
14
15
|
* Prose handed to the calling model in the `initialize` result — the only place
|
|
15
16
|
* it learns what the tool list cannot say: which Google product this API is,
|
|
@@ -42,11 +43,6 @@ const INSTRUCTIONS = "Google People API v1 manages the signed-in account's perso
|
|
|
42
43
|
* rather than with a failed call. There is no in-chat login here: credentials
|
|
43
44
|
* come only from the environment, so the fix is an operator action + restart.
|
|
44
45
|
*/
|
|
45
|
-
const UNCONFIGURED_PREFIX = "ATTENTION: Google Contacts is not connected yet — no credentials are configured, so every " +
|
|
46
|
-
"tool call will fail. The operator must set GOOGLE_CONTACTS_CLIENT_ID + " +
|
|
47
|
-
"GOOGLE_CONTACTS_CLIENT_SECRET + GOOGLE_CONTACTS_REFRESH_TOKEN (recommended), or " +
|
|
48
|
-
"GOOGLE_CONTACTS_ACCESS_TOKEN with a short-lived access token, in the MCP client's " +
|
|
49
|
-
"server config and restart this server — the variables are read only at startup. ";
|
|
50
46
|
/** Reads the package version so the server reports its real version to MCP clients. */
|
|
51
47
|
function readVersion() {
|
|
52
48
|
try {
|
|
@@ -87,10 +83,9 @@ async function main() {
|
|
|
87
83
|
// credentials can be reported; wired to the server before tools register.
|
|
88
84
|
const telemetry = new Telemetry(readVersion());
|
|
89
85
|
const { config, problem } = loadConfigOrDegraded(telemetry);
|
|
90
|
-
const client = new GoogleContactsClient(config);
|
|
91
86
|
// Decided once, at startup: credentials come only from the environment, so
|
|
92
87
|
// "restart after setting the variables" is the accurate advice to give.
|
|
93
|
-
const connected = hasCredentials(config);
|
|
88
|
+
const connected = hasCredentials(config) || hasAuthToken();
|
|
94
89
|
const server = new McpServer({
|
|
95
90
|
name: "mcp-google-contacts",
|
|
96
91
|
version: readVersion(),
|
|
@@ -99,7 +94,7 @@ async function main() {
|
|
|
99
94
|
{
|
|
100
95
|
instructions: connected
|
|
101
96
|
? INSTRUCTIONS
|
|
102
|
-
:
|
|
97
|
+
: authUnconfiguredPrefix() + (problem ? `Configuration problem: ${problem.message} ` : "") + INSTRUCTIONS,
|
|
103
98
|
});
|
|
104
99
|
instrumentToolCalls(server, telemetry);
|
|
105
100
|
server.server.oninitialized = () => {
|
|
@@ -111,6 +106,11 @@ async function main() {
|
|
|
111
106
|
else
|
|
112
107
|
telemetry.send("unconfigured_start", { reason: problem?.reason ?? "missing_credentials" });
|
|
113
108
|
};
|
|
109
|
+
// The auth tools come first so their TokenProvider exists before the client:
|
|
110
|
+
// the client falls back to it whenever the environment carries no
|
|
111
|
+
// credentials (env always wins — component invariant 3).
|
|
112
|
+
const tokenProvider = registerAuthTools(server);
|
|
113
|
+
const client = new GoogleContactsClient(config, tokenProvider);
|
|
114
114
|
registerContactTools(server, client);
|
|
115
115
|
registerGroupTools(server, client);
|
|
116
116
|
registerBatchTools(server, client);
|
|
@@ -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 { GoogleContactsError } 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.
|
|
7
|
+
*/
|
|
8
|
+
export const LOGIN_SCOPES = [
|
|
9
|
+
"https://www.googleapis.com/auth/contacts",
|
|
10
|
+
"https://www.googleapis.com/auth/contacts.other.readonly",
|
|
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 Contacts 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 Google People 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 GoogleContactsError && error.status === 403 && isApiDisabled(error.body)) {
|
|
57
|
+
throw new OAuthError("accessNotConfigured", "Google People 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 "contacts" puts the stored
|
|
86
|
+
* login in ~/.config/mcp-google-contacts/credentials.json (the component
|
|
87
|
+
* prefixes "mcp-google-"), envPrefix keeps the provider reading the exact
|
|
88
|
+
* GOOGLE_CONTACTS_* 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: "contacts",
|
|
93
|
+
envPrefix: "GOOGLE_CONTACTS",
|
|
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,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mcp-google-contacts",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "1.0.0",
|
|
4
4
|
"description": "MCP server for Google Contacts (People API) — search, read, create, update and delete contacts, manage contact groups and run batch operations. For Claude, Cursor, Codex and other AI clients.",
|
|
5
5
|
"mcpName": "io.github.A1-x-Tech/mcp-google-contacts",
|
|
6
6
|
"type": "module",
|
|
@@ -49,6 +49,7 @@
|
|
|
49
49
|
"url": "https://github.com/A1-x-Tech/mcp-google-contacts/issues"
|
|
50
50
|
},
|
|
51
51
|
"dependencies": {
|
|
52
|
+
"@a1-x-tech/mcp-google-auth": "^0.1.0",
|
|
52
53
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
53
54
|
"zod": "^3.25.0"
|
|
54
55
|
},
|
package/test/dist-smoke.test.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
2
5
|
import test from "node:test";
|
|
3
6
|
import { fileURLToPath } from "node:url";
|
|
4
7
|
|
|
@@ -11,8 +14,15 @@ import { registerGroupTools } from "../dist/tools/groups.js";
|
|
|
11
14
|
import { registerBatchTools } from "../dist/tools/batch.js";
|
|
12
15
|
import { registerOtherContactTools } from "../dist/tools/other.js";
|
|
13
16
|
import { registerRawTool } from "../dist/tools/raw.js";
|
|
17
|
+
import { registerAuthTools } from "../dist/tools/auth.js";
|
|
14
18
|
|
|
19
|
+
/**
|
|
20
|
+
* Sorted, because every assertion compares it against a sorted tool list. The
|
|
21
|
+
* six onboarding tools come from @a1-x-tech/mcp-google-auth, so this list is
|
|
22
|
+
* also the check that the component is wired into the published binary.
|
|
23
|
+
*/
|
|
15
24
|
const ALL_TOOLS = [
|
|
25
|
+
"auth_status",
|
|
16
26
|
"batch_create_contacts",
|
|
17
27
|
"batch_delete_contacts",
|
|
18
28
|
"batch_get_contacts",
|
|
@@ -22,18 +32,36 @@ const ALL_TOOLS = [
|
|
|
22
32
|
"create_contact_group",
|
|
23
33
|
"delete_contact",
|
|
24
34
|
"delete_contact_group",
|
|
35
|
+
"finish_login",
|
|
25
36
|
"get_contact",
|
|
26
37
|
"get_contact_group",
|
|
27
38
|
"list_contact_groups",
|
|
28
39
|
"list_contacts",
|
|
29
40
|
"list_other_contacts",
|
|
41
|
+
"logout",
|
|
30
42
|
"modify_group_members",
|
|
31
43
|
"raw_request",
|
|
32
44
|
"search_contacts",
|
|
45
|
+
"set_client",
|
|
46
|
+
"setup_instructions",
|
|
47
|
+
"start_login",
|
|
33
48
|
"update_contact",
|
|
34
49
|
"update_contact_group",
|
|
35
50
|
];
|
|
36
51
|
|
|
52
|
+
/**
|
|
53
|
+
* A throwaway $XDG_CONFIG_HOME for the spawned server. The auth component
|
|
54
|
+
* re-reads $XDG_CONFIG_HOME/mcp-google-contacts/credentials.json per call, so
|
|
55
|
+
* without this a real login on the developer's machine would make the
|
|
56
|
+
* "unconfigured" case pass for the wrong reason.
|
|
57
|
+
*/
|
|
58
|
+
function isolatedConfigDir(t) {
|
|
59
|
+
const dir = mkdtempSync(join(tmpdir(), "mcp-contacts-dist-smoke-"));
|
|
60
|
+
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
|
61
|
+
return dir;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
|
|
37
65
|
test("dist client rejects foreign-origin paths before sending the Bearer token", async () => {
|
|
38
66
|
const original = globalThis.fetch;
|
|
39
67
|
let called = false;
|
|
@@ -88,6 +116,7 @@ test("dist registers the expected tools", () => {
|
|
|
88
116
|
};
|
|
89
117
|
const client = {};
|
|
90
118
|
|
|
119
|
+
registerAuthTools(server, client);
|
|
91
120
|
registerContactTools(server, client);
|
|
92
121
|
registerGroupTools(server, client);
|
|
93
122
|
registerBatchTools(server, client);
|
|
@@ -97,13 +126,14 @@ test("dist registers the expected tools", () => {
|
|
|
97
126
|
assert.deepEqual(names.sort(), ALL_TOOLS);
|
|
98
127
|
});
|
|
99
128
|
|
|
100
|
-
test("dist binary completes a real MCP handshake over stdio and lists every tool", async () => {
|
|
129
|
+
test("dist binary completes a real MCP handshake over stdio and lists every tool", async (t) => {
|
|
101
130
|
const transport = new StdioClientTransport({
|
|
102
131
|
command: process.execPath,
|
|
103
132
|
args: [fileURLToPath(new URL("../dist/index.js", import.meta.url))],
|
|
104
133
|
env: {
|
|
105
134
|
...process.env,
|
|
106
135
|
GOOGLE_CONTACTS_ACCESS_TOKEN: "test-token",
|
|
136
|
+
XDG_CONFIG_HOME: isolatedConfigDir(t),
|
|
107
137
|
ASKADS_TELEMETRY: "0", // keep the suite offline
|
|
108
138
|
},
|
|
109
139
|
stderr: "pipe",
|
|
@@ -139,13 +169,14 @@ test("dist binary completes a real MCP handshake over stdio and lists every tool
|
|
|
139
169
|
* answer a tool call with the actionable error — offline: the CredentialsError
|
|
140
170
|
* fires before any fetch, so this test never touches the network.
|
|
141
171
|
*/
|
|
142
|
-
test("dist binary starts without credentials: handshake, tool list, actionable call error", async () => {
|
|
172
|
+
test("dist binary starts without credentials: handshake, tool list, actionable call error", async (t) => {
|
|
143
173
|
const env = Object.fromEntries(
|
|
144
174
|
Object.entries(process.env).filter(
|
|
145
175
|
([key, value]) => value !== undefined && !key.startsWith("GOOGLE_CONTACTS_"),
|
|
146
176
|
),
|
|
147
177
|
);
|
|
148
178
|
env.ASKADS_TELEMETRY = "0"; // keep the suite offline
|
|
179
|
+
env.XDG_CONFIG_HOME = isolatedConfigDir(t); // ignore any real login on this machine
|
|
149
180
|
const transport = new StdioClientTransport({
|
|
150
181
|
command: process.execPath,
|
|
151
182
|
args: [fileURLToPath(new URL("../dist/index.js", import.meta.url))],
|
|
@@ -157,7 +188,8 @@ test("dist binary starts without credentials: handshake, tool list, actionable c
|
|
|
157
188
|
try {
|
|
158
189
|
// The model must read the fix before it picks a tool.
|
|
159
190
|
const instructions = client.getInstructions() ?? "";
|
|
160
|
-
assert.match(instructions, /
|
|
191
|
+
assert.match(instructions, /NOT CONNECTED/);
|
|
192
|
+
assert.match(instructions, /start_login/);
|
|
161
193
|
assert.match(instructions, /GOOGLE_CONTACTS_CLIENT_ID/);
|
|
162
194
|
assert.match(instructions, /restart/);
|
|
163
195
|
|
|
@@ -168,7 +200,8 @@ test("dist binary starts without credentials: handshake, tool list, actionable c
|
|
|
168
200
|
const result = await client.callTool({ name: "get_contact", arguments: { resource_name: "people/me" } });
|
|
169
201
|
assert.equal(result.isError, true);
|
|
170
202
|
const text = result.content.map((c) => c.text ?? "").join(" ");
|
|
171
|
-
assert.match(text, /
|
|
203
|
+
assert.match(text, /not connected/i);
|
|
204
|
+
assert.match(text, /start_login/);
|
|
172
205
|
assert.match(text, /restart the server/);
|
|
173
206
|
} finally {
|
|
174
207
|
await client.close();
|