@a1-x-tech/mcp-google-sheets 1.0.0 → 1.1.1

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
@@ -273,7 +273,7 @@ Every variable is optional — with none of them the server connects [from the c
273
273
 
274
274
  ## Data, limits and background work
275
275
 
276
- - **Requests go to Google.** The local server refreshes Google OAuth tokens and calls the Sheets API — and, for spreadsheet search and sharing only, the Drive API. Its anonymous telemetry contains an installation ID, package version, AI client and platform versions, and tool names — never OAuth tokens, spreadsheet data, tool arguments or prompts. Set `ASKADS_TELEMETRY=0` to opt out.
276
+ - **Requests go to Google.** The local server refreshes Google OAuth tokens and calls the Sheets API — and, for spreadsheet search and sharing only, the Drive API. Its anonymous telemetry contains an installation ID, package version, AI client and platform versions, and tool names — never OAuth tokens, spreadsheet data, tool arguments or prompts. For each tool call it also sends the outcome and, on failure, an excerpt of the error text with e-mails, addresses, tokens, numbers of 4+ digits and quoted text replaced by `#`; a value from your request can appear in it if the error text contains it. Set `ASKADS_TELEMETRY=0` to opt out.
277
277
  - **Google applies per-minute quotas.** The documented limits are 300 reads and 300 writes per minute per project, and 60 of each per user; a batch call counts once however many ranges or requests it carries. A spreadsheet holds at most 10,000,000 cells. On `429`, the server uses backoff; reads also retry after network and `5xx` errors, while writes are not replayed after an uncertain failure.
278
278
  - **There is no background polling.** The server runs only when called. If your AI app supports scheduled tasks, it can check a spreadsheet periodically.
279
279
 
package/README.ru.md CHANGED
@@ -273,7 +273,7 @@ Refresh token OAuth-приложения в режиме Testing может ис
273
273
 
274
274
  ## Данные, лимиты и работа в фоне
275
275
 
276
- - **Запросы идут в Google.** Локальный сервер обновляет OAuth-токены Google и вызывает Sheets API, а для поиска таблиц и управления доступом — Drive API. Анонимная телеметрия содержит ID установки, версию пакета, версии AI-клиента и платформы и имена инструментов — но не OAuth-токены, данные таблиц, аргументы или промпты. Чтобы отключить её, задайте `ASKADS_TELEMETRY=0`.
276
+ - **Запросы идут в Google.** Локальный сервер обновляет OAuth-токены Google и вызывает Sheets API, а для поиска таблиц и управления доступом — Drive API. Анонимная телеметрия содержит ID установки, версию пакета, версии AI-клиента и платформы и имена инструментов — но не OAuth-токены, данные таблиц, аргументы или промпты. При вызове инструмента сервер также отправляет его исход, а при ошибке - фрагмент её текста: код и сообщение, в которых e-mail, адреса, токены, числа от 4 цифр и текст в кавычках заменены на «#». Если в тексте ошибки есть значение из запроса, оно тоже может попасть во фрагмент. Чтобы отключить её, задайте `ASKADS_TELEMETRY=0`.
277
277
  - **У Google есть поминутные квоты.** Документированные лимиты: 300 чтений и 300 записей в минуту на проект и по 60 на пользователя; пакетный вызов считается один раз, сколько бы диапазонов или запросов он ни нёс. В одной таблице не больше 10 000 000 ячеек. При `429` сервер использует задержку; чтение также повторяется после сетевых и `5xx` ошибок, а запись после неопределённой ошибки не повторяется.
278
278
  - **Постоянного опроса нет.** Сервер работает только при вызове. Если AI-приложение поддерживает задания по расписанию, оно может периодически проверять таблицу.
279
279
 
package/dist/telemetry.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * Anonymous usage telemetry — fire-and-forget pings to usage.gistrec.cloud.
3
3
  *
4
4
  * Privacy contract (mirrored by the receiver): only an anonymous random
5
- * instance id, event/tool names, a fixed-vocabulary failure reason and
5
+ * instance id, event/tool names, a fixed-vocabulary failure reason or tool outcome and
6
6
  * environment versions ever leave the machine. The OAuth credentials,
7
7
  * spreadsheet data, tool arguments, prompts and the names or values of
8
8
  * environment variables are never read, serialized or sent. Sends are capped
@@ -64,6 +64,10 @@ export class Telemetry {
64
64
  setClientInfo(info) {
65
65
  this.clientInfo = info;
66
66
  }
67
+ /** Whether pings go out at all (ASKADS_TELEMETRY opt-out). */
68
+ isEnabled() {
69
+ return this.enabled;
70
+ }
67
71
  /** Fire-and-forget: the server's own work never waits on a ping. */
68
72
  send(event, fields = {}) {
69
73
  void this.post(event, fields);
@@ -87,7 +91,8 @@ export class Telemetry {
87
91
  client_name: this.clientInfo?.name,
88
92
  client_version: this.clientInfo?.version,
89
93
  tool: fields.tool,
90
- reason: fields.reason,
94
+ reason: wireReason(event, fields.reason),
95
+ error_detail: event === "tool_call" ? fields.error_detail : undefined,
91
96
  node_version: process.version,
92
97
  os: process.platform,
93
98
  });
@@ -104,17 +109,247 @@ export class Telemetry {
104
109
  }
105
110
  }
106
111
  }
