gogcli-mcp-drive 2.21.0 → 2.22.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.
@@ -7,7 +7,7 @@
7
7
  },
8
8
  "metadata": {
9
9
  "description": "Extended Google Drive for Claude via gogcli — auth + full Drive support (upload, download, permissions, comments, shared drives)",
10
- "version": "2.21.0"
10
+ "version": "2.22.0"
11
11
  },
12
12
  "plugins": [
13
13
  {
@@ -15,7 +15,7 @@
15
15
  "displayName": "gogcli (Drive)",
16
16
  "source": "./",
17
17
  "description": "Extended Google Drive for Claude via gogcli — auth + full Drive support (upload, download, permissions, comments, shared drives)",
18
- "version": "2.21.0",
18
+ "version": "2.22.0",
19
19
  "author": {
20
20
  "name": "Chris Hall"
21
21
  },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "gogcli-mcp-drive",
3
3
  "displayName": "gogcli (Drive)",
4
- "version": "2.21.0",
4
+ "version": "2.22.0",
5
5
  "description": "Extended Google Drive for Claude via gogcli — auth + full Drive support (upload, download, permissions, comments, shared drives)",
6
6
  "author": {
7
7
  "name": "Chris Hall",
package/README.md CHANGED
@@ -51,7 +51,7 @@ Plus 5 auth tools and 9 base Drive tools (ls, search, get, mkdir, rename, move,
51
51
  | Tool | Description |
52
52
  |------|-------------|
53
53
  | `gog_drive_download` | Download a file (exports Google Docs formats: pdf, docx, xlsx, etc.) |
54
- | `gog_drive_upload` | Upload a local file, optionally replacing an existing file or converting to Google format |
54
+ | `gog_drive_upload` | Upload a local file, optionally replacing an existing file (unconditionally or only at a given version) or converting to Google format |
55
55
  | `gog_drive_sync_push` | Recursively push a local directory's contents into a Drive folder (additive; no remote deletes) |
56
56
  | `gog_drive_copy` | Copy a file to a new file with the given name |
57
57
  | `gog_drive_url` | Print shareable web URLs for one or more files |
package/SKILL.md CHANGED
@@ -35,7 +35,7 @@ Extended Google Drive MCP server via [gogcli](https://github.com/openclaw/gogcli
35
35
  | Tool | What it does |
36
36
  |------|-------------|
37
37
  | `gog_drive_download` | Download a file (Google Docs → pdf/docx/xlsx/etc.) |
38
- | `gog_drive_upload` | Upload a local file, replace existing, or convert to Google format |
38
+ | `gog_drive_upload` | Upload a local file, replace existing (optionally only at a given version), or convert to Google format |
39
39
  | `gog_drive_sync_push` | Recursively push a local directory into a Drive folder (additive; no remote deletes) |
40
40
  | `gog_drive_copy` | Copy a file to a new file |
41
41
  | `gog_drive_url` | Print shareable URLs for one or more files |
package/dist/index.js CHANGED
@@ -31140,6 +31140,21 @@ import { delimiter, join } from "node:path";
31140
31140
  function isGogFileArg(arg) {
31141
31141
  return typeof arg !== "string";
31142
31142
  }
31143
+ var RUNNER_TRANSPORT_BRAND = /* @__PURE__ */ Symbol.for("gogcli.RunnerTransportError");
31144
+ var RunnerTransportError = class extends Error {
31145
+ kind;
31146
+ status;
31147
+ constructor(message, kind, status) {
31148
+ super(message);
31149
+ this.name = "RunnerTransportError";
31150
+ this.kind = kind;
31151
+ this.status = status;
31152
+ Object.defineProperty(this, RUNNER_TRANSPORT_BRAND, { value: true });
31153
+ }
31154
+ };
31155
+ function isRunnerTransportError(err) {
31156
+ return err instanceof Error && err[RUNNER_TRANSPORT_BRAND] === true;
31157
+ }
31143
31158
  var runExecutor = new AsyncLocalStorage();
31144
31159
  var defaultExecutor;
31145
31160
  function setDefaultGogExecutor(executor) {
@@ -31320,7 +31335,11 @@ async function run(args, options = {}) {
31320
31335
  }
31321
31336
  return redact(output);
31322
31337
  } catch (err) {
31323
- throw new Error(redact(err instanceof Error ? err.message : String(err)));
31338
+ const message = redact(err instanceof Error ? err.message : String(err));
31339
+ if (isRunnerTransportError(err)) {
31340
+ throw new RunnerTransportError(message, err.kind, err.status);
31341
+ }
31342
+ throw new Error(message);
31324
31343
  }
31325
31344
  }
31326
31345
  async function runBinary(args, options = {}) {
@@ -31421,6 +31440,13 @@ var TIMESTAMP_KEYS = /* @__PURE__ */ new Set([
31421
31440
  // Calendar event start/end
31422
31441
  "internalDate",
31423
31442
  // Gmail, epoch milliseconds (authoritative)
31443
+ // gog >= 0.35.0 Gmail message AND thread listings. Already offset-bearing
31444
+ // (RFC3339 from internalDate), so it needs no offset repair — it is
31445
+ // allowlisted purely to gain a Display sibling, and to be re-rendered in
31446
+ // DISPLAY_TZ like every other instant. Separately sourced from the sibling
31447
+ // `date`, which is a naive re-format of the sender's Date header; the two may
31448
+ // legitimately disagree. See docs/timestamps.md.
31449
+ "internalDateIso",
31424
31450
  "modifiedTime",
31425
31451
  // Drive
31426
31452
  "createdTime",
@@ -31587,7 +31613,7 @@ function registerRunTool(server, options) {
31587
31613
  function errorText(err) {
31588
31614
  return err instanceof Error ? `Error: ${err.message}` : String(err);
31589
31615
  }
31590
- var DEFINITE_AUTH_PATTERN = /\b(401|unauthorized|invalid_grant)\b/i;
31616
+ var DEFINITE_AUTH_PATTERN = /\b(?:unauthorized|invalid_grant)\b|\b(?:error|status|code|http|responded|response)["']?[\s:=(,]{0,4}401\b/i;
31591
31617
  var STALE_TOKEN_PATTERN = /\b(?:access[ _-]?)?token\b[^.;\n]{0,40}\b(?:has\s+)?(?:been\s+)?(?:expired|revoked)\b|\b(?:expired|revoked)\s+(?:access[ _-]?)?token\b/i;
31592
31618
  var AUTH_ERROR_PATTERN = new RegExp(`${DEFINITE_AUTH_PATTERN.source}|${STALE_TOKEN_PATTERN.source}`, "i");
31593
31619
  var INVALID_GRANT_PATTERN = /invalid_grant|token has been expired or revoked/i;
@@ -31597,6 +31623,14 @@ var AUTH_HINT = "\n\nAuthentication may have expired. Use gog_auth_add to re-aut
31597
31623
  var INVALID_GRANT_HINT = '\n\nThe stored refresh token was rejected (invalid_grant): it has expired or been revoked, so the whole account is signed out and re-authorization is required. The most common cause is the 7-day refresh-token limit Google applies to OAuth apps whose consent screen is still in "Testing" mode. Re-authorize with gog_auth_add (opens a browser) or gog_auth_add_url + gog_auth_add_complete (remote/headless). To stop this recurring, publish the OAuth consent screen to "In production" in the Google Cloud project that owns the OAuth client. Ask the user if they would like to re-authenticate.';
31598
31624
  var TRANSIENT_HINT = "\n\nThis error is often transient. Retry the same call before trying a different approach (do not fall back to smaller writes or row-by-row operations).";
31599
31625
  var GRID_LIMIT_HINT = "\n\nThe target range is outside the sheet's current grid. Add the missing rows or columns first with gog_sheets_insert (dimension: rows or cols), then retry the write.";
31626
+ var RUNNER_TRANSPORT_AUTH_HINT = "\n\nThis is the CONNECTOR's own transport auth failing, not your Google sign-in. The gog-runner backend rejected the bearer token this server sent, so the request never reached gog and no Google credential was checked \u2014 the Google account is not the problem and re-authorizing it cannot fix this. An operator must make the Worker secret GOG_RUNNER_KEY equal RUNNER_KEY on the Fly app (wrangler secret put GOG_RUNNER_KEY / fly secrets set RUNNER_KEY), then retry.";
31627
+ var RUNNER_TRANSPORT_HINTS = {
31628
+ "transport-auth": RUNNER_TRANSPORT_AUTH_HINT,
31629
+ // The request itself was malformed, so the runner will refuse it identically
31630
+ // every time. Nothing to advise beyond the message the runner already gave.
31631
+ "transport-request": "",
31632
+ "transport-retryable": TRANSIENT_HINT
31633
+ };
31600
31634
  function formatAccountList(raw) {
31601
31635
  try {
31602
31636
  const parsed = JSON.parse(raw);
@@ -31609,11 +31643,12 @@ function formatAccountList(raw) {
31609
31643
  }
31610
31644
  async function diagnose(err) {
31611
31645
  const errText = errorText(err);
31646
+ const transportHint = isRunnerTransportError(err) ? RUNNER_TRANSPORT_HINTS[err.kind] : void 0;
31612
31647
  const isInvalidGrant = INVALID_GRANT_PATTERN.test(errText);
31613
31648
  const isTransientError = !DEFINITE_AUTH_PATTERN.test(errText) && TRANSIENT_ERROR_PATTERN.test(errText);
31614
31649
  const isAuthError = !isTransientError && AUTH_ERROR_PATTERN.test(errText);
31615
31650
  const isGridLimitError = GRID_LIMIT_ERROR_PATTERN.test(errText);
31616
- const hint = isInvalidGrant ? INVALID_GRANT_HINT : isAuthError ? AUTH_HINT : isTransientError ? TRANSIENT_HINT : isGridLimitError ? GRID_LIMIT_HINT : "";
31651
+ const hint = transportHint ?? (isInvalidGrant ? INVALID_GRANT_HINT : isAuthError ? AUTH_HINT : isTransientError ? TRANSIENT_HINT : isGridLimitError ? GRID_LIMIT_HINT : "");
31617
31652
  try {
31618
31653
  const accounts = formatAccountList(await run(["auth", "list"]));
31619
31654
  return errorResult(`${errText}
@@ -31646,8 +31681,8 @@ function formatOneAccountHealth(a, now) {
31646
31681
  const age = ageInDays(a.created_at, now);
31647
31682
  const ageStr = age === null ? "" : ` Authorized ${age.toFixed(1)} day(s) ago.`;
31648
31683
  if (a.valid === false) {
31649
- const cause = INVALID_GRANT_PATTERN.test(a.error ?? "") ? 'refresh token expired or revoked \u2014 commonly the 7-day limit on OAuth consent screens still in "Testing" mode' : a.error?.trim() || "unknown error";
31650
- return `\u2717 ${email3}: NEEDS RE-AUTH \u2014 ${cause}.${ageStr} Re-authorize with gog_auth_add (browser) or gog_auth_add_url + gog_auth_add_complete (remote/headless).`;
31684
+ const cause2 = INVALID_GRANT_PATTERN.test(a.error ?? "") ? 'refresh token expired or revoked \u2014 commonly the 7-day limit on OAuth consent screens still in "Testing" mode' : a.error?.trim() || "unknown error";
31685
+ return `\u2717 ${email3}: NEEDS RE-AUTH \u2014 ${cause2}.${ageStr} Re-authorize with gog_auth_add (browser) or gog_auth_add_url + gog_auth_add_complete (remote/headless).`;
31651
31686
  }
31652
31687
  if (a.valid === true) {
31653
31688
  let line = `\u2713 ${email3}: token valid.${ageStr}`;
@@ -31689,7 +31724,7 @@ function registerAuthToolsWith(server, defaultServices) {
31689
31724
  }
31690
31725
  });
31691
31726
  server.registerTool("gog_auth_status", {
31692
- description: "Show gogcli auth configuration: keyring backend, credential files, and auth setup.",
31727
+ description: "Show gogcli auth CONFIGURATION: keyring backend, credential files, and auth setup. Despite the name this is not a health check \u2014 it reads local setup and does not contact Google, so it says nothing about whether an account can still authenticate. Use gog_auth_health for that.",
31693
31728
  annotations: { readOnlyHint: true },
31694
31729
  inputSchema: {}
31695
31730
  }, async () => {
@@ -31700,7 +31735,7 @@ function registerAuthToolsWith(server, defaultServices) {
31700
31735
  }
31701
31736
  });
31702
31737
  server.registerTool("gog_auth_health", {
31703
- description: 'Check the LIVE health of each stored Google account. Unlike gog_auth_status (which only reports keyring/config setup), this performs a real token refresh against Google, so it detects expired or revoked (invalid_grant) refresh tokens \u2014 the account-wide sign-out that blocks every service. Reports per account: whether the token is currently valid, the mapped cause when it is not, how long ago it was authorized, and a warning as it approaches the 7-day refresh-token limit that applies to OAuth apps whose consent screen is still in "Testing" mode. Run it proactively to re-authorize on your own schedule instead of mid-task.',
31738
+ description: 'Check the LIVE health of each stored Google account. Unlike gog_auth_status (which only reports keyring/config setup), this performs a real token refresh against Google, so it detects expired or revoked (invalid_grant) refresh tokens \u2014 the account-wide sign-out that blocks every service. Reports per account: whether the token is currently valid, the mapped cause when it is not, how long ago it was authorized, and a warning as it approaches the 7-day refresh-token limit that applies to OAuth apps whose consent screen is still in "Testing" mode. Run it proactively to re-authorize on your own schedule instead of mid-task. On the hosted connector this is the ONLY check that measures Google: a connector showing "connected" or "refreshed" has verified the connector key that reaches the gog machine, and nothing else \u2014 the Google credential lives on that machine and can be dead while the connection looks perfectly healthy.',
31704
31739
  annotations: { readOnlyHint: true },
31705
31740
  inputSchema: {}
31706
31741
  }, async () => {
@@ -32021,7 +32056,40 @@ var failIfNotEmptyParam = external_exports.boolean().optional().describe(
32021
32056
  );
32022
32057
 
32023
32058
  // ../gogcli-mcp/src/server.ts
32024
- var VERSION = true ? "2.21.0" : "0.0.0";
32059
+ var VERSION = true ? "2.22.0" : "0.0.0";
32060
+
32061
+ // ../gogcli-mcp/src/auth-log.ts
32062
+ var FAILURES = /* @__PURE__ */ new Set([
32063
+ "token.mint-failed",
32064
+ "grant.dead",
32065
+ "replay.failed",
32066
+ "runner.auth-failed",
32067
+ "connect.key-rejected",
32068
+ // An enrolment that could not proceed is a failure even though nobody is at
32069
+ // fault: it is the only trace a half-enrolled connector leaves behind, and
32070
+ // the absence of exactly this record is why DEFECT 4 could not be explained.
32071
+ "connect.runner-unreachable",
32072
+ "connect.google-unhealthy",
32073
+ "refusal.google-unhealthy",
32074
+ // The loudest record on this branch, and the only one that means "we cannot
32075
+ // explain this". Google refused a real call while a live check of the same
32076
+ // credential, taken seconds later, succeeded — so neither the 7-day cliff nor
32077
+ // a revoked grant accounts for it. It is filed as a failure precisely because
32078
+ // it is the record nobody may scroll past: it is the only evidence that could
32079
+ // ever justify building something on the hosted path, and its absence over
32080
+ // time is what retires that theory for good.
32081
+ "refusal.google-ok"
32082
+ ]);
32083
+ var PREFIX = "gog-auth ";
32084
+ var TAG_CHARS = 12;
32085
+ function credentialTag(cacheKeyHash) {
32086
+ return cacheKeyHash.slice(0, TAG_CHARS);
32087
+ }
32088
+ function logAuthTransition(event, context) {
32089
+ const record2 = JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), event, ...context });
32090
+ const write = FAILURES.has(event) ? console.error : console.warn;
32091
+ write(PREFIX + redactSecrets2(record2));
32092
+ }
32025
32093
 
32026
32094
  // ../gogcli-mcp/src/google-token.ts
32027
32095
  var TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token";
@@ -32048,22 +32116,73 @@ function makeAccessTokenSource(env) {
32048
32116
  );
32049
32117
  };
32050
32118
  }
32051
- return async () => {
32052
- const key = await cacheKey(refreshToken, clientId);
32053
- const hit = cache.get(key);
32054
- if (hit && hit.expiresAt - EXPIRY_MARGIN_MS > Date.now()) return hit.accessToken;
32055
- let pending = inFlight.get(key);
32119
+ let keyPromise;
32120
+ const key = () => keyPromise ??= cacheKey(refreshToken, clientId);
32121
+ const logCacheHits = parseBoolEnv("GOG_AUTH_LOG_CACHE_HITS", { env });
32122
+ const read = async () => {
32123
+ const k = await key();
32124
+ const hit = cache.get(k);
32125
+ if (hit && hit.expiresAt - EXPIRY_MARGIN_MS > Date.now()) {
32126
+ if (logCacheHits) logAuthTransition("token.cache-hit", { credential: credentialTag(k) });
32127
+ return hit.accessToken;
32128
+ }
32129
+ let pending = inFlight.get(k);
32056
32130
  if (!pending) {
32057
32131
  pending = exchange(refreshToken, clientId, clientSecret).then((minted2) => {
32058
- cache.set(key, minted2);
32132
+ cache.set(k, minted2);
32133
+ logAuthTransition("token.minted", {
32134
+ credential: credentialTag(k),
32135
+ reason: `valid for ${Math.round((minted2.expiresAt - Date.now()) / 1e3)}s`
32136
+ });
32059
32137
  return minted2;
32060
- }).finally(() => inFlight.delete(key));
32061
- inFlight.set(key, pending);
32138
+ }).catch((err) => {
32139
+ logAuthTransition(err.grantDead ? "grant.dead" : "token.mint-failed", {
32140
+ credential: credentialTag(k),
32141
+ reason: err.message
32142
+ });
32143
+ throw err;
32144
+ }).finally(() => inFlight.delete(k));
32145
+ inFlight.set(k, pending);
32062
32146
  }
32063
32147
  const minted = await pending;
32064
32148
  return minted.accessToken;
32065
32149
  };
32150
+ const invalidate = async (rejected) => {
32151
+ const k = await key();
32152
+ const hit = cache.get(k);
32153
+ if (!hit || hit.accessToken !== rejected) {
32154
+ logAuthTransition("token.evict-noop", {
32155
+ credential: credentialTag(k),
32156
+ reason: hit ? "a concurrent caller had already replaced this credential\u2019s token" : "no token was cached for this credential"
32157
+ });
32158
+ return false;
32159
+ }
32160
+ cache.delete(k);
32161
+ logAuthTransition("token.evicted", {
32162
+ credential: credentialTag(k),
32163
+ reason: "Google rejected this access token; the next read will mint a new one"
32164
+ });
32165
+ return true;
32166
+ };
32167
+ return Object.assign(read, {
32168
+ invalidate,
32169
+ credentialId: async () => credentialTag(await key())
32170
+ });
32066
32171
  }
32172
+ var TokenExchangeError = class extends Error {
32173
+ /**
32174
+ * The REFRESH token is dead (Google's `invalid_grant`), not merely the access
32175
+ * token. Carried as a flag rather than re-read from the message, because
32176
+ * inferring the author of a failure from prose several authors can produce is
32177
+ * precisely the mistake this branch exists to undo. `instanceof` is safe: the
32178
+ * class is thrown and caught inside this one module.
32179
+ */
32180
+ grantDead;
32181
+ constructor(message, grantDead) {
32182
+ super(message);
32183
+ this.grantDead = grantDead;
32184
+ }
32185
+ };
32067
32186
  async function exchange(refreshToken, clientId, clientSecret) {
32068
32187
  let res;
32069
32188
  try {
@@ -32078,79 +32197,338 @@ async function exchange(refreshToken, clientId, clientSecret) {
32078
32197
  }).toString()
32079
32198
  });
32080
32199
  } catch (err) {
32081
- throw new Error(
32082
- `the Google token exchange could not be reached: ${err instanceof Error ? err.message : String(err)}`
32200
+ throw new TokenExchangeError(
32201
+ `the Google token exchange could not be reached: ${err instanceof Error ? err.message : String(err)}`,
32202
+ false
32083
32203
  );
32084
32204
  }
32085
32205
  const body = await res.json().catch(() => ({}));
32086
32206
  if (!res.ok) {
32087
32207
  if (body.error === "invalid_grant") {
32088
- throw new Error(
32089
- 'the stored refresh token has expired or been revoked, so this account must be re-authorized (commonly the 7-day limit on OAuth consent screens still in "Testing" mode). Re-enrol with gog_auth_add_url + gog_auth_add_complete and store the new refresh token.'
32208
+ throw new TokenExchangeError(
32209
+ 'the stored refresh token was rejected (invalid_grant): it has expired or been revoked, so this account must be re-authorized (commonly the 7-day limit on OAuth consent screens still in "Testing" mode). Re-enrol with gog_auth_add_url + gog_auth_add_complete and store the new refresh token.',
32210
+ true
32090
32211
  );
32091
32212
  }
32092
- throw new Error(
32093
- `the access token could not be refreshed (HTTP ${res.status}${body.error ? `, ${body.error}` : ""})`
32213
+ throw new TokenExchangeError(
32214
+ `the access token could not be refreshed (HTTP ${res.status}${body.error ? `, ${body.error}` : ""})`,
32215
+ false
32094
32216
  );
32095
32217
  }
32096
32218
  if (!body.access_token) {
32097
- throw new Error("the access token could not be refreshed: Google returned no access_token");
32219
+ throw new TokenExchangeError(
32220
+ "the access token could not be refreshed: Google returned no access_token",
32221
+ false
32222
+ );
32098
32223
  }
32099
32224
  const expiresInMs = (body.expires_in ?? 3600) * 1e3;
32100
32225
  return { accessToken: body.access_token, expiresAt: Date.now() + expiresInMs };
32101
32226
  }
32102
32227
 
32228
+ // ../gogcli-mcp/src/google-probe.ts
32229
+ var bool = (value) => typeof value === "boolean" ? value : void 0;
32230
+ var cause = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
32231
+ function readGoogleProbe(body) {
32232
+ const record2 = typeof body === "object" && body !== null ? body : {};
32233
+ const measured = bool(record2.measured);
32234
+ const reported = cause(record2.error);
32235
+ if (measured === false) {
32236
+ return {
32237
+ kind: "unmeasured",
32238
+ reason: reported ?? "the runner reported it could not measure the Google layer"
32239
+ };
32240
+ }
32241
+ if (measured === true) {
32242
+ if (bool(record2.ok) === true) return { kind: "ok" };
32243
+ return {
32244
+ kind: "unhealthy",
32245
+ reason: reported ?? "the runner reported the Google layer unhealthy with no cause"
32246
+ };
32247
+ }
32248
+ return {
32249
+ kind: "unmeasured",
32250
+ reason: reported ? `the runner did not report whether it measured the Google layer; it said: ${reported}` : "the runner did not report whether it measured the Google layer"
32251
+ };
32252
+ }
32253
+
32103
32254
  // ../gogcli-mcp/src/connector-runtime.ts
32104
32255
  var DEFAULT_TIMEOUT_MS = 3e4;
32105
32256
  var DEADLINE_GRACE_MS = 5e3;
32257
+ var MIN_REPLAY_BUDGET_MS = 1e3;
32258
+ var REFUSAL_PROBE_TIMEOUT_MS = 4e3;
32259
+ var MIN_PROBE_BUDGET_MS = 1e3;
32260
+ var PROBE_INTERVAL_MS = 6e4;
32106
32261
  var RUNNER_GOG_FAILED = 422;
32107
32262
  var RUNNER_DRAINING = 503;
32263
+ var RUNNER_BAD_REQUEST = 400;
32264
+ var RUNNER_BAD_KEY = 401;
32265
+ var GogFailedError = class extends Error {
32266
+ /** gog's stderr alone, with no echoed argv mixed in. */
32267
+ stderr;
32268
+ constructor(message, stderr) {
32269
+ super(message);
32270
+ this.stderr = stderr;
32271
+ }
32272
+ };
32273
+ var GOOGLE_TOKEN_REJECTED_PATTERN = /Google API error \(401\b|invalid[ _]authentication[ _]credentials|\bACCESS_TOKEN_EXPIRED\b|\binvalid_token\b/i;
32274
+ var REFRESH_TOKEN_DEAD_PATTERN = /\binvalid_grant\b/i;
32275
+ var READ_ONLY_SUBCOMMANDS = /* @__PURE__ */ new Set([
32276
+ "cat",
32277
+ "describe",
32278
+ "get",
32279
+ "info",
32280
+ "list",
32281
+ "list-slides",
32282
+ "ls",
32283
+ "metadata",
32284
+ "read-slide",
32285
+ "search",
32286
+ "services",
32287
+ "status",
32288
+ "structure"
32289
+ ]);
32290
+ function gogTarget(args) {
32291
+ const words = args.filter((arg) => typeof arg === "string");
32292
+ let service;
32293
+ for (let i = 0; i < words.length; i += 1) {
32294
+ const word = words[i];
32295
+ if (word.startsWith("-")) {
32296
+ if (word === "--account") i += 1;
32297
+ continue;
32298
+ }
32299
+ if (service === void 0) {
32300
+ service = word;
32301
+ continue;
32302
+ }
32303
+ return { service, subcommand: word };
32304
+ }
32305
+ return { service };
32306
+ }
32307
+ async function remintAfterGoogleRejection(err, used, args, readAccessToken, deadlineAt, probeGoogle) {
32308
+ if (!(err instanceof GogFailedError)) return void 0;
32309
+ const grantDead = REFRESH_TOKEN_DEAD_PATTERN.test(err.stderr);
32310
+ if (!grantDead && !GOOGLE_TOKEN_REJECTED_PATTERN.test(err.stderr)) return void 0;
32311
+ const { service, subcommand } = gogTarget(args);
32312
+ const credential = await readAccessToken?.credentialId?.();
32313
+ const where = { credential, service };
32314
+ if (grantDead) {
32315
+ logAuthTransition("grant.dead", {
32316
+ ...where,
32317
+ reason: "gog reported invalid_grant: the stored refresh token is dead, so no token can be minted and this account must be re-authorized"
32318
+ });
32319
+ return void 0;
32320
+ }
32321
+ if (!used) {
32322
+ await probeGoogle(where);
32323
+ logAuthTransition("replay.declined", {
32324
+ ...where,
32325
+ reason: "no access token was supplied with the call, so gog acted as the backend volume\u2019s own identity"
32326
+ });
32327
+ return void 0;
32328
+ }
32329
+ if (!readAccessToken?.invalidate) {
32330
+ logAuthTransition("replay.declined", {
32331
+ ...where,
32332
+ reason: "this token source cannot mint a replacement, so a replay would resend the rejected token"
32333
+ });
32334
+ return void 0;
32335
+ }
32336
+ const evicted = await readAccessToken.invalidate(used);
32337
+ if (subcommand === void 0 || !READ_ONLY_SUBCOMMANDS.has(subcommand)) {
32338
+ logAuthTransition("replay.declined", {
32339
+ ...where,
32340
+ reason: `not replayable: '${subcommand ?? "(none)"}' is not a known read-only subcommand and a write could double-apply`
32341
+ });
32342
+ return void 0;
32343
+ }
32344
+ if (!evicted) {
32345
+ logAuthTransition("replay.declined", {
32346
+ ...where,
32347
+ reason: "the rejected token was already superseded, so the cache holds the token a replay would send"
32348
+ });
32349
+ return void 0;
32350
+ }
32351
+ const fresh = await readAccessToken();
32352
+ if (!fresh) {
32353
+ logAuthTransition("replay.declined", {
32354
+ ...where,
32355
+ reason: "the token source produced no token after eviction; replaying without one would act as the backend"
32356
+ });
32357
+ return void 0;
32358
+ }
32359
+ const budgetMs = deadlineAt - Date.now();
32360
+ if (budgetMs < MIN_REPLAY_BUDGET_MS) {
32361
+ logAuthTransition("replay.declined", {
32362
+ ...where,
32363
+ reason: `only ${budgetMs}ms of the call\u2019s deadline remained, so a replay could only time out; the rejected token was evicted, so the next call mints a fresh one`
32364
+ });
32365
+ return void 0;
32366
+ }
32367
+ return { token: fresh, budgetMs, invalidate: readAccessToken.invalidate, ...where };
32368
+ }
32108
32369
  function makeFlyExecutor(endpoint, key, readAccessToken) {
32370
+ let lastProbeAt = Number.NEGATIVE_INFINITY;
32371
+ const probeGoogleAfterRefusal = async (where, deadlineAt) => {
32372
+ const record2 = { ...where, endpoint };
32373
+ const now = Date.now();
32374
+ const remainingMs = deadlineAt - now;
32375
+ if (remainingMs < MIN_PROBE_BUDGET_MS) {
32376
+ logAuthTransition("refusal.google-unmeasured", {
32377
+ ...record2,
32378
+ reason: `only ${remainingMs}ms of the call\u2019s deadline remained, so the Google layer was not measured rather than delay the caller\u2019s own error`
32379
+ });
32380
+ return;
32381
+ }
32382
+ if (now - lastProbeAt < PROBE_INTERVAL_MS) {
32383
+ logAuthTransition("refusal.google-unmeasured", {
32384
+ ...record2,
32385
+ // "attempted", not "measured". `lastProbeAt` is stamped before the
32386
+ // fetch and is deliberately NOT reset when the probe comes back with no
32387
+ // verdict (a 404 from a runner too old to have the endpoint, a timeout,
32388
+ // a dead socket) — the backend cost this throttle exists to bound was
32389
+ // paid either way, and resetting it would let a retry loop storm a
32390
+ // runner that is already unwell. So the timestamp stays and the sentence
32391
+ // has to be the true one: on this branch a log line may not assert a
32392
+ // measurement that never happened, and the previous probe may well have
32393
+ // measured nothing at all.
32394
+ reason: "a Google probe was attempted recently, so another was not sent: this probe spawns gog on the backend and takes the keyring\u2019s exclusive lock"
32395
+ });
32396
+ return;
32397
+ }
32398
+ lastProbeAt = now;
32399
+ let event;
32400
+ let reason;
32401
+ try {
32402
+ const res = await fetch(`${endpoint}/health/google`, {
32403
+ headers: { Authorization: `Bearer ${key}` },
32404
+ // Never more than the probe's own budget, never more than the call has
32405
+ // left. `Math.min` rather than a plain constant because the second
32406
+ // bound is the caller's, and it outranks ours.
32407
+ signal: AbortSignal.timeout(Math.min(REFUSAL_PROBE_TIMEOUT_MS, remainingMs))
32408
+ });
32409
+ if (!res.ok) {
32410
+ event = "refusal.google-unmeasured";
32411
+ reason = `the runner did not answer the Google probe (HTTP ${res.status})`;
32412
+ } else {
32413
+ const verdict = readGoogleProbe(await res.json());
32414
+ if (verdict.kind === "ok") {
32415
+ event = "refusal.google-ok";
32416
+ reason = "Google refused this call, yet a live token check on the same volume succeeded \u2014 so a dead or expired refresh token does not explain this refusal";
32417
+ } else {
32418
+ event = verdict.kind === "unhealthy" ? "refusal.google-unhealthy" : "refusal.google-unmeasured";
32419
+ reason = verdict.reason;
32420
+ }
32421
+ }
32422
+ } catch (err) {
32423
+ event = "refusal.google-unmeasured";
32424
+ reason = err instanceof Error ? err.message : String(err);
32425
+ }
32426
+ logAuthTransition(event, { ...record2, reason });
32427
+ };
32109
32428
  return async (args, opts) => {
32110
32429
  const deadlineMs = (opts?.timeout ?? DEFAULT_TIMEOUT_MS) + DEADLINE_GRACE_MS;
32111
32430
  const accessToken = await readAccessToken?.();
32112
- let res;
32431
+ const deadlineAt = Date.now() + deadlineMs;
32113
32432
  try {
32114
- res = await fetch(endpoint + "/run", {
32115
- method: "POST",
32116
- headers: {
32117
- Authorization: "Bearer " + key,
32118
- "Content-Type": "application/json"
32119
- },
32120
- body: JSON.stringify(accessToken ? { args, accessToken } : { args }),
32121
- signal: AbortSignal.timeout(deadlineMs)
32122
- });
32433
+ return await attempt(endpoint, key, args, accessToken, deadlineMs);
32123
32434
  } catch (err) {
32124
- const name = err instanceof Error ? err.name : "";
32125
- if (name === "TimeoutError" || name === "AbortError") {
32126
- throw new Error(
32127
- `gog-runner did not respond within ${deadlineMs}ms (${endpoint}) \u2014 the Fly backend may be cold or wedged`
32128
- );
32435
+ const replay = await remintAfterGoogleRejection(
32436
+ err,
32437
+ accessToken,
32438
+ args,
32439
+ readAccessToken,
32440
+ deadlineAt,
32441
+ (where2) => probeGoogleAfterRefusal(where2, deadlineAt)
32442
+ );
32443
+ if (replay === void 0) throw err;
32444
+ const where = { credential: replay.credential, service: replay.service, endpoint };
32445
+ logAuthTransition("replay.attempted", {
32446
+ ...where,
32447
+ reason: "Google rejected the access token; replaying this read once with a freshly minted one"
32448
+ });
32449
+ try {
32450
+ const stdout = await attempt(endpoint, key, args, replay.token, replay.budgetMs);
32451
+ logAuthTransition("replay.succeeded", where);
32452
+ return stdout;
32453
+ } catch (replayErr) {
32454
+ logAuthTransition("replay.failed", { ...where, reason: String(replayErr) });
32455
+ if (replayErr instanceof GogFailedError && GOOGLE_TOKEN_REJECTED_PATTERN.test(replayErr.stderr)) {
32456
+ await replay.invalidate(replay.token);
32457
+ }
32458
+ throw replayErr;
32129
32459
  }
32130
- throw err;
32131
32460
  }
32132
- if (!res.ok) {
32133
- const body = await res.json().catch(() => null);
32134
- const detail = body && typeof body.error === "string" ? body.stderr && body.stderr.trim() && body.stderr.trim() !== body.error.trim() ? `${body.error}
32461
+ };
32462
+ }
32463
+ async function attempt(endpoint, key, args, accessToken, deadlineMs) {
32464
+ let res;
32465
+ try {
32466
+ res = await fetch(endpoint + "/run", {
32467
+ method: "POST",
32468
+ headers: {
32469
+ Authorization: "Bearer " + key,
32470
+ "Content-Type": "application/json"
32471
+ },
32472
+ body: JSON.stringify(accessToken ? { args, accessToken } : { args }),
32473
+ signal: AbortSignal.timeout(deadlineMs)
32474
+ });
32475
+ } catch (err) {
32476
+ const name = err instanceof Error ? err.name : "";
32477
+ if (name === "TimeoutError" || name === "AbortError") {
32478
+ throw new RunnerTransportError(
32479
+ `gog-runner did not respond within ${deadlineMs}ms (${endpoint}) \u2014 the Fly backend may be cold or wedged`,
32480
+ "transport-retryable"
32481
+ );
32482
+ }
32483
+ throw err;
32484
+ }
32485
+ if (!res.ok) {
32486
+ const body = await res.json().catch(() => null);
32487
+ const detail = body && typeof body.error === "string" ? body.stderr && body.stderr.trim() && body.stderr.trim() !== body.error.trim() ? `${body.error}
32135
32488
  ${body.stderr}` : body.error : "";
32136
- if (res.status === RUNNER_GOG_FAILED) {
32137
- throw new Error(detail || "gog failed on the runner (no detail supplied)");
32138
- }
32139
- if (res.status === RUNNER_DRAINING || body?.retryable === true) {
32140
- throw new Error(
32141
- `gog-runner is restarting; retry this call.${detail ? ` ${detail}` : ""}`
32142
- );
32143
- }
32144
- if (detail) {
32145
- throw new Error(detail);
32146
- }
32147
- throw new Error(
32148
- `gog-runner HTTP ${res.status}: the response did not come from the runner, so the request never reached gog. The backend Machine was most likely starting or shutting down \u2014 this is transient, retry the same call.`
32489
+ if (res.status === RUNNER_GOG_FAILED) {
32490
+ throw new GogFailedError(
32491
+ detail || "gog failed on the runner (no detail supplied)",
32492
+ typeof body?.stderr === "string" ? body.stderr : ""
32149
32493
  );
32150
32494
  }
32151
- const { stdout } = await res.json();
32152
- return stdout;
32153
- };
32495
+ if (res.status === RUNNER_BAD_KEY) {
32496
+ logAuthTransition("runner.auth-failed", {
32497
+ service: gogTarget(args).service,
32498
+ endpoint,
32499
+ reason: "the gog-runner rejected the connector\u2019s bearer token, so gog never ran and no Google credential was read; GOG_RUNNER_KEY does not match the Fly app\u2019s RUNNER_KEY"
32500
+ });
32501
+ throw new RunnerTransportError(
32502
+ "gog-runner rejected the connector's bearer token, so the request never reached gog and no Google credential was involved. The Worker secret GOG_RUNNER_KEY no longer matches RUNNER_KEY on the Fly app; set them to the same value (wrangler secret put GOG_RUNNER_KEY / fly secrets set RUNNER_KEY) and retry.",
32503
+ "transport-auth",
32504
+ res.status
32505
+ );
32506
+ }
32507
+ if (res.status === RUNNER_BAD_REQUEST) {
32508
+ throw new RunnerTransportError(
32509
+ detail || "gog-runner rejected the request (no detail supplied)",
32510
+ "transport-request",
32511
+ res.status
32512
+ );
32513
+ }
32514
+ if (res.status === RUNNER_DRAINING || body?.retryable === true) {
32515
+ throw new RunnerTransportError(
32516
+ `gog-runner is restarting; retry this call.${detail ? ` ${detail}` : ""}`,
32517
+ "transport-retryable",
32518
+ res.status
32519
+ );
32520
+ }
32521
+ if (detail) {
32522
+ throw new Error(detail);
32523
+ }
32524
+ throw new RunnerTransportError(
32525
+ `gog-runner HTTP ${res.status}: the response did not come from the runner, so the request never reached gog. The backend Machine was most likely starting or shutting down \u2014 this is transient, retry the same call.`,
32526
+ "transport-retryable",
32527
+ res.status
32528
+ );
32529
+ }
32530
+ const { stdout } = await res.json();
32531
+ return stdout;
32154
32532
  }
32155
32533
 
32156
32534
  // ../gogcli-mcp/src/remote-runner.ts
@@ -32184,24 +32562,31 @@ function registerExtraDriveTools(server) {
32184
32562
  return runOrDiagnose(args, { account });
32185
32563
  });
32186
32564
  server.registerTool("gog_drive_upload", {
32187
- description: "Upload a local file to Drive. Use --replace to replace the content of an existing file (preserves link/permissions), or --convert to auto-convert to a Google format.",
32565
+ description: 'Upload a local file to Drive. Use replace to replace the content of an existing file (preserves link/permissions), or convert to auto-convert to a Google format. Pair replace with ifVersion to make the overwrite conditional: gog sends an atomic If-Match precondition and reports a conflict \u2014 applying nothing \u2014 if the file changed since you read it, instead of silently clobbering a concurrent edit. No read tool surfaces the version number: fetch it immediately before uploading with gog_drive_run { subcommand: "raw", args: ["<fileId>", "--fields=version"] } \u2014 it comes back as a JSON string, so pass it on as a number. Conditional replacement refuses Google Workspace files (Docs/Sheets/Slides), which have no replaceable binary content.',
32188
32566
  annotations: { destructiveHint: true },
32189
32567
  inputSchema: {
32190
32568
  localPath: external_exports.string().describe("Path to the local file to upload"),
32191
32569
  name: external_exports.string().optional().describe("Override filename (create) or rename target (replace)"),
32192
32570
  parent: external_exports.string().optional().describe("Destination folder ID (create only)"),
32193
- replace: external_exports.string().optional().describe("Replace content of an existing Drive file ID (preserves link/permissions)"),
32571
+ replace: external_exports.string().optional().describe("Replace content of an existing Drive file ID (preserves link/permissions). Unconditional unless ifVersion is set."),
32572
+ ifVersion: external_exports.number().int().positive().optional().describe(
32573
+ 'Replace only if the Drive file is still at this version (requires replace). On mismatch nothing is written and gog reports a conflict \u2014 re-read the file and reapply your edit. Read the current version with gog_drive_run { subcommand: "raw", args: ["<fileId>", "--fields=version"] } \u2014 which answers {"version":"35"}, a JSON STRING (the Drive API serializes its int64 fields as strings). Convert it to a number before passing it here, or this param rejects it.'
32574
+ ),
32194
32575
  mimeType: external_exports.string().optional().describe("Override MIME type inference"),
32195
32576
  keepRevisionForever: external_exports.boolean().optional().describe("Keep the new head revision forever (binary files only)"),
32196
32577
  convert: external_exports.boolean().optional().describe("Auto-convert to native Google format based on file extension (create only)"),
32197
32578
  convertTo: external_exports.string().optional().describe("Convert to a specific Google format: doc | sheet | slides (create only)"),
32198
32579
  account: accountParam
32199
32580
  }
32200
- }, async ({ localPath, name, parent, replace, mimeType, keepRevisionForever, convert, convertTo, account }) => {
32581
+ }, async ({ localPath, name, parent, replace, ifVersion, mimeType, keepRevisionForever, convert, convertTo, account }) => {
32582
+ if (ifVersion !== void 0 && !replace) {
32583
+ throw new Error("ifVersion requires replace: a version precondition only applies when replacing an existing Drive file.");
32584
+ }
32201
32585
  const args = ["drive", "upload", localPath];
32202
32586
  if (name) args.push(`--name=${name}`);
32203
32587
  if (parent) args.push(`--parent=${parent}`);
32204
32588
  if (replace) args.push(`--replace=${replace}`);
32589
+ if (ifVersion !== void 0) args.push(`--if-version=${ifVersion}`);
32205
32590
  if (mimeType) args.push(`--mime-type=${mimeType}`);
32206
32591
  if (keepRevisionForever) args.push("--keep-revision-forever");
32207
32592
  if (convert) args.push("--convert");
package/manifest.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "manifest_version": "0.3",
4
4
  "name": "gogcli-mcp-drive",
5
5
  "display_name": "gogcli (Drive)",
6
- "version": "2.21.0",
6
+ "version": "2.22.0",
7
7
  "description": "Extended Google Drive for Claude via gogcli — auth + full Drive support (upload, download, permissions, comments, shared drives)",
8
8
  "author": {
9
9
  "name": "Chris Hall",
@@ -139,7 +139,7 @@
139
139
  },
140
140
  {
141
141
  "name": "gog_drive_upload",
142
- "description": "Upload a local file, optionally replacing an existing file or converting to Google format"
142
+ "description": "Upload a local file, optionally replacing an existing file (unconditionally, or only at a given version) or converting to Google format"
143
143
  },
144
144
  {
145
145
  "name": "gog_drive_sync_push",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gogcli-mcp-drive",
3
- "version": "2.21.0",
3
+ "version": "2.22.0",
4
4
  "mcpName": "io.github.chrischall/gogcli-mcp-drive",
5
5
  "description": "Extended Google Drive MCP server via gogcli — auth + full Drive support (upload/download/permissions/comments/shared drives)",
6
6
  "author": "Claude Code (AI) <https://www.anthropic.com/claude>",
package/server.json CHANGED
@@ -7,12 +7,12 @@
7
7
  "source": "github",
8
8
  "subfolder": "packages/gogcli-mcp-drive"
9
9
  },
10
- "version": "2.21.0",
10
+ "version": "2.22.0",
11
11
  "packages": [
12
12
  {
13
13
  "registryType": "npm",
14
14
  "identifier": "gogcli-mcp-drive",
15
- "version": "2.21.0",
15
+ "version": "2.22.0",
16
16
  "transport": {
17
17
  "type": "stdio"
18
18
  },
@@ -22,24 +22,40 @@ export function registerExtraDriveTools(server: McpServer): void {
22
22
  });
23
23
 
24
24
  server.registerTool('gog_drive_upload', {
25
- description: 'Upload a local file to Drive. Use --replace to replace the content of an existing file (preserves link/permissions), or --convert to auto-convert to a Google format.',
25
+ description:
26
+ 'Upload a local file to Drive. Use replace to replace the content of an existing file (preserves link/permissions), ' +
27
+ 'or convert to auto-convert to a Google format. ' +
28
+ 'Pair replace with ifVersion to make the overwrite conditional: gog sends an atomic If-Match precondition and reports ' +
29
+ 'a conflict — applying nothing — if the file changed since you read it, instead of silently clobbering a concurrent edit. ' +
30
+ 'No read tool surfaces the version number: fetch it immediately before uploading with ' +
31
+ 'gog_drive_run { subcommand: "raw", args: ["<fileId>", "--fields=version"] } — it comes back as a JSON string, so pass it on as a number. ' +
32
+ 'Conditional replacement refuses Google Workspace files (Docs/Sheets/Slides), which have no replaceable binary content.',
26
33
  annotations: { destructiveHint: true },
27
34
  inputSchema: {
28
35
  localPath: z.string().describe('Path to the local file to upload'),
29
36
  name: z.string().optional().describe('Override filename (create) or rename target (replace)'),
30
37
  parent: z.string().optional().describe('Destination folder ID (create only)'),
31
- replace: z.string().optional().describe('Replace content of an existing Drive file ID (preserves link/permissions)'),
38
+ replace: z.string().optional().describe('Replace content of an existing Drive file ID (preserves link/permissions). Unconditional unless ifVersion is set.'),
39
+ ifVersion: z.number().int().positive().optional().describe(
40
+ 'Replace only if the Drive file is still at this version (requires replace). On mismatch nothing is written and gog reports a conflict — re-read the file and reapply your edit. ' +
41
+ 'Read the current version with gog_drive_run { subcommand: "raw", args: ["<fileId>", "--fields=version"] } — which answers {"version":"35"}, '
42
+ + 'a JSON STRING (the Drive API serializes its int64 fields as strings). Convert it to a number before passing it here, or this param rejects it.',
43
+ ),
32
44
  mimeType: z.string().optional().describe('Override MIME type inference'),
33
45
  keepRevisionForever: z.boolean().optional().describe('Keep the new head revision forever (binary files only)'),
34
46
  convert: z.boolean().optional().describe('Auto-convert to native Google format based on file extension (create only)'),
35
47
  convertTo: z.string().optional().describe('Convert to a specific Google format: doc | sheet | slides (create only)'),
36
48
  account: accountParam,
37
49
  },
38
- }, async ({ localPath, name, parent, replace, mimeType, keepRevisionForever, convert, convertTo, account }) => {
50
+ }, async ({ localPath, name, parent, replace, ifVersion, mimeType, keepRevisionForever, convert, convertTo, account }) => {
51
+ if (ifVersion !== undefined && !replace) {
52
+ throw new Error('ifVersion requires replace: a version precondition only applies when replacing an existing Drive file.');
53
+ }
39
54
  const args = ['drive', 'upload', localPath];
40
55
  if (name) args.push(`--name=${name}`);
41
56
  if (parent) args.push(`--parent=${parent}`);
42
57
  if (replace) args.push(`--replace=${replace}`);
58
+ if (ifVersion !== undefined) args.push(`--if-version=${ifVersion}`);
43
59
  if (mimeType) args.push(`--mime-type=${mimeType}`);
44
60
  if (keepRevisionForever) args.push('--keep-revision-forever');
45
61
  if (convert) args.push('--convert');
@@ -79,6 +79,50 @@ describe('gog_drive_upload', () => {
79
79
  await harness.callTool('gog_drive_upload', { localPath: '/tmp/x.txt', keepRevisionForever: false, convert: false });
80
80
  expect(lib.runOrDiagnose).toHaveBeenCalledWith(['drive', 'upload', '/tmp/x.txt'], { account: undefined });
81
81
  });
82
+
83
+ // gog 0.35.0 (openclaw/gogcli 1b26124) adds --if-version: an atomic
84
+ // If-Match precondition on --replace that turns a blind overwrite into a
85
+ // compare-and-swap.
86
+ it('passes --if-version alongside --replace for conditional replacement', async () => {
87
+ await harness.callTool('gog_drive_upload', { localPath: '/tmp/x.txt', replace: 'file2', ifVersion: 7 });
88
+ expect(lib.runOrDiagnose).toHaveBeenCalledWith(
89
+ ['drive', 'upload', '/tmp/x.txt', '--replace=file2', '--if-version=7'],
90
+ { account: undefined },
91
+ );
92
+ });
93
+
94
+ it('rejects ifVersion without replace instead of spending a gog call', async () => {
95
+ const result = await harness.callTool('gog_drive_upload', { localPath: '/tmp/x.txt', ifVersion: 7 });
96
+ expect(result.isError).toBe(true);
97
+ expect(result.content[0].text).toMatch(/ifVersion requires replace/);
98
+ expect(lib.runOrDiagnose).not.toHaveBeenCalled();
99
+ });
100
+
101
+ it('rejects a non-positive ifVersion before it reaches gog', async () => {
102
+ const result = await harness.callTool('gog_drive_upload', { localPath: '/tmp/x.txt', replace: 'file2', ifVersion: 0 });
103
+ expect(result.isError).toBe(true);
104
+ expect(lib.runOrDiagnose).not.toHaveBeenCalled();
105
+ });
106
+
107
+ // No gog read command surfaces the Drive `version` int: driveFileGetFields
108
+ // and info_via_drive.go both omit it, and `drive upload` itself is the only
109
+ // caller that requests it. `drive raw` (fields=*) is the sole way to read it,
110
+ // and it is reachable only through the gog_drive_run escape hatch — so the
111
+ // description has to say so or the flag is unusable.
112
+ it('description explains how to obtain the current version', async () => {
113
+ const { McpServer } = await import('@modelcontextprotocol/sdk/server/mcp.js');
114
+ const server = new McpServer({ name: 'test', version: '0.0.0' });
115
+ const configs = new Map<string, { description?: string }>();
116
+ vi.spyOn(server, 'registerTool').mockImplementation((name, config) => {
117
+ configs.set(name, config as { description?: string });
118
+ return undefined as never;
119
+ });
120
+ registerExtraDriveTools(server);
121
+ const desc = configs.get('gog_drive_upload')?.description ?? '';
122
+ expect(desc).toMatch(/gog_drive_run/);
123
+ expect(desc).toMatch(/raw/);
124
+ expect(desc).toMatch(/--fields=version/);
125
+ });
82
126
  });
83
127
 
84
128
  describe('gog_drive_sync_push', () => {
@@ -656,3 +700,24 @@ describe('gog_drive_shortcut_create', () => {
656
700
  );
657
701
  });
658
702
  });
703
+
704
+ // `drive raw <id> --fields=version` returns {"version":"35"} — the Drive v3
705
+ // `version` field is an int64, which Google's JSON encoding serializes as a
706
+ // STRING. ifVersion is z.number().int().positive(), so a model that pastes the
707
+ // value straight back through gets a zod validation error instead of a
708
+ // conditional replace. The description has to say to convert it.
709
+ describe('gog_drive_upload ifVersion description', () => {
710
+ it('warns that the version reads back as a JSON string', async () => {
711
+ const { McpServer } = await import('@modelcontextprotocol/sdk/server/mcp.js');
712
+ const server = new McpServer({ name: 'test', version: '0.0.0' });
713
+ const schemas = new Map<string, Record<string, { description?: string }>>();
714
+ vi.spyOn(server, 'registerTool').mockImplementation((name, config) => {
715
+ schemas.set(name, (config as { inputSchema: Record<string, { description?: string }> }).inputSchema);
716
+ return undefined as never;
717
+ });
718
+ registerExtraDriveTools(server);
719
+ const desc = schemas.get('gog_drive_upload')?.ifVersion?.description ?? '';
720
+ expect(desc).toMatch(/string/i);
721
+ expect(desc).toMatch(/number/i);
722
+ });
723
+ });