mcp-google-multi 6.0.0-beta.1 → 6.0.0-beta.3

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.
Files changed (182) hide show
  1. package/README.md +5 -3
  2. package/dist/accounts.d.ts +22 -1
  3. package/dist/accounts.js +64 -16
  4. package/dist/api-probe.d.ts +5 -0
  5. package/dist/api-probe.js +23 -15
  6. package/dist/arg-normalize.d.ts +61 -4
  7. package/dist/arg-normalize.js +229 -4
  8. package/dist/arg-strict.d.ts +61 -0
  9. package/dist/arg-strict.js +193 -0
  10. package/dist/auth.d.ts +4 -3
  11. package/dist/auth.js +26 -85
  12. package/dist/boot-gates.d.ts +26 -0
  13. package/dist/boot-gates.js +38 -0
  14. package/dist/cimd-cache.d.ts +38 -0
  15. package/dist/cimd-cache.js +117 -0
  16. package/dist/client.d.ts +32 -2
  17. package/dist/client.js +0 -0
  18. package/dist/compose.d.ts +11 -0
  19. package/dist/compose.js +109 -0
  20. package/dist/config-file.d.ts +14 -0
  21. package/dist/config-file.js +41 -1
  22. package/dist/discover.js +38 -15
  23. package/dist/discovery-client.d.ts +11 -1
  24. package/dist/discovery-client.js +120 -18
  25. package/dist/doctor.d.ts +15 -3
  26. package/dist/doctor.js +151 -27
  27. package/dist/env-load.d.ts +11 -0
  28. package/dist/env-load.js +23 -1
  29. package/dist/executor.d.ts +3 -0
  30. package/dist/executor.js +16 -3
  31. package/dist/fanout.d.ts +9 -1
  32. package/dist/fanout.js +83 -14
  33. package/dist/fs-atomic.d.ts +11 -0
  34. package/dist/fs-atomic.js +219 -28
  35. package/dist/hint-provider.d.ts +129 -0
  36. package/dist/hint-provider.js +64 -0
  37. package/dist/http-transport.d.ts +73 -6
  38. package/dist/http-transport.js +350 -26
  39. package/dist/identity.d.ts +4 -1
  40. package/dist/identity.js +25 -6
  41. package/dist/index.js +142 -114
  42. package/dist/master-key.js +13 -5
  43. package/dist/mcp-token.d.ts +136 -19
  44. package/dist/mcp-token.js +569 -72
  45. package/dist/metrics-cli.d.ts +21 -0
  46. package/dist/metrics-cli.js +206 -0
  47. package/dist/metrics-tap.d.ts +12 -0
  48. package/dist/metrics-tap.js +95 -0
  49. package/dist/migrate-config.js +2 -2
  50. package/dist/oauth-as.d.ts +103 -3
  51. package/dist/oauth-as.js +374 -79
  52. package/dist/oauth-consent.d.ts +35 -10
  53. package/dist/oauth-consent.js +101 -39
  54. package/dist/outbound-allowlist.d.ts +34 -0
  55. package/dist/outbound-allowlist.js +111 -0
  56. package/dist/reauth-hint.d.ts +1 -1
  57. package/dist/reauth-hint.js +12 -8
  58. package/dist/registry-transfer.d.ts +5 -0
  59. package/dist/registry-transfer.js +65 -5
  60. package/dist/registry.d.ts +66 -2
  61. package/dist/registry.js +214 -18
  62. package/dist/scope-catalog.d.ts +11 -0
  63. package/dist/scope-catalog.js +39 -6
  64. package/dist/scope-observability.d.ts +8 -6
  65. package/dist/scope-observability.js +29 -13
  66. package/dist/services.d.ts +17 -4
  67. package/dist/services.js +77 -6
  68. package/dist/setup-prompt.d.ts +1 -1
  69. package/dist/setup-prompt.js +1 -1
  70. package/dist/ssrf-guard.d.ts +23 -9
  71. package/dist/ssrf-guard.js +101 -62
  72. package/dist/tenant-purge.d.ts +26 -0
  73. package/dist/tenant-purge.js +67 -0
  74. package/dist/token-store.d.ts +20 -2
  75. package/dist/token-store.js +0 -0
  76. package/dist/tools/_coerce.d.ts +5 -0
  77. package/dist/tools/_coerce.js +11 -0
  78. package/dist/tools/_errors.d.ts +34 -3
  79. package/dist/tools/_errors.js +346 -53
  80. package/dist/tools/_local-files.d.ts +9 -0
  81. package/dist/tools/_local-files.js +25 -2
  82. package/dist/tools/account-wizard.d.ts +34 -2
  83. package/dist/tools/account-wizard.js +223 -65
  84. package/dist/tools/accounts-tool.d.ts +7 -0
  85. package/dist/tools/accounts-tool.js +34 -18
  86. package/dist/tools/admin.d.ts +10 -1
  87. package/dist/tools/admin.js +21 -16
  88. package/dist/tools/analytics.d.ts +27 -0
  89. package/dist/tools/analytics.js +289 -0
  90. package/dist/tools/calendar.d.ts +9 -1
  91. package/dist/tools/calendar.js +93 -29
  92. package/dist/tools/chat.d.ts +10 -1
  93. package/dist/tools/chat.js +20 -12
  94. package/dist/tools/contacts.d.ts +2 -1
  95. package/dist/tools/contacts.js +74 -43
  96. package/dist/tools/docs.d.ts +2 -1
  97. package/dist/tools/docs.js +90 -84
  98. package/dist/tools/drive.d.ts +2 -1
  99. package/dist/tools/drive.js +197 -120
  100. package/dist/tools/forms.d.ts +10 -1
  101. package/dist/tools/forms.js +26 -19
  102. package/dist/tools/generated/_shared.d.ts +8 -1
  103. package/dist/tools/generated/_shared.js +18 -4
  104. package/dist/tools/generated/admin.d.ts +2 -1
  105. package/dist/tools/generated/admin.js +610 -479
  106. package/dist/tools/generated/analytics.d.ts +3 -0
  107. package/dist/tools/generated/analytics.js +981 -0
  108. package/dist/tools/generated/appsmarket.d.ts +2 -1
  109. package/dist/tools/generated/appsmarket.js +9 -9
  110. package/dist/tools/generated/calendar.d.ts +2 -1
  111. package/dist/tools/generated/calendar.js +83 -83
  112. package/dist/tools/generated/chat.d.ts +2 -1
  113. package/dist/tools/generated/chat.js +178 -151
  114. package/dist/tools/generated/classroom.d.ts +2 -1
  115. package/dist/tools/generated/classroom.js +467 -425
  116. package/dist/tools/generated/cloudidentity.d.ts +2 -1
  117. package/dist/tools/generated/cloudidentity.js +209 -201
  118. package/dist/tools/generated/cloudsearch.d.ts +2 -1
  119. package/dist/tools/generated/cloudsearch.js +139 -138
  120. package/dist/tools/generated/contacts.d.ts +2 -1
  121. package/dist/tools/generated/contacts.js +49 -40
  122. package/dist/tools/generated/drive.d.ts +2 -1
  123. package/dist/tools/generated/drive.js +133 -124
  124. package/dist/tools/generated/driveactivity.d.ts +2 -1
  125. package/dist/tools/generated/driveactivity.js +3 -3
  126. package/dist/tools/generated/drivelabels.d.ts +2 -1
  127. package/dist/tools/generated/drivelabels.js +113 -85
  128. package/dist/tools/generated/forms.d.ts +2 -1
  129. package/dist/tools/generated/forms.js +14 -14
  130. package/dist/tools/generated/gmail.d.ts +2 -1
  131. package/dist/tools/generated/gmail.js +253 -226
  132. package/dist/tools/generated/groupsmigration.d.ts +2 -1
  133. package/dist/tools/generated/groupsmigration.js +4 -4
  134. package/dist/tools/generated/groupssettings.d.ts +2 -1
  135. package/dist/tools/generated/groupssettings.js +10 -10
  136. package/dist/tools/generated/index.d.ts +2 -1
  137. package/dist/tools/generated/index.js +2 -0
  138. package/dist/tools/generated/keep.d.ts +2 -1
  139. package/dist/tools/generated/keep.js +23 -22
  140. package/dist/tools/generated/licensing.d.ts +2 -1
  141. package/dist/tools/generated/licensing.js +54 -38
  142. package/dist/tools/generated/meet.d.ts +2 -1
  143. package/dist/tools/generated/meet.js +41 -41
  144. package/dist/tools/generated/method-map.d.ts +2 -0
  145. package/dist/tools/generated/method-map.js +894 -0
  146. package/dist/tools/generated/postmaster.d.ts +2 -1
  147. package/dist/tools/generated/postmaster.js +12 -12
  148. package/dist/tools/generated/reseller.d.ts +2 -1
  149. package/dist/tools/generated/reseller.js +69 -63
  150. package/dist/tools/generated/script.d.ts +2 -1
  151. package/dist/tools/generated/script.js +62 -52
  152. package/dist/tools/generated/searchconsole.d.ts +2 -1
  153. package/dist/tools/generated/searchconsole.js +8 -6
  154. package/dist/tools/generated/sheets.d.ts +2 -1
  155. package/dist/tools/generated/sheets.js +25 -24
  156. package/dist/tools/generated/tasks.d.ts +2 -1
  157. package/dist/tools/generated/tasks.js +15 -9
  158. package/dist/tools/generated/vault.d.ts +2 -1
  159. package/dist/tools/generated/vault.js +132 -123
  160. package/dist/tools/generated/workspaceevents.d.ts +2 -1
  161. package/dist/tools/generated/workspaceevents.js +48 -47
  162. package/dist/tools/gmail.d.ts +12 -2
  163. package/dist/tools/gmail.js +95 -51
  164. package/dist/tools/google-api.d.ts +2 -3
  165. package/dist/tools/google-api.js +76 -33
  166. package/dist/tools/meet.d.ts +10 -1
  167. package/dist/tools/meet.js +18 -11
  168. package/dist/tools/searchconsole.d.ts +2 -1
  169. package/dist/tools/searchconsole.js +27 -23
  170. package/dist/tools/sheets.d.ts +2 -1
  171. package/dist/tools/sheets.js +72 -80
  172. package/dist/tools/slides.d.ts +10 -1
  173. package/dist/tools/slides.js +23 -16
  174. package/dist/tools/tasks.d.ts +2 -1
  175. package/dist/tools/tasks.js +35 -31
  176. package/dist/trim.d.ts +26 -0
  177. package/dist/trim.js +67 -0
  178. package/dist/usage-metrics.d.ts +178 -0
  179. package/dist/usage-metrics.js +621 -0
  180. package/dist/write-control.d.ts +27 -1
  181. package/dist/write-control.js +99 -12
  182. package/package.json +34 -3