112
+ /** How a tool call ended; only these constants leave the machine. */
113
+ export const TOOL_OUTCOMES = [
114
+ "ok",
115
+ "error_auth",
116
+ "error_permission",
117
+ "error_not_found",
118
+ "error_rate_limit",
119
+ "error_invalid_request",
120
+ "error_upstream",
121
+ "error_timeout",
122
+ "error_network",
123
+ "error_internal",
124
+ "error_other",
125
+ ];
126
+ /** Drops a tool_call reason that is not in TOOL_OUTCOMES. */
127
+ function wireReason(event, reason) {
128
+ if (event !== "tool_call" || reason === undefined)
129
+ return reason;
130
+ return TOOL_OUTCOMES.includes(reason) ? reason : undefined;
131
+ }
132
+ // First match wins. Direct answers "no access to this client" with auth code 53, so that
133
+ // permission line goes before auth.
134
+ const OUTCOME_PATTERNS = [
135
+ ["error_timeout", /timed?[ _-]?out|таймаут|ETIMEDOUT|AbortError|не был готов|not ready/i],
136
+ ["error_network", /ECONNRESET|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|EPIPE|fetch failed|socket hang up/i],
137
+ ["error_rate_limit", /\b429\b|rate[ _-]?limit|too many requests|quota|квот|лимит|\[(?:56|152|506|9000)\]/i],
138
+ ["error_permission", /нет доступа к кабинету|не подключ[её]н к аккаунту/i],
139
+ [
140
+ "error_auth",
141
+ /\b401\b|unauthori[sz]ed|unauthenticated|invalid[ _-]?(?:token|grant|credentials)|token (?:expired|revoked)|login required|AuthRequired|авториз|не подключ|\[53\]/i,
142
+ ],
143
+ ["error_permission", /\b403\b|forbidden|access[ _-]?denied|permission|insufficient[ _-]?scope|нет доступа|\[(?:54|3228)\]/i],
144
+ ["error_not_found", /\b404\b|not[ _-]?found|не найден|не существует|\[8800\]/i],
145
+ ["error_upstream", /\b5\d\d\b|\b204\b|unavailable|недоступ|internal server error|bad gateway|\[(?:52|1000|1001|1002)\]/i],
146
+ ["error_invalid_request", /\b400\b|\b422\b|bad request|invalid|syntax|некоррект|неверн|недопустим|required|обязател|expected|must (?:be|contain|have)|\[(?:4000|4001|4003|5000|8000)\]/i],
147
+ ];
148
+ // An API code at the head of the message wins over the text, which may quote field names
149
+ // ("ForbiddenPlatform" in a [8000] list of allowed values). 53 is absent: the text tells a
150
+ // dead token from no access to a client.
151
+ const CODE_OUTCOMES = new Map([
152
+ ...["56", "152", "506", "9000"].map((c) => [c, "error_rate_limit"]),
153
+ ...["54", "3228"].map((c) => [c, "error_permission"]),
154
+ ["8800", "error_not_found"],
155
+ ...["52", "1000", "1001", "1002"].map((c) => [c, "error_upstream"]),
156
+ ...["4000", "4001", "4003", "5000", "8000"].map((c) => [c, "error_invalid_request"]),
157
+ ]);
158
+ const LEADING_CODE = /^[^[\n]{0,60}\[(\d{1,5})\]/;
159
+ // Inputs are cut before any regex runs: a long argument echoed in an error must not stall the call.
160
+ const TEXT_MAX = 4000;
161
+ function resultText(value) {
162
+ if (value instanceof Error)
163
+ return `${value.name} ${value.message}`.slice(0, TEXT_MAX);
164
+ const content = value?.content;
165
+ if (!Array.isArray(content))
166
+ return "";
167
+ return content
168
+ .map((part) => (part && typeof part === "object" && typeof part.text === "string" ? part.text : ""))
169
+ .join("\n")
170
+ .slice(0, TEXT_MAX);
171
+ }
172
+ /** `toolOutcome(result)` for a returned result, `toolOutcome(undefined, error)` for a thrown one. */
173
+ export function toolOutcome(result, ...thrown) {
174
+ const didThrow = thrown.length > 0;
175
+ if (!didThrow && !result?.isError)
176
+ return "ok";
177
+ const text = resultText(didThrow ? thrown[0] : result);
178
+ const byCode = CODE_OUTCOMES.get(LEADING_CODE.exec(text)?.[1] ?? "");
179
+ if (byCode)
180
+ return byCode;
181
+ for (const [outcome, pattern] of OUTCOME_PATTERNS)
182
+ if (pattern.test(text))
183
+ return outcome;
184
+ return didThrow ? "error_internal" : "error_other";
185
+ }
186
+ /** Error excerpt: allowlisted fragments of the error text, masked (port of the Ask Ads gateway's). */
187
+ export const DETAIL_MAX = 200;
188
+ const PICK = /\bHTTP (?<http>\d{3})\b(?::\s*(?<htext>[^{[]{1,200}))?|^(?:Ошибка: )?\[(?<bcode>\d{1,5})\]\s*(?<btext>[^;(]{1,200})|\[(?<tag>[A-Za-z][A-Za-z_]{2,})\]\s*(?<ttext>[^;(]{0,200})|\berror_code["']?\s*[:=]\s*["']?(?<code>\d{1,5})\b|\b(?<key>error_string|error_detail|error_type|message)["']?\s*[:=]\s*["']?(?<value>[^"'}\]]{1,80})|\b(?<net>ECONNRESET|ECONNREFUSED|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|timed out|fetch failed|socket hang up|connection closed)\b|(?<netru>превысил таймаут)/gi;
189
+ const SCRUB = /(?<key>(?:login|password|secret|token|api[_-]?key|authorization)\s*[:=]\s*["']?|(?:bearer|basic)\s+)(?<val>[^,;]+)|[^\s,;]*(?:@|:\/\/|%3A|\p{L}\.\p{L})[^\s,;]*|(?<key2>\b(?:token|secret|password|api[_-]?key|access_token|refresh_token|client_secret)\s+)(?!(?:expired|invalid|is|was|for|has|not|missing|required|revoked|provided|type)\b)\S+|\b(?:y0_|AQAA|AQVN|t1\.|sk-|vk1\.|vk_|ghp_|ya29\.)\S+|\b(?=[\w-]*\d)(?=[\w-]*[A-Za-z])[\w-]{20,}\b|\+?\d(?:[\s().-]*\d){3,}/giu;
190
+ const QUOTED = /(?<!\p{L})'[^'\n]+(?:'(?!\p{L})|$)|"[^"\n]+(?:"|$)|«[^»]+(?:»|$)/gu;
191
+ function scrub(value, quoted = true) {
192
+ return (quoted ? value.replace(QUOTED, "#") : value)
193
+ .replace(SCRUB, (...args) => {
194
+ const groups = args[args.length - 1];
195
+ return (groups.key ?? groups.key2 ?? "") + "#";
196
+ })
197
+ .replace(/^[ ;:,.]+|[ ;:,.]+$/g, "");
198
+ }
199
+ export function errorDetail(text) {
200
+ const flat = text.slice(0, 2000).split(/\s+/).filter(Boolean).join(" ");
201
+ const parts = [];
202
+ PICK.lastIndex = 0;
203
+ for (let m = PICK.exec(flat); m; m = PICK.exec(flat)) {
204
+ const g = m.groups ?? {};
205
+ let token;
206
+ if (g.http)
207
+ token = `HTTP ${g.http} ${scrub(g.htext ?? "")}`;
208
+ else if (g.bcode)
209
+ token = `code=${g.bcode} ${scrub(g.btext ?? "")}`;
210
+ else if (g.tag) {
211
+ // Tags are upper-case only; the rest of PICK is case-insensitive.
212
+ if (!/^[A-Z][A-Z_]{2,}$/.test(g.tag)) {
213
+ PICK.lastIndex = m.index + 1;
214
+ continue;
215
+ }
216
+ token = `${g.tag} ${scrub(g.ttext ?? "")}`;
217
+ }
218
+ else if (g.code)
219
+ token = `code=${g.code}`;
220
+ else if (g.key)
221
+ token = `${g.key.toLowerCase()}=${scrub(g.value ?? "")}`;
222
+ else
223
+ token = (g.net ?? g.netru ?? "").toLowerCase();
224
+ token = token.trim();
225
+ if (!parts.includes(token))
226
+ parts.push(token);
227
+ }
228
+ return parts.join("; ").slice(0, DETAIL_MAX);
229
+ }
230
+ /** Set by fail(), never serialized: our own refusal ("local"), a bug in our code ("internal") or a failed fetch ("network"). */
231
+ const FAILURE_ORIGIN = new WeakMap();
232
+ const JS_ERRORS = new Set(["TypeError", "ReferenceError", "RangeError", "SyntaxError", "EvalError", "URIError"]);
233
+ function jsBug(err) {
234
+ if (!(err instanceof Error) || !JS_ERRORS.has(err.name))
235
+ return undefined;
236
+ // Node's own errors (ERR_INVALID_ARG_TYPE …, system errors) quote the values passed in: their code only.
237
+ const code = err.code;
238
+ if (code !== undefined || "errno" in err || "syscall" in err) {
239
+ return typeof code === "string" && /^[A-Z][A-Z0-9_]{2,40}$/.test(code) ? `${err.name} ${code}` : err.name;
240
+ }
241
+ return `${err.name}: ${err.message.split("\n")[0]}`;
242
+ }
243
+ /**
244
+ * Only the class name of this server's own errors (AuthRequiredError, AbortError), used when the
245
+ * allowlist finds nothing. Never the message: a plain Error or a system error (ENOENT …) can carry
246
+ * user data, so those send nothing.
247
+ */
248
+ function errorText(err) {
249
+ if (!(err instanceof Error) || "errno" in err || "syscall" in err)
250
+ return undefined;
251
+ return /^[A-Z][A-Za-z0-9]*(?:Error|Exception)$/.test(err.name) && err.name !== "Error" ? err.name : undefined;
252
+ }
253
+ /**
254
+ * Node's fetch rejects a network failure as TypeError("fetch failed") with the socket/DNS/TLS error
255
+ * in `cause`. Only cause.code leaves the machine: cause.message names hosts and addresses.
256
+ */
257
+ function fetchFailure(err) {
258
+ if (!(err instanceof Error) || err.name !== "TypeError" || err.message !== "fetch failed")
259
+ return undefined;
260
+ const cause = err.cause;
261
+ if (!cause || typeof cause !== "object")
262
+ return undefined;
263
+ const raw = cause.code;
264
+ const code = typeof raw === "string" && /^[A-Z][A-Z0-9_]{2,40}$/.test(raw) ? raw : "";
265
+ return {
266
+ reason: /TIMEOUT|TIMEDOUT/.test(code) ? "error_timeout" : "error_network",
267
+ text: code ? `fetch failed; ${code.toLowerCase()}` : "fetch failed",
268
+ };
269
+ }
270
+ export function noteFailure(result, err) {
271
+ try {
272
+ if (result && typeof result === "object") {
273
+ const net = fetchFailure(err);
274
+ if (typeof err === "string")
275
+ FAILURE_ORIGIN.set(result, { origin: "local", text: err });
276
+ else if (net)
277
+ FAILURE_ORIGIN.set(result, { origin: "network", ...net });
278
+ else {
279
+ const bug = jsBug(err);
280
+ const text = bug ?? errorText(err);
281
+ if (text)
282
+ FAILURE_ORIGIN.set(result, { origin: bug ? "internal" : "error", text });
283
+ }
284
+ }
285
+ }
286
+ catch {
287
+ // never affects the result
288
+ }
289
+ return result;
290
+ }
291
+ /** A JS error quotes identifiers of our code, not user data, so its quotes are kept. */
292
+ function maskedOwnText(prefix, text, quoted = true) {
293
+ return (prefix + scrub(text.slice(0, 2 * DETAIL_MAX).split(/\s+/).filter(Boolean).join(" "), quoted)).slice(0, DETAIL_MAX);
294
+ }
295
+ /** Best effort: classifying or sending must never change what the tool returns or throws. */
296
+ function reportCall(telemetry, tool, value, thrown) {
297
+ if (!telemetry.isEnabled())
298
+ return;
299
+ try {
300
+ let reason = thrown ? toolOutcome(undefined, value) : toolOutcome(value);
301
+ let detail = "";
302
+ if (reason !== "ok") {
303
+ const noted = value && typeof value === "object" ? FAILURE_ORIGIN.get(value) : undefined;
304
+ const net = noted?.origin === "network" ? noted : thrown ? fetchFailure(value) : undefined;
305
+ const bug = noted?.origin === "internal" ? noted.text : thrown ? jsBug(value) : undefined;
306
+ if (net) {
307
+ reason = net.reason;
308
+ detail = net.text;
309
+ }
310
+ else if (bug) {
311
+ reason = "error_internal";
312
+ detail = maskedOwnText("internal: ", bug, false);
313
+ }
314
+ else if (noted?.origin === "local") {
315
+ reason = "error_invalid_request";
316
+ detail = maskedOwnText("local: ", noted.text);
317
+ }
318
+ else {
319
+ detail = errorDetail(resultText(value));
320
+ const own = noted?.origin === "error" ? noted.text : thrown ? errorText(value) : undefined;
321
+ if (!detail && own) {
322
+ detail = own;
323
+ // The class name ("AuthRequiredError") often says more than the message.
324
+ if (reason === "error_other")
325
+ reason = toolOutcome({ isError: true, content: [{ type: "text", text: own }] });
326
+ }
327
+ }
328
+ }
329
+ telemetry.send("tool_call", { tool, reason, error_detail: detail || undefined });
330
+ }
331
+ catch {
332
+ // never affects the call
333
+ }
334
+ }
107
335
  /**
108
- * Count every tool invocation by name. Wraps registerTool once, before the
109
- * domain modules register their tools, so no per-tool wiring is needed.
110
- * Only the tool *name* is recorded — arguments never reach telemetry.
336
+ * Counts every tool call by name and outcome. Wraps registerTool once, before the domain
337
+ * modules register their tools. Calls rejected by SDK input validation are not counted.
111
338
  */
112
339
  export function instrumentToolCalls(server, telemetry) {
113
340
  const original = server.registerTool.bind(server);
114
341
  // registerTool's generic signature does not survive a wrapper; the runtime
115
342
  // shape (name, config, callback) is stable per SDK contract.
116
- server.registerTool = ((name, config, callback) => original(name, config, ((...args) => {
117
- telemetry.send("tool_call", { tool: name });
118
- return callback(...args);
343
+ server.registerTool = ((name, config, callback) => original(name, config, (async (...args) => {
344
+ let result;
345
+ try {
346
+ result = await callback(...args);
347
+ }
348
+ catch (e) {
349
+ reportCall(telemetry, name, e, true);
350
+ throw e;
351
+ }
352
+ reportCall(telemetry, name, result, false);
353
+ return result;
119
354
  })));
120
355
  }
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { noteFailure } from "../telemetry.js";
2
3
  /**
3
4
  * Schema factories, not shared consts: reusing one zod object across two fields
4
5
  * makes zod-to-json-schema dedupe them into a `$ref`, which some tool-schema
@@ -58,7 +59,11 @@ export function ok(data) {
58
59
  const text = typeof data === "string" ? data : JSON.stringify(data);
59
60
  return { content: [{ type: "text", text: text ?? "null" }] };
60
61
  }
62
+ /** The failed result; also notes, off the wire, whether it is our own refusal or a JS bug (telemetry). */
61
63
  export function fail(err) {
64
+ return noteFailure(failText(err), err);
65
+ }
66
+ function failText(err) {
62
67
  let message = err instanceof Error ? err.message : String(err);
63
68
  // Surface the underlying cause (e.g. the network error behind a timeout) — no
64
69
  // secrets live in cause, and it makes failures far easier to diagnose.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a1-x-tech/mcp-google-sheets",
3
- "version": "1.0.0",
3
+ "version": "1.1.1",
4
4
  "description": "MCP server for the Google Sheets API — search spreadsheets, read and write ranges, manage sheets, formatting, validation, protected ranges, tables, charts and sharing. For Claude, Cursor, Codex and other AI clients.",
5
5
  "mcpName": "io.github.A1-x-Tech/mcp-google-sheets",
6
6
  "type": "module",