gogcli-mcp-drive 2.21.1 → 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.1"
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.1",
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.1",
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
@@ -31440,6 +31440,13 @@ var TIMESTAMP_KEYS = /* @__PURE__ */ new Set([
31440
31440
  // Calendar event start/end
31441
31441
  "internalDate",
31442
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",
31443
31450
  "modifiedTime",
31444
31451
  // Drive
31445
31452
  "createdTime",
@@ -31674,8 +31681,8 @@ function formatOneAccountHealth(a, now) {
31674
31681
  const age = ageInDays(a.created_at, now);
31675
31682
  const ageStr = age === null ? "" : ` Authorized ${age.toFixed(1)} day(s) ago.`;
31676
31683
  if (a.valid === false) {
31677
- 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";
31678
- 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).`;
31679
31686
  }
31680
31687
  if (a.valid === true) {
31681
31688
  let line = `\u2713 ${email3}: token valid.${ageStr}`;
@@ -31717,7 +31724,7 @@ function registerAuthToolsWith(server, defaultServices) {
31717
31724
  }
31718
31725
  });
31719
31726
  server.registerTool("gog_auth_status", {
31720
- 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.",
31721
31728
  annotations: { readOnlyHint: true },
31722
31729
  inputSchema: {}
31723
31730
  }, async () => {
@@ -31728,7 +31735,7 @@ function registerAuthToolsWith(server, defaultServices) {
31728
31735
  }
31729
31736
  });
31730
31737
  server.registerTool("gog_auth_health", {
31731
- 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.',
31732
31739
  annotations: { readOnlyHint: true },
31733
31740
  inputSchema: {}
31734
31741
  }, async () => {
@@ -32049,14 +32056,29 @@ var failIfNotEmptyParam = external_exports.boolean().optional().describe(
32049
32056
  );
32050
32057
 
32051
32058
  // ../gogcli-mcp/src/server.ts
32052
- var VERSION = true ? "2.21.1" : "0.0.0";
32059
+ var VERSION = true ? "2.22.0" : "0.0.0";
32053
32060
 
32054
32061
  // ../gogcli-mcp/src/auth-log.ts
32055
32062
  var FAILURES = /* @__PURE__ */ new Set([
32056
32063
  "token.mint-failed",
32057
32064
  "grant.dead",
32058
32065
  "replay.failed",
32059
- "runner.auth-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"
32060
32082
  ]);
32061
32083
  var PREFIX = "gog-auth ";
32062
32084
  var TAG_CHARS = 12;
@@ -32203,10 +32225,39 @@ async function exchange(refreshToken, clientId, clientSecret) {
32203
32225
  return { accessToken: body.access_token, expiresAt: Date.now() + expiresInMs };
32204
32226
  }
32205
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
+
32206
32254
  // ../gogcli-mcp/src/connector-runtime.ts
32207
32255
  var DEFAULT_TIMEOUT_MS = 3e4;
32208
32256
  var DEADLINE_GRACE_MS = 5e3;
32209
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;
32210
32261
  var RUNNER_GOG_FAILED = 422;
32211
32262
  var RUNNER_DRAINING = 503;
32212
32263
  var RUNNER_BAD_REQUEST = 400;
@@ -32253,7 +32304,7 @@ function gogTarget(args) {
32253
32304
  }
32254
32305
  return { service };
32255
32306
  }
32256
- async function remintAfterGoogleRejection(err, used, args, readAccessToken, deadlineAt) {
32307
+ async function remintAfterGoogleRejection(err, used, args, readAccessToken, deadlineAt, probeGoogle) {
32257
32308
  if (!(err instanceof GogFailedError)) return void 0;
32258
32309
  const grantDead = REFRESH_TOKEN_DEAD_PATTERN.test(err.stderr);
32259
32310
  if (!grantDead && !GOOGLE_TOKEN_REJECTED_PATTERN.test(err.stderr)) return void 0;
@@ -32268,6 +32319,7 @@ async function remintAfterGoogleRejection(err, used, args, readAccessToken, dead
32268
32319
  return void 0;
32269
32320
  }
32270
32321
  if (!used) {
32322
+ await probeGoogle(where);
32271
32323
  logAuthTransition("replay.declined", {
32272
32324
  ...where,
32273
32325
  reason: "no access token was supplied with the call, so gog acted as the backend volume\u2019s own identity"
@@ -32315,6 +32367,64 @@ async function remintAfterGoogleRejection(err, used, args, readAccessToken, dead
32315
32367
  return { token: fresh, budgetMs, invalidate: readAccessToken.invalidate, ...where };
32316
32368
  }
32317
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
+ };
32318
32428
  return async (args, opts) => {
32319
32429
  const deadlineMs = (opts?.timeout ?? DEFAULT_TIMEOUT_MS) + DEADLINE_GRACE_MS;
32320
32430
  const accessToken = await readAccessToken?.();
@@ -32327,7 +32437,8 @@ function makeFlyExecutor(endpoint, key, readAccessToken) {
32327
32437
  accessToken,
32328
32438
  args,
32329
32439
  readAccessToken,
32330
- deadlineAt
32440
+ deadlineAt,
32441
+ (where2) => probeGoogleAfterRefusal(where2, deadlineAt)
32331
32442
  );
32332
32443
  if (replay === void 0) throw err;
32333
32444
  const where = { credential: replay.credential, service: replay.service, endpoint };
@@ -32451,24 +32562,31 @@ function registerExtraDriveTools(server) {
32451
32562
  return runOrDiagnose(args, { account });
32452
32563
  });
32453
32564
  server.registerTool("gog_drive_upload", {
32454
- 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.',
32455
32566
  annotations: { destructiveHint: true },
32456
32567
  inputSchema: {
32457
32568
  localPath: external_exports.string().describe("Path to the local file to upload"),
32458
32569
  name: external_exports.string().optional().describe("Override filename (create) or rename target (replace)"),
32459
32570
  parent: external_exports.string().optional().describe("Destination folder ID (create only)"),
32460
- 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
+ ),
32461
32575
  mimeType: external_exports.string().optional().describe("Override MIME type inference"),
32462
32576
  keepRevisionForever: external_exports.boolean().optional().describe("Keep the new head revision forever (binary files only)"),
32463
32577
  convert: external_exports.boolean().optional().describe("Auto-convert to native Google format based on file extension (create only)"),
32464
32578
  convertTo: external_exports.string().optional().describe("Convert to a specific Google format: doc | sheet | slides (create only)"),
32465
32579
  account: accountParam
32466
32580
  }
32467
- }, 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
+ }
32468
32585
  const args = ["drive", "upload", localPath];
32469
32586
  if (name) args.push(`--name=${name}`);
32470
32587
  if (parent) args.push(`--parent=${parent}`);
32471
32588
  if (replace) args.push(`--replace=${replace}`);
32589
+ if (ifVersion !== void 0) args.push(`--if-version=${ifVersion}`);
32472
32590
  if (mimeType) args.push(`--mime-type=${mimeType}`);
32473
32591
  if (keepRevisionForever) args.push("--keep-revision-forever");
32474
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.1",
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.1",
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.1",
10
+ "version": "2.22.0",
11
11
  "packages": [
12
12
  {
13
13
  "registryType": "npm",
14
14
  "identifier": "gogcli-mcp-drive",
15
- "version": "2.21.1",
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
+ });