package/dist/doctor.js CHANGED
@@ -2,13 +2,19 @@ import * as fs from 'node:fs';
2
2
  import * as path from 'node:path';
3
3
  import * as readline from 'node:readline';
4
4
  import { getAccountSet } from './accounts.js';
5
- import { deriveAccountHealth } from './tools/accounts-tool.js';
5
+ import { accountHealthDepsFor, deriveAccountHealth } from './tools/accounts-tool.js';
6
+ import { isOwnerContext } from './identity.js';
6
7
  import { peekMasterKeyProvenance, deleteMasterKeyMaterial } from './master-key.js';
7
8
  import { hasToken } from './token-store.js';
8
- import { configDir } from './config-file.js';
9
- import { probeApiEnablement } from './api-probe.js';
9
+ import { configDir, loadConfigFile } from './config-file.js';
10
+ import { envValueSource } from './env-load.js';
11
+ import { reauthHint } from './reauth-hint.js';
12
+ import { describeMetricsDir, resolveUsageMetrics, sourceLabel } from './usage-metrics.js';
13
+ import { apiProbeDepsFor, probeApiEnablement } from './api-probe.js';
14
+ import { safeMessage, stringifyEnvelope } from './tools/_errors.js';
10
15
  import { resolveHttpConfig, HttpConfigError } from './http-config.js';
