mcp-google-contacts 0.1.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/LICENSE +21 -0
- package/README.md +306 -0
- package/README.ru.md +306 -0
- package/dist/client.js +561 -0
- package/dist/config.js +83 -0
- package/dist/index.js +126 -0
- package/dist/telemetry.js +120 -0
- package/dist/tools/batch.js +71 -0
- package/dist/tools/contacts.js +150 -0
- package/dist/tools/groups.js +123 -0
- package/dist/tools/other.js +62 -0
- package/dist/tools/raw.js +30 -0
- package/dist/tools/util.js +221 -0
- package/dist/types.js +48 -0
- package/package.json +60 -0
- package/test/dist-smoke.test.js +176 -0
package/dist/client.js
ADDED
|
@@ -0,0 +1,561 @@
|
|
|
1
|
+
import { GoogleContactsError } from "./types.js";
|
|
2
|
+
import { CredentialsError } from "./config.js";
|
|
3
|
+
/** Google's OAuth2 token endpoint — refresh tokens are exchanged here. */
|
|
4
|
+
const TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
5
|
+
/**
|
|
6
|
+
* The field mask sent when a tool does not ask for specific person fields.
|
|
7
|
+
* The People API requires an explicit mask on every read — there is no
|
|
8
|
+
* server-side default — so this compact set is what "a contact" means here;
|
|
9
|
+
* tools widen it per call via person_fields/read_mask.
|
|
10
|
+
*/
|
|
11
|
+
export const DEFAULT_PERSON_FIELDS = "names,emailAddresses,phoneNumbers,organizations,memberships";
|
|
12
|
+
/**
|
|
13
|
+
* "Other contacts" only ever carry names, emails, phones (+ photos/metadata),
|
|
14
|
+
* and their endpoints reject the wider person mask — hence a separate default.
|
|
15
|
+
*/
|
|
16
|
+
export const DEFAULT_OTHER_CONTACT_FIELDS = "names,emailAddresses,phoneNumbers";
|
|
17
|
+
/**
|
|
18
|
+
* Validates a full resource name of the given collection before it is spliced
|
|
19
|
+
* into a URL path. The error names the expected shape but never echoes the
|
|
20
|
+
* input back — a mistyped "name" may well be a real person's data.
|
|
21
|
+
*/
|
|
22
|
+
function assertResourceName(name, kind) {
|
|
23
|
+
if (!new RegExp(`^${kind}/[a-zA-Z0-9_-]+$`).test(name)) {
|
|
24
|
+
throw new Error(`Invalid ${kind} resource name — pass the full "${kind}/<id>" form exactly as the API returned it, never a bare id.`);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** Parses the normalized birthday string into the API's structured Date. */
|
|
28
|
+
function parseBirthday(value) {
|
|
29
|
+
const match = /^(?:(\d{4})-)?(\d{1,2})-(\d{1,2})$/.exec(value);
|
|
30
|
+
const month = match ? Number(match[2]) : 0;
|
|
31
|
+
const day = match ? Number(match[3]) : 0;
|
|
32
|
+
if (!match || month < 1 || month > 12 || day < 1 || day > 31) {
|
|
33
|
+
throw new Error('birthday must be "YYYY-MM-DD" or "MM-DD" (a real calendar month and day).');
|
|
34
|
+
}
|
|
35
|
+
return compact({ year: match[1] ? Number(match[1]) : undefined, month, day });
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Builds a People API Person from the normalized contact vocabulary and
|
|
39
|
+
* returns it together with the touched field groups — that list IS the
|
|
40
|
+
* computed `updatePersonFields`/`updateMask` for the mutation endpoints.
|
|
41
|
+
* Pure wire mapping. A group left `undefined` is omitted entirely (and stays
|
|
42
|
+
* out of the mask); a provided-but-empty group ([], "") becomes an empty
|
|
43
|
+
* array that, riding in the mask, tells updateContact to CLEAR the group.
|
|
44
|
+
*/
|
|
45
|
+
export function buildPerson(f) {
|
|
46
|
+
const person = {};
|
|
47
|
+
const fieldGroups = [];
|
|
48
|
+
const put = (group, value) => {
|
|
49
|
+
person[group] = value;
|
|
50
|
+
fieldGroups.push(group);
|
|
51
|
+
};
|
|
52
|
+
if ([f.givenName, f.middleName, f.familyName, f.prefix, f.suffix].some((v) => v !== undefined)) {
|
|
53
|
+
const name = compact({
|
|
54
|
+
givenName: f.givenName,
|
|
55
|
+
middleName: f.middleName,
|
|
56
|
+
familyName: f.familyName,
|
|
57
|
+
honorificPrefix: f.prefix,
|
|
58
|
+
honorificSuffix: f.suffix,
|
|
59
|
+
});
|
|
60
|
+
put("names", Object.values(name).some((v) => v !== "") ? [name] : []);
|
|
61
|
+
}
|
|
62
|
+
if (f.nickname !== undefined)
|
|
63
|
+
put("nicknames", f.nickname ? [{ value: f.nickname }] : []);
|
|
64
|
+
if (f.emails !== undefined) {
|
|
65
|
+
put("emailAddresses", f.emails.map((e) => compact({ value: e.value, type: e.type })));
|
|
66
|
+
}
|
|
67
|
+
if (f.phones !== undefined) {
|
|
68
|
+
put("phoneNumbers", f.phones.map((p) => compact({ value: p.value, type: p.type })));
|
|
69
|
+
}
|
|
70
|
+
if (f.addresses !== undefined) {
|
|
71
|
+
put("addresses", f.addresses.map((a) => compact({
|
|
72
|
+
streetAddress: a.street,
|
|
73
|
+
city: a.city,
|
|
74
|
+
region: a.region,
|
|
75
|
+
postalCode: a.postalCode,
|
|
76
|
+
country: a.country,
|
|
77
|
+
type: a.type,
|
|
78
|
+
})));
|
|
79
|
+
}
|
|
80
|
+
if (f.organization !== undefined) {
|
|
81
|
+
const org = compact({
|
|
82
|
+
name: f.organization.name,
|
|
83
|
+
title: f.organization.title,
|
|
84
|
+
department: f.organization.department,
|
|
85
|
+
});
|
|
86
|
+
put("organizations", Object.keys(org).length ? [org] : []);
|
|
87
|
+
}
|
|
88
|
+
if (f.birthday !== undefined) {
|
|
89
|
+
put("birthdays", f.birthday ? [{ date: parseBirthday(f.birthday) }] : []);
|
|
90
|
+
}
|
|
91
|
+
if (f.notes !== undefined) {
|
|
92
|
+
put("biographies", f.notes ? [{ value: f.notes, contentType: "TEXT_PLAIN" }] : []);
|
|
93
|
+
}
|
|
94
|
+
if (f.urls !== undefined) {
|
|
95
|
+
put("urls", f.urls.map((u) => compact({ value: u.value, type: u.type })));
|
|
96
|
+
}
|
|
97
|
+
return { person, fieldGroups };
|
|
98
|
+
}
|
|
99
|
+
export class GoogleContactsClient {
|
|
100
|
+
config;
|
|
101
|
+
base;
|
|
102
|
+
timeoutMs;
|
|
103
|
+
maxRetries;
|
|
104
|
+
retryBaseMs;
|
|
105
|
+
/** Cached access token from the refresh flow, with its expiry. */
|
|
106
|
+
cachedToken;
|
|
107
|
+
/** In-flight refresh, deduping concurrent token requests. */
|
|
108
|
+
refreshInFlight;
|
|
109
|
+
/** Search endpoints whose server-side cache was already warmed this session. */
|
|
110
|
+
warmedSearchPaths = new Set();
|
|
111
|
+
constructor(config) {
|
|
112
|
+
this.config = config;
|
|
113
|
+
this.base = config.apiBase.endsWith("/") ? config.apiBase : config.apiBase + "/";
|
|
114
|
+
this.timeoutMs = config.timeoutMs ?? 60_000;
|
|
115
|
+
this.maxRetries = config.maxRetries ?? 3;
|
|
116
|
+
this.retryBaseMs = config.retryBaseMs ?? 500;
|
|
117
|
+
}
|
|
118
|
+
canRefresh() {
|
|
119
|
+
return Boolean(this.config.refreshToken && this.config.clientId && this.config.clientSecret);
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Returns a valid Bearer token. With the refresh triple configured, mints an
|
|
123
|
+
* access token from the refresh token and caches it until shortly before it
|
|
124
|
+
* expires (concurrent callers share one in-flight refresh); otherwise the
|
|
125
|
+
* static GOOGLE_CONTACTS_ACCESS_TOKEN is used as-is. With neither configured,
|
|
126
|
+
* throws {@link CredentialsError} BEFORE any fetch — a missing setup must
|
|
127
|
+
* never enter the retry/backoff loop or trigger the 401 re-mint, because no
|
|
128
|
+
* amount of retrying mints credentials.
|
|
129
|
+
*/
|
|
130
|
+
async accessToken(forceRefresh = false) {
|
|
131
|
+
if (!this.canRefresh()) {
|
|
132
|
+
if (!this.config.accessToken)
|
|
133
|
+
throw new CredentialsError();
|
|
134
|
+
return this.config.accessToken;
|
|
135
|
+
}
|
|
136
|
+
if (!forceRefresh && this.cachedToken && Date.now() < this.cachedToken.expiresAt) {
|
|
137
|
+
return this.cachedToken.value;
|
|
138
|
+
}
|
|
139
|
+
if (!this.refreshInFlight) {
|
|
140
|
+
this.refreshInFlight = this.refreshAccessToken().finally(() => {
|
|
141
|
+
this.refreshInFlight = undefined;
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
return this.refreshInFlight;
|
|
145
|
+
}
|
|
146
|
+
/** Exchanges the refresh token for a fresh access token at Google's token endpoint. */
|
|
147
|
+
async refreshAccessToken() {
|
|
148
|
+
const body = new URLSearchParams({
|
|
149
|
+
client_id: this.config.clientId,
|
|
150
|
+
client_secret: this.config.clientSecret,
|
|
151
|
+
refresh_token: this.config.refreshToken,
|
|
152
|
+
grant_type: "refresh_token",
|
|
153
|
+
}).toString();
|
|
154
|
+
const { res, text } = await this.fetchWithTimeout(TOKEN_URL, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body }, "oauth2 token refresh");
|
|
155
|
+
let data;
|
|
156
|
+
try {
|
|
157
|
+
data = JSON.parse(text);
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
data = text;
|
|
161
|
+
}
|
|
162
|
+
if (!res.ok)
|
|
163
|
+
throw new GoogleContactsError(res.status, data);
|
|
164
|
+
const token = data.access_token;
|
|
165
|
+
if (typeof token !== "string" || !token) {
|
|
166
|
+
throw new Error("OAuth2 token endpoint returned no access_token.");
|
|
167
|
+
}
|
|
168
|
+
const expiresIn = Number(data.expires_in);
|
|
169
|
+
const ttl = Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : 3600;
|
|
170
|
+
// Refresh 60s ahead of the real expiry so requests never race a dying token.
|
|
171
|
+
this.cachedToken = { value: token, expiresAt: Date.now() + Math.max(ttl - 60, 30) * 1000 };
|
|
172
|
+
return token;
|
|
173
|
+
}
|
|
174
|
+
/** Verifies the OAuth credentials by minting a fresh access token (refresh flow only). */
|
|
175
|
+
async authCheck() {
|
|
176
|
+
if (!this.canRefresh()) {
|
|
177
|
+
throw new Error("authCheck needs the refresh flow (GOOGLE_CONTACTS_CLIENT_ID / _CLIENT_SECRET / _REFRESH_TOKEN); with a static GOOGLE_CONTACTS_ACCESS_TOKEN fetch a contact instead.");
|
|
178
|
+
}
|
|
179
|
+
await this.accessToken(true);
|
|
180
|
+
return { ok: true, auth: "refresh_token" };
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Backoff before a retry: honors Retry-After when present — in both RFC 9110
|
|
184
|
+
* forms, delay-seconds and HTTP-date — else exponential. Capped at 30s either
|
|
185
|
+
* way; a past or unparsable date falls back to the exponential schedule.
|
|
186
|
+
*/
|
|
187
|
+
backoffMs(attempt, res) {
|
|
188
|
+
const header = res?.headers.get("Retry-After");
|
|
189
|
+
if (header) {
|
|
190
|
+
const seconds = Number(header);
|
|
191
|
+
const waitMs = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(header) - Date.now();
|
|
192
|
+
if (Number.isFinite(waitMs) && waitMs > 0)
|
|
193
|
+
return Math.min(waitMs, 30_000);
|
|
194
|
+
}
|
|
195
|
+
return Math.min(this.retryBaseMs * 2 ** attempt, 30_000);
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* fetch with an AbortController timeout. Reads the response body inside the
|
|
199
|
+
* guarded zone so the timeout also covers a slow or drip-feeding body, not
|
|
200
|
+
* just the initial headers, and returns the text alongside the response.
|
|
201
|
+
*/
|
|
202
|
+
async fetchWithTimeout(url, init, label) {
|
|
203
|
+
const controller = new AbortController();
|
|
204
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
205
|
+
try {
|
|
206
|
+
const res = await fetch(url, { ...init, signal: controller.signal });
|
|
207
|
+
const text = await res.text();
|
|
208
|
+
return { res, text };
|
|
209
|
+
}
|
|
210
|
+
catch (err) {
|
|
211
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
212
|
+
throw new Error(`Request to "${label}" timed out after ${this.timeoutMs}ms`);
|
|
213
|
+
}
|
|
214
|
+
throw err;
|
|
215
|
+
}
|
|
216
|
+
finally {
|
|
217
|
+
clearTimeout(timer);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Low-level request to a Google People API path (e.g. "v1/people/c123").
|
|
222
|
+
* Auth is a Bearer token (refreshed transparently; a 401 forces one re-mint
|
|
223
|
+
* + retry). 429 is always retried with backoff; 5xx and network
|
|
224
|
+
* errors/timeouts are retried only for GET — the People API has real writes,
|
|
225
|
+
* and retrying a create/update/delete after an ambiguous failure would apply
|
|
226
|
+
* it twice. Any other non-2xx throws a {@link GoogleContactsError}.
|
|
227
|
+
* `opts.retries` overrides the configured retry budget for this one call
|
|
228
|
+
* (the warmup request runs with 0 so its backoff never delays the real one).
|
|
229
|
+
*/
|
|
230
|
+
async request(method, path, body, query, opts) {
|
|
231
|
+
const maxRetries = opts?.retries ?? this.maxRetries;
|
|
232
|
+
// Guard method !== "GET" keeps undici from crashing on a GET-with-body.
|
|
233
|
+
const hasBody = body !== undefined && method !== "GET";
|
|
234
|
+
// Resolve the path against the API base, then reject anything that escaped
|
|
235
|
+
// to a foreign origin (an absolute "https://evil/x" or a "\\evil/x" slipped
|
|
236
|
+
// through raw_request) so the Bearer token can never leak to another host.
|
|
237
|
+
const url = new URL(path.replace(/^\//, ""), this.base);
|
|
238
|
+
if (url.origin !== new URL(this.base).origin) {
|
|
239
|
+
throw new Error(`raw_request path must be a relative API path (resolved to foreign origin ${url.origin})`);
|
|
240
|
+
}
|
|
241
|
+
if (query) {
|
|
242
|
+
for (const [key, value] of Object.entries(query)) {
|
|
243
|
+
if (value === undefined)
|
|
244
|
+
continue;
|
|
245
|
+
if (Array.isArray(value)) {
|
|
246
|
+
for (const item of value)
|
|
247
|
+
url.searchParams.append(key, item);
|
|
248
|
+
}
|
|
249
|
+
else {
|
|
250
|
+
url.searchParams.set(key, String(value));
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
const target = url.toString();
|
|
255
|
+
// Writes must not be replayed on ambiguous failures (see the retry gate below).
|
|
256
|
+
const idempotent = method === "GET";
|
|
257
|
+
let refreshedOn401 = false;
|
|
258
|
+
for (let attempt = 0;; attempt++) {
|
|
259
|
+
const token = await this.accessToken();
|
|
260
|
+
const headers = { Authorization: `Bearer ${token}` };
|
|
261
|
+
if (hasBody)
|
|
262
|
+
headers["Content-Type"] = "application/json";
|
|
263
|
+
let res;
|
|
264
|
+
let text;
|
|
265
|
+
try {
|
|
266
|
+
({ res, text } = await this.fetchWithTimeout(target, { method, headers, body: hasBody ? JSON.stringify(body) : undefined }, path));
|
|
267
|
+
}
|
|
268
|
+
catch (err) {
|
|
269
|
+
// Network error or timeout: the request may or may not have reached the
|
|
270
|
+
// API, so only reads are retried; writes rethrow immediately.
|
|
271
|
+
if (idempotent && attempt < maxRetries) {
|
|
272
|
+
await delay(this.backoffMs(attempt));
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
throw err;
|
|
276
|
+
}
|
|
277
|
+
// An expired/revoked access token: re-mint once and replay. The request
|
|
278
|
+
// never executed, so this is safe for writes too.
|
|
279
|
+
if (res.status === 401 && this.canRefresh() && !refreshedOn401) {
|
|
280
|
+
refreshedOn401 = true;
|
|
281
|
+
await this.accessToken(true);
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
// 429 means the request was rejected before executing — safe to retry for
|
|
285
|
+
// any method. 5xx is ambiguous (the write may have committed), so it is
|
|
286
|
+
// gated to idempotent requests.
|
|
287
|
+
const transient = res.status === 429 || (idempotent && res.status >= 500 && res.status < 600);
|
|
288
|
+
if (transient && attempt < maxRetries) {
|
|
289
|
+
await delay(this.backoffMs(attempt, res));
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
let data = undefined;
|
|
293
|
+
if (text) {
|
|
294
|
+
try {
|
|
295
|
+
data = JSON.parse(text);
|
|
296
|
+
}
|
|
297
|
+
catch {
|
|
298
|
+
data = text;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
if (!res.ok)
|
|
302
|
+
throw new GoogleContactsError(res.status, data);
|
|
303
|
+
return data;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
/** Joins a person-fields mask, falling back to the compact default. */
|
|
307
|
+
mask(fields, fallback = DEFAULT_PERSON_FIELDS) {
|
|
308
|
+
return fields && fields.length > 0 ? fields.join(",") : fallback;
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Sends the warmup request Google's docs recommend (an empty query primes
|
|
312
|
+
* the server-side search cache) — ONCE per endpoint per client session, not
|
|
313
|
+
* before every search: repeating it would double the spend against the tight
|
|
314
|
+
* per-user quota (~90 requests/min). It runs with retries disabled — a
|
|
315
|
+
* warmup 429 must not burn seconds of backoff before the real query — and a
|
|
316
|
+
* failure is swallowed: it only costs result freshness, never the search.
|
|
317
|
+
*/
|
|
318
|
+
async warmupSearch(path, readMask) {
|
|
319
|
+
if (this.warmedSearchPaths.has(path))
|
|
320
|
+
return;
|
|
321
|
+
this.warmedSearchPaths.add(path);
|
|
322
|
+
await this.request("GET", path, undefined, { query: "", readMask }, { retries: 0 }).catch(() => undefined);
|
|
323
|
+
}
|
|
324
|
+
// ---- Contacts: read ----
|
|
325
|
+
/**
|
|
326
|
+
* Lists the account's contacts (people/me/connections) with pagination,
|
|
327
|
+
* sorting and incremental sync via sync tokens. The People API requires an
|
|
328
|
+
* explicit personFields mask; the compact default fills in when the tool
|
|
329
|
+
* passes none.
|
|
330
|
+
*/
|
|
331
|
+
async listContacts(p = {}) {
|
|
332
|
+
return this.request("GET", "v1/people/me/connections", undefined, compact({
|
|
333
|
+
personFields: this.mask(p.personFields),
|
|
334
|
+
pageSize: p.pageSize,
|
|
335
|
+
pageToken: p.pageToken,
|
|
336
|
+
sortOrder: p.sortOrder,
|
|
337
|
+
requestSyncToken: p.requestSyncToken,
|
|
338
|
+
syncToken: p.syncToken,
|
|
339
|
+
}));
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Searches the account's saved contacts. The first search of the session
|
|
343
|
+
* warms the server-side cache first (see {@link warmupSearch}); later
|
|
344
|
+
* searches go straight to the real query.
|
|
345
|
+
*/
|
|
346
|
+
async searchContacts(p) {
|
|
347
|
+
const readMask = this.mask(p.readMask);
|
|
348
|
+
await this.warmupSearch("v1/people:searchContacts", readMask);
|
|
349
|
+
return this.request("GET", "v1/people:searchContacts", undefined, compact({ query: p.query, readMask, pageSize: p.pageSize }));
|
|
350
|
+
}
|
|
351
|
+
/** One person by resource name ("people/c...", or "people/me" for the caller). */
|
|
352
|
+
async getContact(resourceName, personFields) {
|
|
353
|
+
assertResourceName(resourceName, "people");
|
|
354
|
+
return this.request("GET", `v1/${resourceName}`, undefined, {
|
|
355
|
+
personFields: this.mask(personFields),
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
/** Up to 200 people in one call (people:batchGet with repeated resourceNames). */
|
|
359
|
+
async batchGetContacts(resourceNames, personFields) {
|
|
360
|
+
for (const name of resourceNames)
|
|
361
|
+
assertResourceName(name, "people");
|
|
362
|
+
return this.request("GET", "v1/people:batchGet", undefined, {
|
|
363
|
+
resourceNames,
|
|
364
|
+
personFields: this.mask(personFields),
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
// ---- Contacts: write ----
|
|
368
|
+
/** Creates one contact from the normalized vocabulary; returns the person with the given mask. */
|
|
369
|
+
async createContact(fields, personFields) {
|
|
370
|
+
const { person, fieldGroups } = buildPerson(fields);
|
|
371
|
+
if (fieldGroups.length === 0)
|
|
372
|
+
throw new Error("At least one contact field is required.");
|
|
373
|
+
return this.request("POST", "v1/people:createContact", person, {
|
|
374
|
+
personFields: this.mask(personFields),
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Updates one contact. The People API demands the person's current etag —
|
|
379
|
+
* a stale etag fails with 400 so concurrent edits are never silently
|
|
380
|
+
* overwritten. When the caller has no etag, the current one is fetched
|
|
381
|
+
* first (a GET, so retry-safe); the PATCH itself is never retried on
|
|
382
|
+
* ambiguous failures. `updatePersonFields` is the computed group list from
|
|
383
|
+
* buildPerson, and each masked group is replaced as a whole.
|
|
384
|
+
*/
|
|
385
|
+
async updateContact(p) {
|
|
386
|
+
assertResourceName(p.resourceName, "people");
|
|
387
|
+
const { person, fieldGroups } = buildPerson(p.fields);
|
|
388
|
+
if (fieldGroups.length === 0)
|
|
389
|
+
throw new Error("At least one contact field to update is required.");
|
|
390
|
+
let etag = p.etag;
|
|
391
|
+
if (!etag) {
|
|
392
|
+
const current = await this.request("GET", `v1/${p.resourceName}`, undefined, {
|
|
393
|
+
personFields: "metadata",
|
|
394
|
+
});
|
|
395
|
+
etag = current.etag;
|
|
396
|
+
if (!etag)
|
|
397
|
+
throw new Error("Could not read the current etag of the contact — does it still exist?");
|
|
398
|
+
}
|
|
399
|
+
return this.request("PATCH", `v1/${p.resourceName}:updateContact`, { ...person, etag }, {
|
|
400
|
+
updatePersonFields: fieldGroups.join(","),
|
|
401
|
+
personFields: this.mask(p.personFields),
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
/** Deletes one contact permanently. */
|
|
405
|
+
async deleteContact(resourceName) {
|
|
406
|
+
assertResourceName(resourceName, "people");
|
|
407
|
+
return this.request("DELETE", `v1/${resourceName}:deleteContact`);
|
|
408
|
+
}
|
|
409
|
+
// ---- Contacts: batch mutations ----
|
|
410
|
+
/** Creates up to 200 contacts in one call; atomic per request. */
|
|
411
|
+
async batchCreateContacts(contacts, readMask) {
|
|
412
|
+
const wrapped = contacts.map((fields, i) => {
|
|
413
|
+
const { person, fieldGroups } = buildPerson(fields);
|
|
414
|
+
if (fieldGroups.length === 0) {
|
|
415
|
+
throw new Error(`Contact #${i} has no fields — every entry needs at least one contact field.`);
|
|
416
|
+
}
|
|
417
|
+
return { contactPerson: person };
|
|
418
|
+
});
|
|
419
|
+
return this.request("POST", "v1/people:batchCreateContacts", {
|
|
420
|
+
contacts: wrapped,
|
|
421
|
+
readMask: this.mask(readMask),
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Updates up to 200 contacts in one call. The API applies ONE shared
|
|
426
|
+
* updateMask — computed here as the union of every entry's field groups, so
|
|
427
|
+
* a group provided by one entry and omitted by another is CLEARED on the
|
|
428
|
+
* latter (documented on the tool). Missing etags are resolved with a single
|
|
429
|
+
* batchGet (a GET, retry-safe) before the one write.
|
|
430
|
+
*/
|
|
431
|
+
async batchUpdateContacts(updates, readMask) {
|
|
432
|
+
const built = updates.map((u, i) => {
|
|
433
|
+
assertResourceName(u.resourceName, "people");
|
|
434
|
+
const { person, fieldGroups } = buildPerson(u.fields);
|
|
435
|
+
if (fieldGroups.length === 0) {
|
|
436
|
+
throw new Error(`Update #${i} has no fields — every entry needs at least one contact field.`);
|
|
437
|
+
}
|
|
438
|
+
return { ...u, person, fieldGroups };
|
|
439
|
+
});
|
|
440
|
+
const unionMask = [];
|
|
441
|
+
for (const b of built) {
|
|
442
|
+
for (const group of b.fieldGroups)
|
|
443
|
+
if (!unionMask.includes(group))
|
|
444
|
+
unionMask.push(group);
|
|
445
|
+
}
|
|
446
|
+
const missing = built.filter((b) => !b.etag).map((b) => b.resourceName);
|
|
447
|
+
const etags = new Map();
|
|
448
|
+
if (missing.length > 0) {
|
|
449
|
+
const res = await this.request("GET", "v1/people:batchGet", undefined, { resourceNames: missing, personFields: "metadata" });
|
|
450
|
+
for (const r of res.responses ?? []) {
|
|
451
|
+
const rn = r.requestedResourceName ?? r.person?.resourceName;
|
|
452
|
+
if (rn && r.person?.etag)
|
|
453
|
+
etags.set(rn, r.person.etag);
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
const contacts = {};
|
|
457
|
+
for (const b of built) {
|
|
458
|
+
const etag = b.etag ?? etags.get(b.resourceName);
|
|
459
|
+
if (!etag) {
|
|
460
|
+
throw new Error("Could not read the current etag of every contact — check that they all exist.");
|
|
461
|
+
}
|
|
462
|
+
contacts[b.resourceName] = { ...b.person, etag };
|
|
463
|
+
}
|
|
464
|
+
return this.request("POST", "v1/people:batchUpdateContacts", {
|
|
465
|
+
contacts,
|
|
466
|
+
updateMask: unionMask.join(","),
|
|
467
|
+
readMask: this.mask(readMask),
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
/** Deletes up to 500 contacts in one call. Permanent for every one of them. */
|
|
471
|
+
async batchDeleteContacts(resourceNames) {
|
|
472
|
+
for (const name of resourceNames)
|
|
473
|
+
assertResourceName(name, "people");
|
|
474
|
+
return this.request("POST", "v1/people:batchDeleteContacts", { resourceNames });
|
|
475
|
+
}
|
|
476
|
+
// ---- Contact groups ----
|
|
477
|
+
/** Lists contact groups (user labels and system groups like myContacts/starred). */
|
|
478
|
+
async listContactGroups(p = {}) {
|
|
479
|
+
return this.request("GET", "v1/contactGroups", undefined, compact({
|
|
480
|
+
pageSize: p.pageSize,
|
|
481
|
+
pageToken: p.pageToken,
|
|
482
|
+
groupFields: p.groupFields?.length ? p.groupFields.join(",") : undefined,
|
|
483
|
+
syncToken: p.syncToken,
|
|
484
|
+
}));
|
|
485
|
+
}
|
|
486
|
+
/** One group by resource name; maxMembers > 0 also returns memberResourceNames. */
|
|
487
|
+
async getContactGroup(resourceName, opts = {}) {
|
|
488
|
+
assertResourceName(resourceName, "contactGroups");
|
|
489
|
+
return this.request("GET", `v1/${resourceName}`, undefined, compact({
|
|
490
|
+
maxMembers: opts.maxMembers,
|
|
491
|
+
groupFields: opts.groupFields?.length ? opts.groupFields.join(",") : undefined,
|
|
492
|
+
}));
|
|
493
|
+
}
|
|
494
|
+
/** Creates a user contact group with the given display name. */
|
|
495
|
+
async createContactGroup(name) {
|
|
496
|
+
return this.request("POST", "v1/contactGroups", { contactGroup: { name } });
|
|
497
|
+
}
|
|
498
|
+
/**
|
|
499
|
+
* Renames a user contact group. Like contacts, groups are etag-guarded:
|
|
500
|
+
* the current etag is fetched first (GET, retry-safe) when not provided.
|
|
501
|
+
*/
|
|
502
|
+
async updateContactGroup(p) {
|
|
503
|
+
assertResourceName(p.resourceName, "contactGroups");
|
|
504
|
+
let etag = p.etag;
|
|
505
|
+
if (!etag) {
|
|
506
|
+
const current = await this.request("GET", `v1/${p.resourceName}`);
|
|
507
|
+
etag = current.etag;
|
|
508
|
+
if (!etag)
|
|
509
|
+
throw new Error("Could not read the current etag of the contact group — does it still exist?");
|
|
510
|
+
}
|
|
511
|
+
return this.request("PUT", `v1/${p.resourceName}`, { contactGroup: { name: p.name, etag } });
|
|
512
|
+
}
|
|
513
|
+
/** Deletes a user group; deleteContacts=true also deletes all its member contacts. */
|
|
514
|
+
async deleteContactGroup(resourceName, deleteContacts) {
|
|
515
|
+
assertResourceName(resourceName, "contactGroups");
|
|
516
|
+
return this.request("DELETE", `v1/${resourceName}`, undefined, compact({ deleteContacts }));
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* Adds/removes contacts to/from a group in one call. The response lists
|
|
520
|
+
* notFoundResourceNames and canNotRemoveLastContactGroupResourceNames —
|
|
521
|
+
* a 200 does not mean every member changed; the tool surfaces the body as-is.
|
|
522
|
+
*/
|
|
523
|
+
async modifyGroupMembers(p) {
|
|
524
|
+
assertResourceName(p.resourceName, "contactGroups");
|
|
525
|
+
for (const member of [...(p.add ?? []), ...(p.remove ?? [])])
|
|
526
|
+
assertResourceName(member, "people");
|
|
527
|
+
return this.request("POST", `v1/${p.resourceName}/members:modify`, compact({ resourceNamesToAdd: p.add, resourceNamesToRemove: p.remove }));
|
|
528
|
+
}
|
|
529
|
+
// ---- Other contacts (separate read-only scope) ----
|
|
530
|
+
/** Lists "Other contacts" — auto-saved addresses outside the saved contact list. */
|
|
531
|
+
async listOtherContacts(p = {}) {
|
|
532
|
+
return this.request("GET", "v1/otherContacts", undefined, compact({
|
|
533
|
+
readMask: this.mask(p.readMask, DEFAULT_OTHER_CONTACT_FIELDS),
|
|
534
|
+
pageSize: p.pageSize,
|
|
535
|
+
pageToken: p.pageToken,
|
|
536
|
+
requestSyncToken: p.requestSyncToken,
|
|
537
|
+
syncToken: p.syncToken,
|
|
538
|
+
}));
|
|
539
|
+
}
|
|
540
|
+
/** Searches "Other contacts", with the same once-per-session warmup as searchContacts. */
|
|
541
|
+
async searchOtherContacts(p) {
|
|
542
|
+
const readMask = this.mask(p.readMask, DEFAULT_OTHER_CONTACT_FIELDS);
|
|
543
|
+
await this.warmupSearch("v1/otherContacts:search", readMask);
|
|
544
|
+
return this.request("GET", "v1/otherContacts:search", undefined, compact({ query: p.query, readMask, pageSize: p.pageSize }));
|
|
545
|
+
}
|
|
546
|
+
/** Copies one "Other contact" into My Contacts — their only write operation. */
|
|
547
|
+
async copyOtherContact(p) {
|
|
548
|
+
assertResourceName(p.resourceName, "otherContacts");
|
|
549
|
+
return this.request("POST", `v1/${p.resourceName}:copyOtherContactToMyContactsGroup`, {
|
|
550
|
+
copyMask: this.mask(p.copyMask, DEFAULT_OTHER_CONTACT_FIELDS),
|
|
551
|
+
readMask: this.mask(p.readMask),
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
/** Drops keys whose value is `undefined` so they are not sent to the API. */
|
|
556
|
+
function compact(obj) {
|
|
557
|
+
return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined));
|
|
558
|
+
}
|
|
559
|
+
function delay(ms) {
|
|
560
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
561
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/** Default Google People API host. */
|
|
2
|
+
export const DEFAULT_BASE = "https://people.googleapis.com";
|
|
3
|
+
/**
|
|
4
|
+
* A malformed environment variable. Thrown instead of exiting on the spot so
|
|
5
|
+
* index.ts can catch it, report the drop-off and start degraded instead of
|
|
6
|
+
* dying; `reason` is the machine-readable code that ships with that ping
|
|
7
|
+
* (never a variable's value).
|
|
8
|
+
*/
|
|
9
|
+
export class ConfigError extends Error {
|
|
10
|
+
reason;
|
|
11
|
+
constructor(message, reason) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = "ConfigError";
|
|
14
|
+
this.reason = reason;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* What a tool call without credentials reads. The first sentence is the
|
|
19
|
+
* historical startup error, verbatim — the rest exists because credentials come
|
|
20
|
+
* only from the environment, so the fix is an operator action plus a restart,
|
|
21
|
+
* never a retry.
|
|
22
|
+
*/
|
|
23
|
+
export const MISSING_CREDENTIALS_MESSAGE = "Google OAuth credentials are required: set GOOGLE_CONTACTS_CLIENT_ID + " +
|
|
24
|
+
"GOOGLE_CONTACTS_CLIENT_SECRET + GOOGLE_CONTACTS_REFRESH_TOKEN (recommended), or " +
|
|
25
|
+
"GOOGLE_CONTACTS_ACCESS_TOKEN with a short-lived access token. " +
|
|
26
|
+
"This is not a network failure and retrying will not help: the operator must set these " +
|
|
27
|
+
"environment variables in the MCP client's server config and restart the server — they are " +
|
|
28
|
+
"read only at startup.";
|
|
29
|
+
/**
|
|
30
|
+
* Raised when a tool call needs credentials and none were configured. The
|
|
31
|
+
* message is the whole point of the class: it is the only text the calling
|
|
32
|
+
* model reads about the missing setup, so it names the fix (which variables,
|
|
33
|
+
* and that a restart is needed) instead of the failure.
|
|
34
|
+
*/
|
|
35
|
+
export class CredentialsError extends Error {
|
|
36
|
+
constructor(message = MISSING_CREDENTIALS_MESSAGE) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.name = "CredentialsError";
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** True when the config carries usable credentials (the full refresh triple or a static token). */
|
|
42
|
+
export function hasCredentials(config) {
|
|
43
|
+
return Boolean(config.accessToken || (config.clientId && config.clientSecret && config.refreshToken));
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Builds the client config from environment variables.
|
|
47
|
+
*
|
|
48
|
+
* Missing credentials are NOT an error here: the server starts anyway and the
|
|
49
|
+
* client raises {@link CredentialsError} on the first tool call, so an
|
|
50
|
+
* unconfigured install completes the MCP handshake and carries the fix into
|
|
51
|
+
* the session instead of dying before it with nothing to read. A malformed
|
|
52
|
+
* setup — the refresh triple set only partially — still throws, because
|
|
53
|
+
* guessing what the user meant is worse.
|
|
54
|
+
*
|
|
55
|
+
* GOOGLE_CONTACTS_CLIENT_ID OAuth2 client id (refresh flow, recommended)
|
|
56
|
+
* GOOGLE_CONTACTS_CLIENT_SECRET OAuth2 client secret (refresh flow)
|
|
57
|
+
* GOOGLE_CONTACTS_REFRESH_TOKEN OAuth2 refresh token (refresh flow)
|
|
58
|
+
* GOOGLE_CONTACTS_ACCESS_TOKEN static access token (alternative; expires in ~1h)
|
|
59
|
+
* GOOGLE_CONTACTS_API_BASE API root override (default https://people.googleapis.com)
|
|
60
|
+
* GOOGLE_CONTACTS_TIMEOUT_MS per-request timeout (default 60000)
|
|
61
|
+
* GOOGLE_CONTACTS_MAX_RETRIES retries on transient errors (default 3)
|
|
62
|
+
*/
|
|
63
|
+
export function loadConfig() {
|
|
64
|
+
const clientId = process.env.GOOGLE_CONTACTS_CLIENT_ID;
|
|
65
|
+
const clientSecret = process.env.GOOGLE_CONTACTS_CLIENT_SECRET;
|
|
66
|
+
const refreshToken = process.env.GOOGLE_CONTACTS_REFRESH_TOKEN;
|
|
67
|
+
const accessToken = process.env.GOOGLE_CONTACTS_ACCESS_TOKEN;
|
|
68
|
+
const oauthProvided = [clientId, clientSecret, refreshToken].filter(Boolean).length;
|
|
69
|
+
if (oauthProvided > 0 && oauthProvided < 3) {
|
|
70
|
+
throw new ConfigError("GOOGLE_CONTACTS_CLIENT_ID, GOOGLE_CONTACTS_CLIENT_SECRET and GOOGLE_CONTACTS_REFRESH_TOKEN must be set together (OAuth2 refresh flow).", "incomplete_oauth_config");
|
|
71
|
+
}
|
|
72
|
+
const timeoutMs = Number(process.env.GOOGLE_CONTACTS_TIMEOUT_MS);
|
|
73
|
+
const maxRetries = Number(process.env.GOOGLE_CONTACTS_MAX_RETRIES);
|
|
74
|
+
return {
|
|
75
|
+
clientId,
|
|
76
|
+
clientSecret,
|
|
77
|
+
refreshToken,
|
|
78
|
+
accessToken,
|
|
79
|
+
apiBase: process.env.GOOGLE_CONTACTS_API_BASE || DEFAULT_BASE,
|
|
80
|
+
timeoutMs: Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 60_000,
|
|
81
|
+
maxRetries: Number.isFinite(maxRetries) && maxRetries >= 0 ? maxRetries : 3,
|
|
82
|
+
};
|
|
83
|
+
}
|