gogcli-mcp-gmail 2.20.0 → 2.21.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/dist/index.js CHANGED
@@ -4264,8 +4264,8 @@ var require_core = __commonJS({
4264
4264
  return this;
4265
4265
  }
4266
4266
  case "object": {
4267
- const cacheKey = schemaKeyRef;
4268
- this._cache.delete(cacheKey);
4267
+ const cacheKey2 = schemaKeyRef;
4268
+ this._cache.delete(cacheKey2);
4269
4269
  let id = schemaKeyRef[this.opts.schemaId];
4270
4270
  if (id) {
4271
4271
  id = (0, resolve_1.normalizeId)(id);
@@ -23068,17 +23068,33 @@ function normalizeObjectSchema(schema) {
23068
23068
  }
23069
23069
  return void 0;
23070
23070
  }
23071
+ function getDotPath(path) {
23072
+ if (path.length === 0) {
23073
+ return "object root";
23074
+ }
23075
+ return path.reduce((acc, seg, index) => {
23076
+ if (index === 0) {
23077
+ return String(seg);
23078
+ }
23079
+ if (typeof seg === "number") {
23080
+ return `${acc}[${seg}]`;
23081
+ }
23082
+ return `${acc}.${seg}`;
23083
+ }, "");
23084
+ }
23071
23085
  function getParseErrorMessage(error51) {
23072
23086
  if (error51 && typeof error51 === "object") {
23087
+ if ("issues" in error51 && Array.isArray(error51.issues) && error51.issues.length > 0) {
23088
+ return error51.issues.map((i) => {
23089
+ if (!i.path?.length) {
23090
+ return i.message;
23091
+ }
23092
+ return `${i.message} at ${getDotPath(i.path)}`;
23093
+ }).join("\n");
23094
+ }
23073
23095
  if ("message" in error51 && typeof error51.message === "string") {
23074
23096
  return error51.message;
23075
23097
  }
23076
- if ("issues" in error51 && Array.isArray(error51.issues) && error51.issues.length > 0) {
23077
- const firstIssue = error51.issues[0];
23078
- if (firstIssue && typeof firstIssue === "object" && "message" in firstIssue) {
23079
- return String(firstIssue.message);
23080
- }
23081
- }
23082
23098
  try {
23083
23099
  return JSON.stringify(error51);
23084
23100
  } catch {
@@ -29693,16 +29709,7 @@ var Server = class extends Protocol {
29693
29709
  if (!methodSchema) {
29694
29710
  throw new Error("Schema is missing a method literal");
29695
29711
  }
29696
- let methodValue;
29697
- if (isZ4Schema(methodSchema)) {
29698
- const v4Schema = methodSchema;
29699
- const v4Def = v4Schema._zod?.def;
29700
- methodValue = v4Def?.value ?? v4Schema.value;
29701
- } else {
29702
- const v3Schema = methodSchema;
29703
- const legacyDef = v3Schema._def;
29704
- methodValue = legacyDef?.value ?? v3Schema.value;
29705
- }
29712
+ const methodValue = getLiteralValue(methodSchema);
29706
29713
  if (typeof methodValue !== "string") {
29707
29714
  throw new Error("Schema method literal must be a string");
29708
29715
  }
@@ -30890,8 +30897,17 @@ var EMPTY_COMPLETION_RESULT = {
30890
30897
  import process3 from "node:process";
30891
30898
 
30892
30899
  // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
30900
+ var STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024;
30893
30901
  var ReadBuffer = class {
30902
+ constructor(options) {
30903
+ this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE;
30904
+ }
30894
30905
  append(chunk) {
30906
+ const newSize = (this._buffer?.length ?? 0) + chunk.length;
30907
+ if (newSize > this._maxBufferSize) {
30908
+ this.clear();
30909
+ throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);
30910
+ }
30895
30911
  this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
30896
30912
  }
30897
30913
  readMessage() {
@@ -30919,18 +30935,24 @@ function serializeMessage(message) {
30919
30935
 
30920
30936
  // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
30921
30937
  var StdioServerTransport = class {
30922
- constructor(_stdin = process3.stdin, _stdout = process3.stdout) {
30938
+ constructor(_stdin = process3.stdin, _stdout = process3.stdout, options) {
30923
30939
  this._stdin = _stdin;
30924
30940
  this._stdout = _stdout;
30925
- this._readBuffer = new ReadBuffer();
30926
30941
  this._started = false;
30927
30942
  this._ondata = (chunk) => {
30928
- this._readBuffer.append(chunk);
30929
- this.processReadBuffer();
30943
+ try {
30944
+ this._readBuffer.append(chunk);
30945
+ this.processReadBuffer();
30946
+ } catch (error51) {
30947
+ this.onerror?.(error51);
30948
+ this.close().catch(() => {
30949
+ });
30950
+ }
30930
30951
  };
30931
30952
  this._onerror = (error51) => {
30932
30953
  this.onerror?.(error51);
30933
30954
  };
30955
+ this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize });
30934
30956
  }
30935
30957
  /**
30936
30958
  * Starts listening for messages on stdin.
@@ -31123,6 +31145,21 @@ import { delimiter, join } from "node:path";
31123
31145
  function isGogFileArg(arg) {
31124
31146
  return typeof arg !== "string";
31125
31147
  }
31148
+ var RUNNER_TRANSPORT_BRAND = /* @__PURE__ */ Symbol.for("gogcli.RunnerTransportError");
31149
+ var RunnerTransportError = class extends Error {
31150
+ kind;
31151
+ status;
31152
+ constructor(message, kind, status) {
31153
+ super(message);
31154
+ this.name = "RunnerTransportError";
31155
+ this.kind = kind;
31156
+ this.status = status;
31157
+ Object.defineProperty(this, RUNNER_TRANSPORT_BRAND, { value: true });
31158
+ }
31159
+ };
31160
+ function isRunnerTransportError(err) {
31161
+ return err instanceof Error && err[RUNNER_TRANSPORT_BRAND] === true;
31162
+ }
31126
31163
  var runExecutor = new AsyncLocalStorage();
31127
31164
  var defaultExecutor;
31128
31165
  function setDefaultGogExecutor(executor) {
@@ -31303,7 +31340,11 @@ async function run(args, options = {}) {
31303
31340
  }
31304
31341
  return redact(output);
31305
31342
  } catch (err) {
31306
- throw new Error(redact(err instanceof Error ? err.message : String(err)));
31343
+ const message = redact(err instanceof Error ? err.message : String(err));
31344
+ if (isRunnerTransportError(err)) {
31345
+ throw new RunnerTransportError(message, err.kind, err.status);
31346
+ }
31347
+ throw new Error(message);
31307
31348
  }
31308
31349
  }
31309
31350
 
@@ -31562,7 +31603,9 @@ function registerRunTool(server, options) {
31562
31603
  function errorText(err) {
31563
31604
  return err instanceof Error ? `Error: ${err.message}` : String(err);
31564
31605
  }
31565
- var AUTH_ERROR_PATTERN = /\b(401|unauthorized|token.*(expired|revoked)|invalid_grant)\b/i;
31606
+ var DEFINITE_AUTH_PATTERN = /\b(?:unauthorized|invalid_grant)\b|\b(?:error|status|code|http|responded|response)["']?[\s:=(,]{0,4}401\b/i;
31607
+ 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;
31608
+ var AUTH_ERROR_PATTERN = new RegExp(`${DEFINITE_AUTH_PATTERN.source}|${STALE_TOKEN_PATTERN.source}`, "i");
31566
31609
  var INVALID_GRANT_PATTERN = /invalid_grant|token has been expired or revoked/i;
31567
31610
  var TRANSIENT_ERROR_PATTERN = /\b429\b|\b5\d\d\b|\bquota\b|rateLimit|\bDEADLINE_EXCEEDED\b/i;
31568
31611
  var GRID_LIMIT_ERROR_PATTERN = /exceeds grid limits/i;
@@ -31570,6 +31613,14 @@ var AUTH_HINT = "\n\nAuthentication may have expired. Use gog_auth_add to re-aut
31570
31613
  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.';
31571
31614
  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).";
31572
31615
  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.";
31616
+ 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.";
31617
+ var RUNNER_TRANSPORT_HINTS = {
31618
+ "transport-auth": RUNNER_TRANSPORT_AUTH_HINT,
31619
+ // The request itself was malformed, so the runner will refuse it identically
31620
+ // every time. Nothing to advise beyond the message the runner already gave.
31621
+ "transport-request": "",
31622
+ "transport-retryable": TRANSIENT_HINT
31623
+ };
31573
31624
  function formatAccountList(raw) {
31574
31625
  try {
31575
31626
  const parsed = JSON.parse(raw);
@@ -31582,11 +31633,12 @@ function formatAccountList(raw) {
31582
31633
  }
31583
31634
  async function diagnose(err) {
31584
31635
  const errText = errorText(err);
31636
+ const transportHint = isRunnerTransportError(err) ? RUNNER_TRANSPORT_HINTS[err.kind] : void 0;
31585
31637
  const isInvalidGrant = INVALID_GRANT_PATTERN.test(errText);
31586
- const isAuthError = AUTH_ERROR_PATTERN.test(errText);
31587
- const isTransientError = !isAuthError && TRANSIENT_ERROR_PATTERN.test(errText);
31638
+ const isTransientError = !DEFINITE_AUTH_PATTERN.test(errText) && TRANSIENT_ERROR_PATTERN.test(errText);
31639
+ const isAuthError = !isTransientError && AUTH_ERROR_PATTERN.test(errText);
31588
31640
  const isGridLimitError = GRID_LIMIT_ERROR_PATTERN.test(errText);
31589
- const hint = isInvalidGrant ? INVALID_GRANT_HINT : isAuthError ? AUTH_HINT : isTransientError ? TRANSIENT_HINT : isGridLimitError ? GRID_LIMIT_HINT : "";
31641
+ const hint = transportHint ?? (isInvalidGrant ? INVALID_GRANT_HINT : isAuthError ? AUTH_HINT : isTransientError ? TRANSIENT_HINT : isGridLimitError ? GRID_LIMIT_HINT : "");
31590
31642
  try {
31591
31643
  const accounts = formatAccountList(await run(["auth", "list"]));
31592
31644
  return errorResult(`${errText}
@@ -31651,7 +31703,7 @@ function formatAuthHealth(raw, now) {
31651
31703
  function registerAuthToolsWith(server, defaultServices) {
31652
31704
  const servicesDescribe = `Services to authorize: "all" or comma-separated list (e.g. "sheets,gmail,calendar"). Default: "${defaultServices}". Prefer the narrowest set you need \u2014 requesting a service whose Google API is not enabled on the OAuth client's project makes Google reject the WHOLE request with invalid_scope.`;
31653
31705
  server.registerTool("gog_auth_list", {
31654
- description: "List all Google accounts stored in gogcli. Use this to check which accounts are configured and available.",
31706
+ description: "List the Google accounts stored in gogcli, with their scopes. This reads local configuration only \u2014 it does not contact Google and does NOT tell you whether an account still works: a signed-out account whose refresh token expired or was revoked is listed here exactly like a healthy one, scopes and all. Use gog_auth_health to check whether an account can actually authenticate.",
31655
31707
  annotations: { readOnlyHint: true },
31656
31708
  inputSchema: {}
31657
31709
  }, async () => {
@@ -31837,59 +31889,375 @@ var failIfNotEmptyParam = external_exports.boolean().optional().describe(
31837
31889
  );
31838
31890
 
31839
31891
  // ../gogcli-mcp/src/server.ts
31840
- var VERSION = true ? "2.20.0" : "0.0.0";
31892
+ var VERSION = true ? "2.21.1" : "0.0.0";
31893
+
31894
+ // ../gogcli-mcp/src/auth-log.ts
31895
+ var FAILURES = /* @__PURE__ */ new Set([
31896
+ "token.mint-failed",
31897
+ "grant.dead",
31898
+ "replay.failed",
31899
+ "runner.auth-failed"
31900
+ ]);
31901
+ var PREFIX = "gog-auth ";
31902
+ var TAG_CHARS = 12;
31903
+ function credentialTag(cacheKeyHash) {
31904
+ return cacheKeyHash.slice(0, TAG_CHARS);
31905
+ }
31906
+ function logAuthTransition(event, context) {
31907
+ const record2 = JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), event, ...context });
31908
+ const write = FAILURES.has(event) ? console.error : console.warn;
31909
+ write(PREFIX + redactSecrets2(record2));
31910
+ }
31911
+
31912
+ // ../gogcli-mcp/src/google-token.ts
31913
+ var TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token";
31914
+ var EXPIRY_MARGIN_MS = 12e4;
31915
+ var cache = /* @__PURE__ */ new Map();
31916
+ var inFlight = /* @__PURE__ */ new Map();
31917
+ async function cacheKey(refreshToken, clientId) {
31918
+ const data = new TextEncoder().encode(`${clientId}\0${refreshToken}`);
31919
+ const digest = await crypto.subtle.digest("SHA-256", data);
31920
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
31921
+ }
31922
+ function makeAccessTokenSource(env) {
31923
+ const direct = readEnvVar("GOG_ACCESS_TOKEN", { env });
31924
+ if (direct) return async () => direct;
31925
+ const refreshToken = readEnvVar("GOG_REFRESH_TOKEN", { env });
31926
+ if (!refreshToken) return void 0;
31927
+ const clientId = readEnvVar("GOG_CLIENT_ID", { env });
31928
+ const clientSecret = readEnvVar("GOG_CLIENT_SECRET", { env });
31929
+ if (!clientId || !clientSecret) {
31930
+ const missing = [!clientId && "GOG_CLIENT_ID", !clientSecret && "GOG_CLIENT_SECRET"].filter(Boolean).join(" and ");
31931
+ return async () => {
31932
+ throw new Error(
31933
+ `GOG_REFRESH_TOKEN is set but ${missing} is not, so no access token can be minted. Set the OAuth client alongside the refresh token, or unset GOG_REFRESH_TOKEN to use the backend\u2019s own identity.`
31934
+ );
31935
+ };
31936
+ }
31937
+ let keyPromise;
31938
+ const key = () => keyPromise ??= cacheKey(refreshToken, clientId);
31939
+ const logCacheHits = parseBoolEnv("GOG_AUTH_LOG_CACHE_HITS", { env });
31940
+ const read = async () => {
31941
+ const k = await key();
31942
+ const hit = cache.get(k);
31943
+ if (hit && hit.expiresAt - EXPIRY_MARGIN_MS > Date.now()) {
31944
+ if (logCacheHits) logAuthTransition("token.cache-hit", { credential: credentialTag(k) });
31945
+ return hit.accessToken;
31946
+ }
31947
+ let pending = inFlight.get(k);
31948
+ if (!pending) {
31949
+ pending = exchange(refreshToken, clientId, clientSecret).then((minted2) => {
31950
+ cache.set(k, minted2);
31951
+ logAuthTransition("token.minted", {
31952
+ credential: credentialTag(k),
31953
+ reason: `valid for ${Math.round((minted2.expiresAt - Date.now()) / 1e3)}s`
31954
+ });
31955
+ return minted2;
31956
+ }).catch((err) => {
31957
+ logAuthTransition(err.grantDead ? "grant.dead" : "token.mint-failed", {
31958
+ credential: credentialTag(k),
31959
+ reason: err.message
31960
+ });
31961
+ throw err;
31962
+ }).finally(() => inFlight.delete(k));
31963
+ inFlight.set(k, pending);
31964
+ }
31965
+ const minted = await pending;
31966
+ return minted.accessToken;
31967
+ };
31968
+ const invalidate = async (rejected) => {
31969
+ const k = await key();
31970
+ const hit = cache.get(k);
31971
+ if (!hit || hit.accessToken !== rejected) {
31972
+ logAuthTransition("token.evict-noop", {
31973
+ credential: credentialTag(k),
31974
+ reason: hit ? "a concurrent caller had already replaced this credential\u2019s token" : "no token was cached for this credential"
31975
+ });
31976
+ return false;
31977
+ }
31978
+ cache.delete(k);
31979
+ logAuthTransition("token.evicted", {
31980
+ credential: credentialTag(k),
31981
+ reason: "Google rejected this access token; the next read will mint a new one"
31982
+ });
31983
+ return true;
31984
+ };
31985
+ return Object.assign(read, {
31986
+ invalidate,
31987
+ credentialId: async () => credentialTag(await key())
31988
+ });
31989
+ }
31990
+ var TokenExchangeError = class extends Error {
31991
+ /**
31992
+ * The REFRESH token is dead (Google's `invalid_grant`), not merely the access
31993
+ * token. Carried as a flag rather than re-read from the message, because
31994
+ * inferring the author of a failure from prose several authors can produce is
31995
+ * precisely the mistake this branch exists to undo. `instanceof` is safe: the
31996
+ * class is thrown and caught inside this one module.
31997
+ */
31998
+ grantDead;
31999
+ constructor(message, grantDead) {
32000
+ super(message);
32001
+ this.grantDead = grantDead;
32002
+ }
32003
+ };
32004
+ async function exchange(refreshToken, clientId, clientSecret) {
32005
+ let res;
32006
+ try {
32007
+ res = await fetch(TOKEN_ENDPOINT, {
32008
+ method: "POST",
32009
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
32010
+ body: new URLSearchParams({
32011
+ grant_type: "refresh_token",
32012
+ refresh_token: refreshToken,
32013
+ client_id: clientId,
32014
+ client_secret: clientSecret
32015
+ }).toString()
32016
+ });
32017
+ } catch (err) {
32018
+ throw new TokenExchangeError(
32019
+ `the Google token exchange could not be reached: ${err instanceof Error ? err.message : String(err)}`,
32020
+ false
32021
+ );
32022
+ }
32023
+ const body = await res.json().catch(() => ({}));
32024
+ if (!res.ok) {
32025
+ if (body.error === "invalid_grant") {
32026
+ throw new TokenExchangeError(
32027
+ '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.',
32028
+ true
32029
+ );
32030
+ }
32031
+ throw new TokenExchangeError(
32032
+ `the access token could not be refreshed (HTTP ${res.status}${body.error ? `, ${body.error}` : ""})`,
32033
+ false
32034
+ );
32035
+ }
32036
+ if (!body.access_token) {
32037
+ throw new TokenExchangeError(
32038
+ "the access token could not be refreshed: Google returned no access_token",
32039
+ false
32040
+ );
32041
+ }
32042
+ const expiresInMs = (body.expires_in ?? 3600) * 1e3;
32043
+ return { accessToken: body.access_token, expiresAt: Date.now() + expiresInMs };
32044
+ }
31841
32045
 
31842
32046
  // ../gogcli-mcp/src/connector-runtime.ts
31843
32047
  var DEFAULT_TIMEOUT_MS = 3e4;
31844
32048
  var DEADLINE_GRACE_MS = 5e3;
32049
+ var MIN_REPLAY_BUDGET_MS = 1e3;
31845
32050
  var RUNNER_GOG_FAILED = 422;
31846
32051
  var RUNNER_DRAINING = 503;
32052
+ var RUNNER_BAD_REQUEST = 400;
32053
+ var RUNNER_BAD_KEY = 401;
32054
+ var GogFailedError = class extends Error {
32055
+ /** gog's stderr alone, with no echoed argv mixed in. */
32056
+ stderr;
32057
+ constructor(message, stderr) {
32058
+ super(message);
32059
+ this.stderr = stderr;
32060
+ }
32061
+ };
32062
+ var GOOGLE_TOKEN_REJECTED_PATTERN = /Google API error \(401\b|invalid[ _]authentication[ _]credentials|\bACCESS_TOKEN_EXPIRED\b|\binvalid_token\b/i;
32063
+ var REFRESH_TOKEN_DEAD_PATTERN = /\binvalid_grant\b/i;
32064
+ var READ_ONLY_SUBCOMMANDS = /* @__PURE__ */ new Set([
32065
+ "cat",
32066
+ "describe",
32067
+ "get",
32068
+ "info",
32069
+ "list",
32070
+ "list-slides",
32071
+ "ls",
32072
+ "metadata",
32073
+ "read-slide",
32074
+ "search",
32075
+ "services",
32076
+ "status",
32077
+ "structure"
32078
+ ]);
32079
+ function gogTarget(args) {
32080
+ const words = args.filter((arg) => typeof arg === "string");
32081
+ let service;
32082
+ for (let i = 0; i < words.length; i += 1) {
32083
+ const word = words[i];
32084
+ if (word.startsWith("-")) {
32085
+ if (word === "--account") i += 1;
32086
+ continue;
32087
+ }
32088
+ if (service === void 0) {
32089
+ service = word;
32090
+ continue;
32091
+ }
32092
+ return { service, subcommand: word };
32093
+ }
32094
+ return { service };
32095
+ }
32096
+ async function remintAfterGoogleRejection(err, used, args, readAccessToken, deadlineAt) {
32097
+ if (!(err instanceof GogFailedError)) return void 0;
32098
+ const grantDead = REFRESH_TOKEN_DEAD_PATTERN.test(err.stderr);
32099
+ if (!grantDead && !GOOGLE_TOKEN_REJECTED_PATTERN.test(err.stderr)) return void 0;
32100
+ const { service, subcommand } = gogTarget(args);
32101
+ const credential = await readAccessToken?.credentialId?.();
32102
+ const where = { credential, service };
32103
+ if (grantDead) {
32104
+ logAuthTransition("grant.dead", {
32105
+ ...where,
32106
+ reason: "gog reported invalid_grant: the stored refresh token is dead, so no token can be minted and this account must be re-authorized"
32107
+ });
32108
+ return void 0;
32109
+ }
32110
+ if (!used) {
32111
+ logAuthTransition("replay.declined", {
32112
+ ...where,
32113
+ reason: "no access token was supplied with the call, so gog acted as the backend volume\u2019s own identity"
32114
+ });
32115
+ return void 0;
32116
+ }
32117
+ if (!readAccessToken?.invalidate) {
32118
+ logAuthTransition("replay.declined", {
32119
+ ...where,
32120
+ reason: "this token source cannot mint a replacement, so a replay would resend the rejected token"
32121
+ });
32122
+ return void 0;
32123
+ }
32124
+ const evicted = await readAccessToken.invalidate(used);
32125
+ if (subcommand === void 0 || !READ_ONLY_SUBCOMMANDS.has(subcommand)) {
32126
+ logAuthTransition("replay.declined", {
32127
+ ...where,
32128
+ reason: `not replayable: '${subcommand ?? "(none)"}' is not a known read-only subcommand and a write could double-apply`
32129
+ });
32130
+ return void 0;
32131
+ }
32132
+ if (!evicted) {
32133
+ logAuthTransition("replay.declined", {
32134
+ ...where,
32135
+ reason: "the rejected token was already superseded, so the cache holds the token a replay would send"
32136
+ });
32137
+ return void 0;
32138
+ }
32139
+ const fresh = await readAccessToken();
32140
+ if (!fresh) {
32141
+ logAuthTransition("replay.declined", {
32142
+ ...where,
32143
+ reason: "the token source produced no token after eviction; replaying without one would act as the backend"
32144
+ });
32145
+ return void 0;
32146
+ }
32147
+ const budgetMs = deadlineAt - Date.now();
32148
+ if (budgetMs < MIN_REPLAY_BUDGET_MS) {
32149
+ logAuthTransition("replay.declined", {
32150
+ ...where,
32151
+ 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`
32152
+ });
32153
+ return void 0;
32154
+ }
32155
+ return { token: fresh, budgetMs, invalidate: readAccessToken.invalidate, ...where };
32156
+ }
31847
32157
  function makeFlyExecutor(endpoint, key, readAccessToken) {
31848
32158
  return async (args, opts) => {
31849
32159
  const deadlineMs = (opts?.timeout ?? DEFAULT_TIMEOUT_MS) + DEADLINE_GRACE_MS;
31850
- const accessToken = readAccessToken?.();
31851
- let res;
32160
+ const accessToken = await readAccessToken?.();
32161
+ const deadlineAt = Date.now() + deadlineMs;
31852
32162
  try {
31853
- res = await fetch(endpoint + "/run", {
31854
- method: "POST",
31855
- headers: {
31856
- Authorization: "Bearer " + key,
31857
- "Content-Type": "application/json"
31858
- },
31859
- body: JSON.stringify(accessToken ? { args, accessToken } : { args }),
31860
- signal: AbortSignal.timeout(deadlineMs)
31861
- });
32163
+ return await attempt(endpoint, key, args, accessToken, deadlineMs);
31862
32164
  } catch (err) {
31863
- const name = err instanceof Error ? err.name : "";
31864
- if (name === "TimeoutError" || name === "AbortError") {
31865
- throw new Error(
31866
- `gog-runner did not respond within ${deadlineMs}ms (${endpoint}) \u2014 the Fly backend may be cold or wedged`
31867
- );
32165
+ const replay = await remintAfterGoogleRejection(
32166
+ err,
32167
+ accessToken,
32168
+ args,
32169
+ readAccessToken,
32170
+ deadlineAt
32171
+ );
32172
+ if (replay === void 0) throw err;
32173
+ const where = { credential: replay.credential, service: replay.service, endpoint };
32174
+ logAuthTransition("replay.attempted", {
32175
+ ...where,
32176
+ reason: "Google rejected the access token; replaying this read once with a freshly minted one"
32177
+ });
32178
+ try {
32179
+ const stdout = await attempt(endpoint, key, args, replay.token, replay.budgetMs);
32180
+ logAuthTransition("replay.succeeded", where);
32181
+ return stdout;
32182
+ } catch (replayErr) {
32183
+ logAuthTransition("replay.failed", { ...where, reason: String(replayErr) });
32184
+ if (replayErr instanceof GogFailedError && GOOGLE_TOKEN_REJECTED_PATTERN.test(replayErr.stderr)) {
32185
+ await replay.invalidate(replay.token);
32186
+ }
32187
+ throw replayErr;
31868
32188
  }
31869
- throw err;
31870
32189
  }
31871
- if (!res.ok) {
31872
- const body = await res.json().catch(() => null);
31873
- const detail = body && typeof body.error === "string" ? body.stderr && body.stderr.trim() && body.stderr.trim() !== body.error.trim() ? `${body.error}
32190
+ };
32191
+ }
32192
+ async function attempt(endpoint, key, args, accessToken, deadlineMs) {
32193
+ let res;
32194
+ try {
32195
+ res = await fetch(endpoint + "/run", {
32196
+ method: "POST",
32197
+ headers: {
32198
+ Authorization: "Bearer " + key,
32199
+ "Content-Type": "application/json"
32200
+ },
32201
+ body: JSON.stringify(accessToken ? { args, accessToken } : { args }),
32202
+ signal: AbortSignal.timeout(deadlineMs)
32203
+ });
32204
+ } catch (err) {
32205
+ const name = err instanceof Error ? err.name : "";
32206
+ if (name === "TimeoutError" || name === "AbortError") {
32207
+ throw new RunnerTransportError(
32208
+ `gog-runner did not respond within ${deadlineMs}ms (${endpoint}) \u2014 the Fly backend may be cold or wedged`,
32209
+ "transport-retryable"
32210
+ );
32211
+ }
32212
+ throw err;
32213
+ }
32214
+ if (!res.ok) {
32215
+ const body = await res.json().catch(() => null);
32216
+ const detail = body && typeof body.error === "string" ? body.stderr && body.stderr.trim() && body.stderr.trim() !== body.error.trim() ? `${body.error}
31874
32217
  ${body.stderr}` : body.error : "";
31875
- if (res.status === RUNNER_GOG_FAILED) {
31876
- throw new Error(detail || "gog failed on the runner (no detail supplied)");
31877
- }
31878
- if (res.status === RUNNER_DRAINING || body?.retryable === true) {
31879
- throw new Error(
31880
- `gog-runner is restarting; retry this call.${detail ? ` ${detail}` : ""}`
31881
- );
31882
- }
31883
- if (detail) {
31884
- throw new Error(detail);
31885
- }
31886
- throw new Error(
31887
- `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.`
32218
+ if (res.status === RUNNER_GOG_FAILED) {
32219
+ throw new GogFailedError(
32220
+ detail || "gog failed on the runner (no detail supplied)",
32221
+ typeof body?.stderr === "string" ? body.stderr : ""
31888
32222
  );
31889
32223
  }
31890
- const { stdout } = await res.json();
31891
- return stdout;
31892
- };
32224
+ if (res.status === RUNNER_BAD_KEY) {
32225
+ logAuthTransition("runner.auth-failed", {
32226
+ service: gogTarget(args).service,
32227
+ endpoint,
32228
+ 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"
32229
+ });
32230
+ throw new RunnerTransportError(
32231
+ "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.",
32232
+ "transport-auth",
32233
+ res.status
32234
+ );
32235
+ }
32236
+ if (res.status === RUNNER_BAD_REQUEST) {
32237
+ throw new RunnerTransportError(
32238
+ detail || "gog-runner rejected the request (no detail supplied)",
32239
+ "transport-request",
32240
+ res.status
32241
+ );
32242
+ }
32243
+ if (res.status === RUNNER_DRAINING || body?.retryable === true) {
32244
+ throw new RunnerTransportError(
32245
+ `gog-runner is restarting; retry this call.${detail ? ` ${detail}` : ""}`,
32246
+ "transport-retryable",
32247
+ res.status
32248
+ );
32249
+ }
32250
+ if (detail) {
32251
+ throw new Error(detail);
32252
+ }
32253
+ throw new RunnerTransportError(
32254
+ `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.`,
32255
+ "transport-retryable",
32256
+ res.status
32257
+ );
32258
+ }
32259
+ const { stdout } = await res.json();
32260
+ return stdout;
31893
32261
  }
31894
32262
 
31895
32263
  // ../gogcli-mcp/src/remote-runner.ts
@@ -31898,7 +32266,7 @@ function useRemoteGogRunner(env = process.env) {
31898
32266
  const key = readEnvVar("GOG_RUNNER_KEY", { env });
31899
32267
  if (!endpoint || !key) return false;
31900
32268
  setDefaultGogExecutor(
31901
- makeFlyExecutor(endpoint.replace(/\/+$/, ""), key, () => readEnvVar("GOG_ACCESS_TOKEN", { env }))
32269
+ makeFlyExecutor(endpoint.replace(/\/+$/, ""), key, makeAccessTokenSource(env))
31902
32270
  );
31903
32271
  return true;
31904
32272
  }
@@ -32473,17 +32841,19 @@ function registerExtraGmailTools(server) {
32473
32841
  return writeDraft(args, account, returnFull);
32474
32842
  });
32475
32843
  server.registerTool("gog_gmail_drafts_update", {
32476
- description: "Update an existing Gmail draft. For replies, prefer replyToThreadId (threads off the thread's latest message) or replyToMessageId (a specific message) over passing a thread id into replyToMessageId. Attachment semantics: supplying attach REPLACES the draft's existing attachments; omitting it preserves them; set clearAttachments to remove all.",
32844
+ description: "Update an existing Gmail draft. For replies, prefer replyToThreadId (threads off the thread's latest message) or replyToMessageId (a specific message) over passing a thread id into replyToMessageId. An update preserves the draft's existing reply context (In-Reply-To/References) and its threadId; it never invents reply headers for a draft that is not a reply. The result reports the effective inReplyTo/references so you can verify threading without a raw-header fetch. Attachment semantics: supplying attach REPLACES the draft's existing attachments; omitting it preserves them; set clearAttachments to remove all.",
32477
32845
  annotations: { destructiveHint: true },
32478
32846
  inputSchema: {
32479
32847
  draftId: external_exports.string().describe("Draft ID"),
32480
32848
  ...draftWriteSchema,
32481
- clearAttachments: external_exports.boolean().optional().describe("Remove all attachments from the draft. By default, omitting attach preserves the draft's existing attachments; this intentionally clears them. Ignored if attach is also supplied (attach replaces).")
32849
+ clearAttachments: external_exports.boolean().optional().describe("Remove all attachments from the draft. By default, omitting attach preserves the draft's existing attachments; this intentionally clears them. Ignored if attach is also supplied (attach replaces)."),
32850
+ clearReplyContext: external_exports.boolean().optional().describe("Strip In-Reply-To/References from the draft, turning a reply back into a standalone message while keeping the same draft id and threadId. Use this to repair a mis-threaded draft in place instead of deleting and recreating it. Mutually exclusive with replyToMessageId, replyToThreadId and quote \u2014 gog rejects the call if any of them is combined with this.")
32482
32851
  }
32483
- }, async ({ draftId, account, returnFull, clearAttachments, ...flags }) => {
32852
+ }, async ({ draftId, account, returnFull, clearAttachments, clearReplyContext, ...flags }) => {
32484
32853
  const args = ["gmail", "drafts", "update", draftId];
32485
32854
  appendDraftFlags(args, flags);
32486
32855
  if (clearAttachments) args.push("--clear-attachments");
32856
+ if (clearReplyContext) args.push("--clear-reply-context");
32487
32857
  return writeDraft(args, account, returnFull, draftId);
32488
32858
  });
32489
32859
  server.registerTool("gog_gmail_drafts_delete", {
package/manifest.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "manifest_version": "0.3",
4
4
  "name": "gogcli-mcp-gmail",
5
5
  "display_name": "gogcli (Gmail)",
6
- "version": "2.20.0",
6
+ "version": "2.21.1",
7
7
  "description": "Extended Gmail for Claude via gogcli — auth + full Gmail support (threads, labels, drafts, attachments, forward, autoreply, bulk operations)",
8
8
  "author": {
9
9
  "name": "Chris Hall",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gogcli-mcp-gmail",
3
- "version": "2.20.0",
3
+ "version": "2.21.1",
4
4
  "mcpName": "io.github.chrischall/gogcli-mcp-gmail",
5
5
  "description": "Extended Gmail MCP server via gogcli — auth + full Gmail support (threads, labels, drafts, attachments, forward, autoreply, bulk operations)",
6
6
  "author": "Claude Code (AI) <https://www.anthropic.com/claude>",
@@ -24,8 +24,8 @@
24
24
  "test:coverage": "vitest run --coverage"
25
25
  },
26
26
  "dependencies": {
27
- "@chrischall/mcp-utils": "^0.13.3",
28
- "@modelcontextprotocol/sdk": "^1.29.0",
27
+ "@chrischall/mcp-utils": "^0.14.0",
28
+ "@modelcontextprotocol/sdk": "^1.30.0",
29
29
  "zod": "^4.4.3"
30
30
  },
31
31
  "license": "MIT",
@@ -840,17 +840,19 @@ export function registerExtraGmailTools(server: McpServer): void {
840
840
  });
841
841
 
842
842
  server.registerTool('gog_gmail_drafts_update', {
843
- description: 'Update an existing Gmail draft. For replies, prefer replyToThreadId (threads off the thread\'s latest message) or replyToMessageId (a specific message) over passing a thread id into replyToMessageId. Attachment semantics: supplying attach REPLACES the draft\'s existing attachments; omitting it preserves them; set clearAttachments to remove all.',
843
+ description: 'Update an existing Gmail draft. For replies, prefer replyToThreadId (threads off the thread\'s latest message) or replyToMessageId (a specific message) over passing a thread id into replyToMessageId. An update preserves the draft\'s existing reply context (In-Reply-To/References) and its threadId; it never invents reply headers for a draft that is not a reply. The result reports the effective inReplyTo/references so you can verify threading without a raw-header fetch. Attachment semantics: supplying attach REPLACES the draft\'s existing attachments; omitting it preserves them; set clearAttachments to remove all.',
844
844
  annotations: { destructiveHint: true },
845
845
  inputSchema: {
846
846
  draftId: z.string().describe('Draft ID'),
847
847
  ...draftWriteSchema,
848
848
  clearAttachments: z.boolean().optional().describe('Remove all attachments from the draft. By default, omitting attach preserves the draft\'s existing attachments; this intentionally clears them. Ignored if attach is also supplied (attach replaces).'),
849
+ clearReplyContext: z.boolean().optional().describe('Strip In-Reply-To/References from the draft, turning a reply back into a standalone message while keeping the same draft id and threadId. Use this to repair a mis-threaded draft in place instead of deleting and recreating it. Mutually exclusive with replyToMessageId, replyToThreadId and quote — gog rejects the call if any of them is combined with this.'),
849
850
  },
850
- }, async ({ draftId, account, returnFull, clearAttachments, ...flags }) => {
851
+ }, async ({ draftId, account, returnFull, clearAttachments, clearReplyContext, ...flags }) => {
851
852
  const args: GogArg[] = ['gmail', 'drafts', 'update', draftId];
852
853
  appendDraftFlags(args, flags);
853
854
  if (clearAttachments) args.push('--clear-attachments');
855
+ if (clearReplyContext) args.push('--clear-reply-context');
854
856
  return writeDraft(args, account, returnFull, draftId);
855
857
  });
856
858
 
@@ -932,6 +932,40 @@ describe('gog_gmail_drafts_update', () => {
932
932
  );
933
933
  });
934
934
 
935
+ it('passes --clear-reply-context when clearReplyContext is true', async () => {
936
+ await harness.callTool('gog_gmail_drafts_update', {
937
+ draftId: 'd1', subject: 'S', body: 'B', clearReplyContext: true,
938
+ });
939
+ expect(lib.runOrDiagnose).toHaveBeenCalledWith(
940
+ ['gmail', 'drafts', 'update', 'd1', '--subject=S', '--body=B', '--clear-reply-context'],
941
+ { account: undefined },
942
+ );
943
+ });
944
+
945
+ // A plain update carries no reply flags at all: gog preserves the draft's own
946
+ // reply context and threadId. Passing a reply target here would re-anchor the
947
+ // draft, so the wrapper must stay silent when the caller says nothing.
948
+ it('sends no reply or thread flags when no reply target is supplied', async () => {
949
+ await harness.callTool('gog_gmail_drafts_update', {
950
+ draftId: 'd1', subject: 'S', body: 'B',
951
+ });
952
+ const args = vi.mocked(lib.runOrDiagnose).mock.calls[0]?.[0] as string[];
953
+ expect(args.some((a) => a.startsWith('--reply-to-message-id'))).toBe(false);
954
+ expect(args.some((a) => a.startsWith('--thread-id'))).toBe(false);
955
+ expect(args).not.toContain('--clear-reply-context');
956
+ });
957
+
958
+ it('combines clearAttachments and clearReplyContext', async () => {
959
+ await harness.callTool('gog_gmail_drafts_update', {
960
+ draftId: 'd1', subject: 'S', body: 'B', clearAttachments: true, clearReplyContext: true,
961
+ });
962
+ expect(lib.runOrDiagnose).toHaveBeenCalledWith(
963
+ ['gmail', 'drafts', 'update', 'd1', '--subject=S', '--body=B',
964
+ '--clear-attachments', '--clear-reply-context'],
965
+ { account: undefined },
966
+ );
967
+ });
968
+
935
969
  it('returnFull re-fetches the draft by its known id', async () => {
936
970
  vi.mocked(lib.runOrDiagnose)
937
971
  .mockResolvedValueOnce(rawTextResult('{"draftId":"d1"}'))