11
16
  import { parseOwnerEmails } from './http-transport.js';
17
+ import { hints } from './hint-provider.js';
12
18
  const MIN_NODE_MAJOR = 22;
13
19
  const DEFAULT_DEPS = {
14
20
  nodeVersion: process.versions.node,
@@ -65,9 +71,22 @@ export function apiEnableLink(api) {
65
71
  return `https://console.cloud.google.com/apis/library/${api}.googleapis.com`;
66
72
  }
67
73
  const LEGACY_ENV_KEYS = ['GOOGLE_ACCOUNTS', 'GOOGLE_OPTIONAL_SCOPES', 'GOOGLE_ADMIN_ACCOUNTS'];
68
- function sectionRuntime(deps) {
74
+ function sectionRuntime(deps, tenantScope = false) {
69
75
  const major = Number.parseInt(deps.nodeVersion.split('.')[0] ?? '0', 10);
70
76
  if (!Number.isFinite(major) || major < MIN_NODE_MAJOR) {
77
+ if (tenantScope) {
78
+ // The host version is operator infrastructure, not the tenant's (E7
79
+ // residue): no version string, and the fix is the operator's to apply.
80
+ const rendered = hints()?.render({ kind: 'operator_only', slug: 'E_NODE_TOO_OLD' });
81
+ return {
82
+ id: 1,
83
+ title: 'Runtime',
84
+ verdict: 'fail',
85
+ slug: 'E_NODE_TOO_OLD',
86
+ lines: ['Runtime below the supported version'],
87
+ hint: rendered?.hint ?? 'Tell the server operator the code E_NODE_TOO_OLD.',
88
+ };
89
+ }
71
90
  return {
72
91
  id: 1,
73
92
  title: 'Runtime',
@@ -77,23 +96,36 @@ function sectionRuntime(deps) {
77
96
  hint: `Upgrade to Node ${MIN_NODE_MAJOR} LTS or newer.`,
78
97
  };
79
98
  }
80
- return { id: 1, title: 'Runtime', verdict: 'ok', lines: [`Node.js ${deps.nodeVersion} (>= ${MIN_NODE_MAJOR})`] };
99
+ return {
100
+ id: 1,
101
+ title: 'Runtime',
102
+ verdict: 'ok',
103
+ lines: [tenantScope ? 'Runtime ok' : `Node.js ${deps.nodeVersion} (>= ${MIN_NODE_MAJOR})`],
104
+ };
81
105
  }
82
- function sectionConfig(deps, set) {
106
+ function sectionConfig(deps, set, tenantScope = false) {
83
107
  const lines = [];
84
108
  let verdict = 'ok';
85
109
  let hint;
86
110
  let slug;
87
111
  if (!set || set.aliases.length === 0) {
112
+ const tenantHint = tenantScope ? (hints()?.render({ kind: 'no_accounts' })?.hint ?? '') : undefined;
88
113
  return {
89
114
  id: 2,
90
115
  title: 'Config',
91
116
  verdict: 'fail',
92
117
  slug: 'E_NO_ACCOUNTS_CONFIGURED',
93
118
  lines: ['No accounts configured.'],
94
- hint: 'Add an account: run `npx mcp-google-multi migrate-config` or set GOOGLE_ACCOUNTS.',
119
+ ...(tenantScope
120
+ ? (tenantHint ? { hint: tenantHint } : {})
121
+ : { hint: 'Add an account: run `npx mcp-google-multi migrate-config` or set GOOGLE_ACCOUNTS.' }),
95
122
  };
96
123
  }
124
+ // The config file, process env, working directory and metrics store below
125
+ // are the operator's host, not the context's: a tenant sees its own count.
126
+ if (tenantScope) {
127
+ return { id: 2, title: 'Config', verdict: 'ok', lines: [`${set.aliases.length} account(s) configured`] };
128
+ }
97
129
  const cfgPath = path.join(configDir(), 'config.json');
98
130
  lines.push(deps.fileExists(cfgPath) ? `config.json present (${set.aliases.length} account(s))` : `config.json absent — accounts sourced from env (${set.aliases.length})`);
99
131
  const legacyEnv = LEGACY_ENV_KEYS.filter((k) => deps.env[k]);
@@ -114,8 +146,24 @@ function sectionConfig(deps, set) {
114
146
  hint = (hint ? `${hint} ` : '') + `Move it: \`mv ${envFile} ${target}\`.`;
115
147
  }
116
148
  }
149
+ lines.push(usageMetricsStatusLine(deps.env));
117
150
  return { id: 2, title: 'Config', verdict, lines, ...(hint ? { hint } : {}), ...(slug ? { slug } : {}) };
118
151
  }
152
+ /** One line, state AND source, so the people being measured can see both
153
+ * here and in `diagnose` (metrics spec section 2). Read-only. */
154
+ export function usageMetricsStatusLine(env) {
155
+ const envSrc = envValueSource('GOOGLE_USAGE_METRICS');
156
+ let configValue;
157
+ try {
158
+ configValue = loadConfigFile(undefined, 'throw')?.usageMetrics;
159
+ }
160
+ catch { /* invalid config is section 2's business, not this line's */ }
161
+ const state = resolveUsageMetrics(env, configValue, envSrc?.kind === 'file' ? envSrc.file : undefined);
162
+ if (!state.enabled)
163
+ return `local usage metrics: off ${sourceLabel(state.source)}`;
164
+ const d = describeMetricsDir(env);
165
+ return `local usage metrics: on ${sourceLabel(state.source)} -> ${d.dir} (${d.files} files, ${d.kb} KB)`;
166
+ }
119
167
  function sectionKeys(deps, aliases) {
120
168
  const provenance = deps.masterKeyProvenance();
121
169
  const tokensExist = deps.anyTokensExist(aliases);
@@ -162,7 +210,8 @@ function sectionsTokensAndScopes(deps, aliases) {
162
210
  if (scopeVerdict === 'ok')
163
211
  scopeVerdict = 'warn';
164
212
  scopeLines.push(`${alias}: ${r.callable.length} callable, ${r.requestable.length} requested-not-granted`);
165
- scopeHint = `Re-auth to grant missing scopes: \`npx mcp-google-multi auth --account ${alias}\`.`;
213
+ const rendered = hints()?.render({ kind: 'scopes_missing', account: alias });
214
+ scopeHint = rendered?.hint ?? `Re-auth to grant missing scopes. ${reauthHint(alias)}`;
166
215
  }
167
216
  else {
168
217
  scopeLines.push(`${alias}: ${r.callable.length} callable, all profile scopes granted`);
@@ -173,7 +222,7 @@ function sectionsTokensAndScopes(deps, aliases) {
173
222
  { id: 5, title: 'Scopes', verdict: scopeVerdict, lines: scopeLines, ...(scopeHint ? { hint: scopeHint } : {}), ...(scopeVerdict === 'warn' ? { slug: 'E_SCOPE_NOT_GRANTED' } : {}) },
174
223
  ];
175
224
  }
176
- async function sectionApiEnablement(deps, aliases) {
225
+ async function sectionApiEnablement(deps, aliases, tenantScope = false) {
177
226
  if (!deps.probeApi) {
178
227
  return { id: 6, title: 'API enablement', verdict: 'unknown', lines: ['Probe not run (no live account probe configured).'] };
179
228
  }
@@ -190,8 +239,15 @@ async function sectionApiEnablement(deps, aliases) {
190
239
  results = await deps.probeApi(healthy);
191
240
  }
192
241
  catch (e) {
193
- // Network / transient: WARN with the target, never crash the report.
194
- return { id: 6, title: 'API enablement', verdict: 'warn', lines: [`Probe could not complete: ${e?.message ?? e}`] };
242
+ // Network / transient: WARN with the target, never crash the report. The
243
+ // raw text can name an egress or proxy host (E7 residue): tenant scope
244
+ // drops it.
245
+ return {
246
+ id: 6,
247
+ title: 'API enablement',
248
+ verdict: 'warn',
249
+ lines: [tenantScope ? 'Probe could not complete.' : `Probe could not complete: ${e?.message ?? e}`],
250
+ };
195
251
  }
196
252
  if (results.length === 0) {
197
253
  return { id: 6, title: 'API enablement', verdict: 'unknown', lines: [`No probeable service scopes granted on "${healthy}".`] };
@@ -199,13 +255,14 @@ async function sectionApiEnablement(deps, aliases) {
199
255
  const disabled = results.filter((r) => r.notEnabled);
200
256
  const lines = results.map((r) => `${r.service}: ${r.ok ? 'enabled' : r.notEnabled ? 'NOT ENABLED' : `unknown (${r.message ?? 'error'})`}`);
201
257
  if (disabled.length > 0) {
258
+ const rendered = hints()?.render({ kind: 'apis_disabled', services: disabled.map((r) => ({ service: r.service, api: r.api })) });
202
259
  return {
203
260
  id: 6,
204
261
  title: 'API enablement',
205
262
  verdict: 'fail',
206
263
  slug: 'E_API_NOT_ENABLED',
207
264
  lines,
208
- hint: disabled.map((r) => `Enable ${r.service}: ${apiEnableLink(r.api)}`).join('\n'),
265
+ hint: rendered?.hint ?? disabled.map((r) => `Enable ${r.service}: ${apiEnableLink(r.api)}`).join('\n'),
209
266
  };
210
267
  }
211
268
  return { id: 6, title: 'API enablement', verdict: 'ok', lines: lines.length ? lines : ['(probed account, all enabled)'] };
@@ -280,21 +337,29 @@ export function overallVerdict(sections) {
280
337
  }
281
338
  return worst;
282
339
  }
283
- export async function runDiagnostics(deps = DEFAULT_DEPS) {
340
+ export async function runDiagnostics(deps = DEFAULT_DEPS, opts = {}) {
341
+ // Tenant scope omits the OPERATOR sections: §3 (key provenance = box
342
+ // infrastructure) and §7 (its owner-gate lines print MCP_OWNER_EMAILS
343
+ // values — other people's addresses from a tenant's seat), and trims §2 to
344
+ // the context's own account count.
345
+ const tenantScope = opts.scope === 'tenant';
284
346
  const sections = [];
285
- sections.push(sectionRuntime(deps));
347
+ sections.push(sectionRuntime(deps, tenantScope));
286
348
  const set = deps.accountSet();
287
- sections.push(sectionConfig(deps, set));
349
+ sections.push(sectionConfig(deps, set, tenantScope));
288
350
  const aliases = set?.aliases ?? [];
289
- sections.push(sectionKeys(deps, aliases));
351
+ if (!tenantScope)
352
+ sections.push(sectionKeys(deps, aliases));
290
353
  if (aliases.length > 0) {
291
354
  const [tokens, scopes] = sectionsTokensAndScopes(deps, aliases);
292
355
  sections.push(tokens, scopes);
293
- sections.push(await sectionApiEnablement(deps, aliases));
356
+ sections.push(await sectionApiEnablement(deps, aliases, tenantScope));
357
+ }
358
+ if (!tenantScope) {
359
+ const http = await sectionHttp(deps, aliases);
360
+ if (http)
361
+ sections.push(http);
294
362
  }
295
- const http = await sectionHttp(deps, aliases);
296
- if (http)
297
- sections.push(http);
298
363
  return { verdict: overallVerdict(sections), sections };
299
364
  }
300
365
  // --- skins -----------------------------------------------------------------
@@ -314,9 +379,35 @@ export function renderDoctorText(report) {
314
379
  out.push(`Overall: ${report.verdict.toUpperCase()}`);
315
380
  return out.join('\n');
316
381
  }
317
- /** Mask the local-part of an email so a report never carries a full address (BR8). */
382
+ const EMAIL_LOCAL_CHAR = /[A-Za-z0-9._%+-]/;
383
+ const EMAIL_DOMAIN_CHAR = /[A-Za-z0-9.-]/;
384
+ /** Mask the local-part of an email so a report never carries a full address
385
+ * (BR8). A linear scan, not a regex: the `local* @domain` pattern backtracks
386
+ * polynomially on long local-charset runs without an @ (CodeQL
387
+ * js/polynomial-redos), and report text can embed arbitrary error strings. */
318
388
  function maskEmails(text) {
319
- return text.replace(/([A-Za-z0-9._%+-])[A-Za-z0-9._%+-]*(@[A-Za-z0-9.-]+)/g, '$1***$2');
389
+ let out = '';
390
+ let i = 0;
391
+ while (i < text.length) {
392
+ if (text[i] === '@') {
393
+ let j = i + 1;
394
+ while (j < text.length && EMAIL_DOMAIN_CHAR.test(text[j]))
395
+ j += 1;
396
+ let k = out.length;
397
+ while (k > 0 && EMAIL_LOCAL_CHAR.test(out[k - 1]))
398
+ k -= 1;
399
+ if (j > i + 1 && k < out.length) {
400
+ // keep the first local char, mask the rest ('*' is outside the local
401
+ // charset, so a masked run can never be re-masked by a later @)
402
+ out = `${out.slice(0, k + 1)}***${text.slice(i, j)}`;
403
+ i = j;
404
+ continue;
405
+ }
406
+ }
407
+ out += text[i];
408
+ i += 1;
409
+ }
410
+ return out;
320
411
  }
321
412
  /** Redacted, paste-ready bug report (BR8): verdicts + provenance labels + token
322
413
  * statuses + slugs; NO token values, secrets, keys, or full email addresses. */
@@ -337,20 +428,53 @@ export function exitCodeFor(report, strict) {
337
428
  return 1;
338
429
  return 0;
339
430
  }
431
+ /** The engine's account, token and probe reads bound to one context, so a
432
+ * report never shows (or probes with) another context's accounts. */
433
+ function diagnosticsDepsFor(ctx) {
434
+ const health = accountHealthDepsFor(ctx.tokenStore, () => ctx.accounts);
435
+ const probe = apiProbeDepsFor(ctx.tokenStore.readToken, ctx.getClient);
436
+ return {
437
+ ...DEFAULT_DEPS,
438
+ accountSet: () => {
439
+ try {
440
+ return ctx.accounts;
441
+ }
442
+ catch {
443
+ return null;
444
+ }
445
+ },
446
+ accountHealth: (alias) => deriveAccountHealth(alias, health),
447
+ anyTokensExist: (aliases) => aliases.some((a) => ctx.tokenStore.hasToken(a)),
448
+ probeApi: (alias) => probeApiEnablement(alias, probe),
449
+ };
450
+ }
340
451
  /** Agent-callable structured health report (read-only). Mirrors `doctor`'s
341
- * engine; NOT alwaysLoad (the agent asks for it when diagnosing). */
342
- export function registerDiagnoseTool(registry) {
343
- registry.registerTool('diagnose', {
452
+ * engine. Registered as a META tool, like `account_list`: it introspects this
453
+ * server rather than Google data, and as a normal tool it became a service of
454
+ * its own with no `{service}_discover` to reveal it (discover tools are built
455
+ * from already-registered services, and this runs after that), so it was
456
+ * advertised only once something else expanded the surface. The README sends
457
+ * people here when they are stuck, so it has to be findable. */
458
+ export function registerDiagnoseTool(registry, ctx) {
459
+ // A non-owner context gets the tenant-scoped report; only the owner context
460
+ // (or the context-free CLI surface) keeps the full operator report.
461
+ const scope = ctx && !isOwnerContext(ctx) ? 'tenant' : 'operator';
462
+ const deps = ctx ? diagnosticsDepsFor(ctx) : DEFAULT_DEPS;
463
+ registry.registerMeta('diagnose', {
344
464
  annotations: { readOnlyHint: true, openWorldHint: true },
345
465
  description: 'Health report for this server: runtime, config, keys, per-account token status, scope grants, and API enablement. Read-only; returns copy-pasteable fixes for anything wrong. Call this to diagnose auth/config failures.',
346
466
  inputSchema: {},
347
467
  }, async () => {
348
468
  try {
349
- const result = await runDiagnostics();
469
+ const result = await runDiagnostics(deps, { scope });
350
470
  return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
351
471
  }
352
472
  catch (e) {
353
- return { content: [{ type: 'text', text: JSON.stringify({ error: 'diagnose_failed', message: e?.message ?? String(e) }) }], isError: true };
473
+ return { content: [{ type: 'text', text: stringifyEnvelope({
474
+ error: 'diagnose_failed',
475
+ message: safeMessage(e),
476
+ retriable: false,
477
+ }) }], isError: true };
354
478
  }
355
479
  });
356
480
  }
@@ -9,3 +9,14 @@ export interface EnvLoadPaths {
9
9
  configDir?: string;
10
10
  }
11
11
  export declare function loadEnvFiles(paths?: EnvLoadPaths): EnvLoadResult;
12
+ /**
13
+ * Which layer supplied `key`: the real process env, or the first loaded .env
14
+ * file defining it (autoload never overwrites, so first wins). undefined when
15
+ * the key is unset. Powers self-announcing enablement sources (usage metrics).
16
+ */
17
+ export declare function envValueSource(key: string): {
18
+ kind: 'process';
19
+ } | {
20
+ kind: 'file';
21
+ file: string;
22
+ } | undefined;
package/dist/env-load.js CHANGED
@@ -1,4 +1,4 @@
1
- import { existsSync } from 'node:fs';
1
+ import { existsSync, readFileSync } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { homedir } from 'node:os';
4
4
  import { fileURLToPath } from 'node:url';
@@ -48,5 +48,27 @@ export function loadEnvFiles(paths = {}) {
48
48
  }
49
49
  for (const [k, v] of boot)
50
50
  process.env[k] = v;
51
+ lastLoad = { bootKeys: new Set(boot.keys()), loaded };
51
52
  return { loaded, searched: candidates };
52
53
  }
54
+ let lastLoad;
55
+ /**
56
+ * Which layer supplied `key`: the real process env, or the first loaded .env
57
+ * file defining it (autoload never overwrites, so first wins). undefined when
58
+ * the key is unset. Powers self-announcing enablement sources (usage metrics).
59
+ */
60
+ export function envValueSource(key) {
61
+ if (process.env[key] === undefined)
62
+ return undefined;
63
+ if (!lastLoad || lastLoad.bootKeys.has(key))
64
+ return { kind: 'process' };
65
+ const re = new RegExp(`^\\s*${key}\\s*=`, 'm');
66
+ for (const p of lastLoad.loaded) {
67
+ try {
68
+ if (re.test(readFileSync(p, 'utf-8')))
69
+ return { kind: 'file', file: p };
70
+ }
71
+ catch { /* file vanished since load: fall through */ }
72
+ }
73
+ return { kind: 'process' };
74
+ }
@@ -1,4 +1,5 @@
1
1
  import { getClient } from './client.js';
2
+ import { type ScopeSetDeps } from './scope-observability.js';
2
3
  export declare const MAX_RESPONSE_CHARS = 100000;
3
4
  export type QueryValue = string | number | boolean;
4
5
  export type QueryParams = Record<string, QueryValue | QueryValue[]>;
@@ -13,6 +14,8 @@ export interface ApiMethodRef {
13
14
  }
14
15
  export interface ExecuteDeps {
15
16
  getClientFn?: typeof getClient;
17
+ /** Token + profile view behind a 403 scope hint; absent = the single owner. */
18
+ scopeDeps?: ScopeSetDeps;
16
19
  }
17
20
  export interface ExecuteArgs {
18
21
  account: string;
package/dist/executor.js CHANGED
@@ -1,7 +1,10 @@
1
1
  import { getClient } from './client.js';
2
+ import { sliceEncoded } from './trim.js';
2
3
  import { expandPath, isGoogleApiUrl } from './discovery-client.js';
3
4
  import { handleGoogleApiError } from './tools/_errors.js';
4
5
  import { scopeHintForMethod } from './scope-observability.js';
6
+ import { checkOutboundForMethod } from './outbound-allowlist.js';
7
+ import { hints } from './hint-provider.js';
5
8
  export const MAX_RESPONSE_CHARS = 100_000;
6
9
  export function jsonResult(payload, isError = false) {
7
10
  const base = { content: [{ type: 'text', text: JSON.stringify(payload) }] };
@@ -29,6 +32,11 @@ export function resolveRequestBody(httpMethod, body) {
29
32
  return body ?? undefined;
30
33
  }
31
34
  export async function executeApiMethod(method, args, deps = {}) {
35
+ // Outbound allowlist: no-op when off; with it active, structured bodies are
36
+ // inspected for recipient fields and raw-compose methods are refused.
37
+ const outbound = checkOutboundForMethod(method.id, args.body, args.account);
38
+ if (outbound)
39
+ return outbound;
32
40
  if (args.queryParams?.alt === 'media') {
33
41
  return jsonResult({
34
42
  error: 'binary_unsupported',
@@ -63,10 +71,11 @@ export async function executeApiMethod(method, args, deps = {}) {
63
71
  }, true);
64
72
  }
65
73
  if (!isGoogleApiUrl(url)) {
74
+ const rendered = hints()?.render({ kind: 'untrusted_host' });
66
75
  return jsonResult({
67
76
  error: 'untrusted_host',
68
77
  message: `Refusing to send credentials to a non-googleapis.com host for "${method.id}".`,
69
- hint: 'The discovery cache may be corrupt; delete DISCOVERY_CACHE_PATH and retry.',
78
+ hint: rendered?.hint ?? 'The discovery cache may be corrupt; delete DISCOVERY_CACHE_PATH and retry.',
70
79
  retriable: false,
71
80
  account: args.account,
72
81
  }, true);
@@ -82,16 +91,20 @@ export async function executeApiMethod(method, args, deps = {}) {
82
91
  });
83
92
  const text = JSON.stringify(res.data ?? null);
84
93
  if (text.length > MAX_RESPONSE_CHARS) {
94
+ // Budget the ENCODED head: jsonResult re-stringifies it, so every quote
95
+ // and backslash inside doubles. Slicing raw characters made the emitted
96
+ // result exceed the cap this tool advertises, by up to 15 percent on a
97
+ // quote-dense listing.
85
98
  return jsonResult({
86
99
  truncated: true,
87
100
  totalChars: text.length,
88
- head: text.slice(0, MAX_RESPONSE_CHARS),
101
+ head: sliceEncoded(text, MAX_RESPONSE_CHARS),
89
102
  hint: 'Narrow the request (fields mask, pageSize) to get complete JSON.',
90
103
  });
91
104
  }
92
105
  return { content: [{ type: 'text', text }] };
93
106
  }
94
107
  catch (error) {
95
- return handleGoogleApiError(error, args.account, undefined, () => method.scopes?.length ? scopeHintForMethod(method.scopes, args.account) : null);
108
+ return handleGoogleApiError(error, args.account, undefined, () => method.scopes?.length ? scopeHintForMethod(method.scopes, args.account, deps.scopeDeps) : null);
96
109
  }
97
110
  }
package/dist/fanout.d.ts CHANGED
@@ -1,6 +1,14 @@
1
1
  import { z } from 'zod';
2
2
  export declare const CSV_RE: RegExp;
3
- export declare function fanoutAccountField(description: string): z.ZodType;
3
+ export declare function fanoutAccountField(description: string, aliases: () => readonly string[]): z.ZodType;
4
+ /** '*' over an empty account set would fan out to nothing and report success. */
5
+ export declare function noAccountsResult(): {
6
+ content: {
7
+ type: "text";
8
+ text: string;
9
+ }[];
10
+ isError: true;
11
+ };
4
12
  export type AccountSelector = {
5
13
  ok: true;
6
14
  fanout: boolean;
package/dist/fanout.js CHANGED
@@ -1,21 +1,59 @@
1
1
  import { z } from 'zod';
2
- import { ACCOUNTS, getAccountSet } from './accounts.js';
2
+ import { getAccountSet, liveAccountCheck, unknownAliasMessage } from './accounts.js';
3
+ import { echoName, echoNames, MAX_SUGGESTED_KEYS } from './arg-strict.js';
4
+ import { hints } from './hint-provider.js';
3
5
  export const CSV_RE = /^[a-zA-Z0-9_-]+(\s*,\s*[a-zA-Z0-9_-]+)+$/;
4
6
  const FANOUT_CONCURRENCY = 5;
5
- export function fanoutAccountField(description) {
6
- const csvExample = ACCOUNTS.length > 1 ? `; or a CSV subset like "${ACCOUNTS.slice(0, 2).join(',')}"` : '';
7
+ // `aliases` is required (no global default): the field is baked into a
8
+ // registry's inputSchema, so it must read THAT registry's account set or a
9
+ // '*' would advertise and accept another registry's aliases. It is a getter:
10
+ // the set is read at parse time, so an alias added mid-session (account_add,
11
+ // a tenant link) is valid on tools registered before it existed.
12
+ export function fanoutAccountField(description, aliases) {
13
+ const boot = aliases();
14
+ const csvExample = boot.length > 1 ? `; or a CSV subset like "${boot.slice(0, 2).join(',')}"` : '';
15
+ // The union's OWN error only fires when every branch aborts at the type
16
+ // check (a non-string). For a string, zod surfaces the single non-aborted
17
+ // branch verbatim, which is the CSV regex, so a mistyped alias used to read
18
+ // as "Invalid string: must match pattern /^[a-zA-Z0-9_-]+(,...)/" and never
19
+ // named an alias. Hence the same message on BOTH.
20
+ const bad = () => unknownAliasMessage(aliases(), true);
7
21
  return z
8
- // '*' first so the tuple is statically non-empty even when ACCOUNTS is empty
9
- // (a fresh install): z.enum requires [string, ...string[]].
10
- .union([z.enum(['*', ...ACCOUNTS]), z.string().regex(CSV_RE)])
22
+ // The selector branch stays first: tools/list injects the live
23
+ // '*' + alias enum into it (registry withLiveAccountEnum).
24
+ .union([z.string().check(liveAccountCheck(aliases, true)), z.string().regex(CSV_RE, { error: bad })], { error: bad })
11
25
  .optional()
12
26
  .describe(`${description}; "*" = all accounts${csvExample}; omit for the default account`);
13
27
  }
28
+ /** '*' over an empty account set would fan out to nothing and report success. */
29
+ export function noAccountsResult() {
30
+ return {
31
+ content: [
32
+ {
33
+ type: 'text',
34
+ text: JSON.stringify({
35
+ error: 'validation_error',
36
+ message: 'No Google account is configured, so "*" selects nothing.',
37
+ hint: unknownAliasMessage([]),
38
+ retriable: false,
39
+ account: '*',
40
+ }),
41
+ },
42
+ ],
43
+ isError: true,
44
+ };
45
+ }
14
46
  export function parseAccountSelector(value, accounts = getAccountSet().aliases) {
15
47
  if (value === '*')
16
48
  return { ok: true, fanout: true, aliases: [...accounts] };
17
- if (!value.includes(','))
18
- return { ok: true, fanout: false, aliases: [value] };
49
+ // A single alias used to skip validation entirely and reach getClient, whose
50
+ // throw landed on the mapper's floor as an unclassified upstream_error. Same
51
+ // check and same envelope wherever the alias was typed.
52
+ if (!value.includes(',')) {
53
+ return accounts.includes(value)
54
+ ? { ok: true, fanout: false, aliases: [value] }
55
+ : { ok: false, invalid: [value] };
56
+ }
19
57
  const seen = new Set();
20
58
  const aliases = [];
21
59
  const invalid = [];
@@ -30,7 +68,9 @@ export function parseAccountSelector(value, accounts = getAccountSet().aliases)
30
68
  }
31
69
  if (invalid.length > 0)
32
70
  return { ok: false, invalid };
33
- return { ok: true, fanout: aliases.length > 1, aliases };
71
+ // Keyed on the CSV FORM, not the deduped count: "a,a" asked for the merged
72
+ // multi-account envelope and used to get a bare single-account payload.
73
+ return { ok: true, fanout: true, aliases };
34
74
  }
35
75
  export function invalidAccountsResult(invalid, accounts = getAccountSet().aliases) {
36
76
  return {
@@ -39,9 +79,11 @@ export function invalidAccountsResult(invalid, accounts = getAccountSet().aliase
39
79
  type: 'text',
40
80
  text: JSON.stringify({
41
81
  error: 'validation_error',
42
- message: `Unknown account alias(es): ${invalid.join(', ')}.`,
43
- hint: `Valid aliases: ${accounts.join(', ')}; or "*" for all accounts.`,
82
+ // The caller's CSV can hold any number of tokens: echo a prefix.
83
+ message: `Unknown account alias(es): ${echoNames(invalid)}.`,
84
+ hint: unknownAliasMessage(accounts, true),
44
85
  retriable: false,
86
+ account: invalid.slice(0, MAX_SUGGESTED_KEYS).map(echoName).join(','),
45
87
  }),
46
88
  },
47
89
  ],
@@ -72,17 +114,44 @@ export async function runFanout(handler, args, aliases) {
72
114
  results[i] = res?.isError ? { account, ok: false, error: payload } : { account, ok: true, data: payload };
73
115
  }
74
116
  catch (err) {
117
+ const rendered = hints()?.render({ kind: 'internal', account });
75
118
  results[i] = {
76
119
  account,
77
120
  ok: false,
78
- error: { error: 'internal', message: err.message, retriable: false, account },
121
+ error: {
122
+ error: 'internal',
123
+ message: rendered?.message ?? err.message,
124
+ hint: rendered?.hint,
125
+ retriable: false,
126
+ account,
127
+ },
79
128
  };
80
129
  }
81
130
  }
82
131
  };
83
132
  await Promise.all(Array.from({ length: Math.min(FANOUT_CONCURRENCY, aliases.length) }, () => worker()));
84
133
  const failed = results.filter((r) => !r.ok).length;
134
+ if (failed === results.length && results.length > 0) {
135
+ // Every account failed, so this IS an error result, and used to carry
136
+ // `isError` with no top-level error, hint or retriable: the agent saw a
137
+ // successful-looking object flagged as an error, and metrics bucketed it
138
+ // as `other`. Hoist a real envelope, keeping the per-account detail.
139
+ const slugs = [...new Set(results.map((r) => r.error?.error ?? 'internal'))];
140
+ const hints = [...new Set(results.map((r) => r.error?.hint).filter(Boolean))];
141
+ const retriable = results.every((r) => r.error?.retriable === true);
142
+ return {
143
+ content: [{ type: 'text', text: JSON.stringify({
144
+ error: 'fanout_failed',
145
+ message: `All ${results.length} accounts failed: ${slugs.join(', ')}. Per-account detail is in results.`,
146
+ hint: hints.length === 1 ? hints[0] : 'Each entry in results carries its own error and hint; they differ per account.',
147
+ retriable,
148
+ account: aliases.join(','),
149
+ results,
150
+ partial: true,
151
+ }) }],
152
+ isError: true,
153
+ };
154
+ }
85
155
  const body = { results, partial: failed > 0 };
86
- const out = { content: [{ type: 'text', text: JSON.stringify(body) }] };
87
- return failed === results.length ? { ...out, isError: true } : out;
156
+ return { content: [{ type: 'text', text: JSON.stringify(body) }] };
88
157
  }
@@ -1,3 +1,14 @@
1
+ /** Which process instance holds a lock: PID namespace id, start time in
2
+ * clock ticks since boot, and a boot id prefix. A part this process cannot
3
+ * read is `host` or `0` (all three without /proc). */
4
+ interface LockIdentity {
5
+ ns: string;
6
+ start: string;
7
+ boot: string;
8
+ }
9
+ /** Test hook: act as a process with this identity (undefined restores the real one). */
10
+ export declare function __setLockIdentityForTest(identity?: LockIdentity): void;
1
11
  export declare function withFileLock<T>(absPath: string, fn: () => T, label?: string): T;
2
12
  export declare function atomicWriteFileSync(absPath: string, contents: string, mode?: number): void;
3
13
  export declare function atomicWriteWithLock(absPath: string, contents: string, mode?: number): void;
14
+ export {};