@mcp-z/mcp-drive 1.0.8 → 1.0.10

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 (97) hide show
  1. package/dist/cjs/constants.js.map +1 -1
  2. package/dist/cjs/index.js +10 -24
  3. package/dist/cjs/index.js.map +1 -1
  4. package/dist/cjs/lib/create-store.js +2 -5
  5. package/dist/cjs/lib/create-store.js.map +1 -1
  6. package/dist/cjs/lib/file-streaming.d.cts +35 -0
  7. package/dist/cjs/lib/file-streaming.d.ts +35 -0
  8. package/dist/cjs/lib/file-streaming.js +289 -0
  9. package/dist/cjs/lib/file-streaming.js.map +1 -0
  10. package/dist/cjs/lib/query-builder.js.map +1 -1
  11. package/dist/cjs/mcp/index.js +8 -19
  12. package/dist/cjs/mcp/index.js.map +1 -1
  13. package/dist/cjs/mcp/prompts/index.js.map +1 -1
  14. package/dist/cjs/mcp/prompts/organize-files.js +3 -6
  15. package/dist/cjs/mcp/prompts/organize-files.js.map +1 -1
  16. package/dist/cjs/mcp/prompts/query-syntax.js +3 -6
  17. package/dist/cjs/mcp/prompts/query-syntax.js.map +1 -1
  18. package/dist/cjs/mcp/resources/file.js +3 -6
  19. package/dist/cjs/mcp/resources/file.js.map +1 -1
  20. package/dist/cjs/mcp/resources/index.js.map +1 -1
  21. package/dist/cjs/mcp/tools/file-move-to-trash.js +5 -11
  22. package/dist/cjs/mcp/tools/file-move-to-trash.js.map +1 -1
  23. package/dist/cjs/mcp/tools/file-move.js +11 -18
  24. package/dist/cjs/mcp/tools/file-move.js.map +1 -1
  25. package/dist/cjs/mcp/tools/file-upload.d.cts +69 -0
  26. package/dist/cjs/mcp/tools/file-upload.d.ts +69 -0
  27. package/dist/cjs/mcp/tools/file-upload.js +387 -0
  28. package/dist/cjs/mcp/tools/file-upload.js.map +1 -0
  29. package/dist/cjs/mcp/tools/files-search.js +7 -14
  30. package/dist/cjs/mcp/tools/files-search.js.map +1 -1
  31. package/dist/cjs/mcp/tools/folder-contents.js +7 -14
  32. package/dist/cjs/mcp/tools/folder-contents.js.map +1 -1
  33. package/dist/cjs/mcp/tools/folder-create.js +5 -11
  34. package/dist/cjs/mcp/tools/folder-create.js.map +1 -1
  35. package/dist/cjs/mcp/tools/folder-path.js +4 -8
  36. package/dist/cjs/mcp/tools/folder-path.js.map +1 -1
  37. package/dist/cjs/mcp/tools/folder-search.js +19 -24
  38. package/dist/cjs/mcp/tools/folder-search.js.map +1 -1
  39. package/dist/cjs/mcp/tools/index.d.cts +1 -0
  40. package/dist/cjs/mcp/tools/index.d.ts +1 -0
  41. package/dist/cjs/mcp/tools/index.js +4 -0
  42. package/dist/cjs/mcp/tools/index.js.map +1 -1
  43. package/dist/cjs/schemas/drive-query-schema.js +2 -3
  44. package/dist/cjs/schemas/drive-query-schema.js.map +1 -1
  45. package/dist/cjs/schemas/drive-validation.js.map +1 -1
  46. package/dist/cjs/schemas/index.js.map +1 -1
  47. package/dist/cjs/setup/config.js +11 -25
  48. package/dist/cjs/setup/config.js.map +1 -1
  49. package/dist/cjs/setup/http.js +15 -16
  50. package/dist/cjs/setup/http.js.map +1 -1
  51. package/dist/cjs/setup/index.js.map +1 -1
  52. package/dist/cjs/setup/oauth-google.js +9 -16
  53. package/dist/cjs/setup/oauth-google.js.map +1 -1
  54. package/dist/cjs/setup/runtime.d.cts +1 -1
  55. package/dist/cjs/setup/runtime.d.ts +1 -1
  56. package/dist/cjs/setup/runtime.js +11 -25
  57. package/dist/cjs/setup/runtime.js.map +1 -1
  58. package/dist/cjs/setup/stdio.js +15 -16
  59. package/dist/cjs/setup/stdio.js.map +1 -1
  60. package/dist/esm/constants.js.map +1 -1
  61. package/dist/esm/index.js.map +1 -1
  62. package/dist/esm/lib/create-store.js.map +1 -1
  63. package/dist/esm/lib/file-streaming.d.ts +35 -0
  64. package/dist/esm/lib/file-streaming.js +111 -0
  65. package/dist/esm/lib/file-streaming.js.map +1 -0
  66. package/dist/esm/lib/query-builder.js.map +1 -1
  67. package/dist/esm/mcp/index.js.map +1 -1
  68. package/dist/esm/mcp/prompts/index.js.map +1 -1
  69. package/dist/esm/mcp/prompts/organize-files.js.map +1 -1
  70. package/dist/esm/mcp/prompts/query-syntax.js.map +1 -1
  71. package/dist/esm/mcp/resources/file.js.map +1 -1
  72. package/dist/esm/mcp/resources/index.js.map +1 -1
  73. package/dist/esm/mcp/tools/file-move-to-trash.js.map +1 -1
  74. package/dist/esm/mcp/tools/file-move.js.map +1 -1
  75. package/dist/esm/mcp/tools/file-upload.d.ts +69 -0
  76. package/dist/esm/mcp/tools/file-upload.js +163 -0
  77. package/dist/esm/mcp/tools/file-upload.js.map +1 -0
  78. package/dist/esm/mcp/tools/files-search.js.map +1 -1
  79. package/dist/esm/mcp/tools/folder-contents.js.map +1 -1
  80. package/dist/esm/mcp/tools/folder-create.js.map +1 -1
  81. package/dist/esm/mcp/tools/folder-path.js.map +1 -1
  82. package/dist/esm/mcp/tools/folder-search.js.map +1 -1
  83. package/dist/esm/mcp/tools/index.d.ts +1 -0
  84. package/dist/esm/mcp/tools/index.js +1 -0
  85. package/dist/esm/mcp/tools/index.js.map +1 -1
  86. package/dist/esm/schemas/drive-query-schema.js.map +1 -1
  87. package/dist/esm/schemas/drive-validation.js.map +1 -1
  88. package/dist/esm/schemas/index.js.map +1 -1
  89. package/dist/esm/setup/config.js.map +1 -1
  90. package/dist/esm/setup/http.js.map +1 -1
  91. package/dist/esm/setup/index.js.map +1 -1
  92. package/dist/esm/setup/oauth-google.js.map +1 -1
  93. package/dist/esm/setup/runtime.d.ts +1 -1
  94. package/dist/esm/setup/runtime.js.map +1 -1
  95. package/dist/esm/setup/stdio.js.map +1 -1
  96. package/dist/esm/types.js.map +1 -1
  97. package/package.json +10 -6
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/mcp-drive/src/index.ts"],"sourcesContent":["import { createConfig, handleVersionHelp } from './setup/config.ts';\nimport { createHTTPServer } from './setup/http.ts';\nimport { createStdioServer } from './setup/stdio.ts';\nimport type { ServerConfig } from './types.ts';\n\nexport { GOOGLE_SCOPE } from './constants.ts';\nexport * as mcp from './mcp/index.ts';\nexport * as schemas from './schemas/index.ts';\nexport * as setup from './setup/index.ts';\nexport * from './types.ts';\n\nexport async function startServer(config: ServerConfig): Promise<void> {\n const { logger, close } = config.transport.type === 'stdio' ? await createStdioServer(config) : await createHTTPServer(config);\n\n process.on('SIGINT', async () => {\n await close();\n process.exit(0);\n });\n\n logger.info(`Server started with ${config.transport.type} transport`);\n await new Promise(() => {});\n}\n\nexport default async function main(): Promise<void> {\n // Check for help/version flags FIRST, before config parsing\n const versionHelpResult = handleVersionHelp(process.argv);\n if (versionHelpResult.handled) {\n console.log(versionHelpResult.output);\n process.exit(0);\n }\n\n // Only parse config if no help/version flags\n const config = createConfig();\n await startServer(config);\n}\n\nif (process.argv[1] === new URL(import.meta.url).pathname) {\n main();\n}\n"],"names":["createConfig","handleVersionHelp","createHTTPServer","createStdioServer","GOOGLE_SCOPE","mcp","schemas","setup","startServer","config","logger","close","transport","type","process","on","exit","info","Promise","main","versionHelpResult","argv","handled","console","log","output","URL","url","pathname"],"mappings":"AAAA,SAASA,YAAY,EAAEC,iBAAiB,QAAQ,oBAAoB;AACpE,SAASC,gBAAgB,QAAQ,kBAAkB;AACnD,SAASC,iBAAiB,QAAQ,mBAAmB;AAGrD,SAASC,YAAY,QAAQ,iBAAiB;AAC9C,sBAAqB,iBAAiB;AAAtC,SAAO,QAAKC,GAAG,GAAuB;AACtC,0BAAyB,qBAAqB;AAA9C,SAAO,YAAKC,OAAO,GAA2B;AAC9C,wBAAuB,mBAAmB;AAA1C,SAAO,UAAKC,KAAK,GAAyB;AAC1C,cAAc,aAAa;AAE3B,OAAO,eAAeC,YAAYC,MAAoB;IACpD,MAAM,EAAEC,MAAM,EAAEC,KAAK,EAAE,GAAGF,OAAOG,SAAS,CAACC,IAAI,KAAK,UAAU,MAAMV,kBAAkBM,UAAU,MAAMP,iBAAiBO;IAEvHK,QAAQC,EAAE,CAAC,UAAU;QACnB,MAAMJ;QACNG,QAAQE,IAAI,CAAC;IACf;IAEAN,OAAOO,IAAI,CAAC,CAAC,oBAAoB,EAAER,OAAOG,SAAS,CAACC,IAAI,CAAC,UAAU,CAAC;IACpE,MAAM,IAAIK,QAAQ,KAAO;AAC3B;AAEA,eAAe,eAAeC;IAC5B,4DAA4D;IAC5D,MAAMC,oBAAoBnB,kBAAkBa,QAAQO,IAAI;IACxD,IAAID,kBAAkBE,OAAO,EAAE;QAC7BC,QAAQC,GAAG,CAACJ,kBAAkBK,MAAM;QACpCX,QAAQE,IAAI,CAAC;IACf;IAEA,6CAA6C;IAC7C,MAAMP,SAAST;IACf,MAAMQ,YAAYC;AACpB;AAEA,IAAIK,QAAQO,IAAI,CAAC,EAAE,KAAK,IAAIK,IAAI,YAAYC,GAAG,EAAEC,QAAQ,EAAE;IACzDT;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/index.ts"],"sourcesContent":["import { createConfig, handleVersionHelp } from './setup/config.ts';\nimport { createHTTPServer } from './setup/http.ts';\nimport { createStdioServer } from './setup/stdio.ts';\nimport type { ServerConfig } from './types.ts';\n\nexport { GOOGLE_SCOPE } from './constants.ts';\nexport * as mcp from './mcp/index.ts';\nexport * as schemas from './schemas/index.ts';\nexport * as setup from './setup/index.ts';\nexport * from './types.ts';\n\nexport async function startServer(config: ServerConfig): Promise<void> {\n const { logger, close } = config.transport.type === 'stdio' ? await createStdioServer(config) : await createHTTPServer(config);\n\n process.on('SIGINT', async () => {\n await close();\n process.exit(0);\n });\n\n logger.info(`Server started with ${config.transport.type} transport`);\n await new Promise(() => {});\n}\n\nexport default async function main(): Promise<void> {\n // Check for help/version flags FIRST, before config parsing\n const versionHelpResult = handleVersionHelp(process.argv);\n if (versionHelpResult.handled) {\n console.log(versionHelpResult.output);\n process.exit(0);\n }\n\n // Only parse config if no help/version flags\n const config = createConfig();\n await startServer(config);\n}\n\nif (process.argv[1] === new URL(import.meta.url).pathname) {\n main();\n}\n"],"names":["createConfig","handleVersionHelp","createHTTPServer","createStdioServer","GOOGLE_SCOPE","mcp","schemas","setup","startServer","config","logger","close","transport","type","process","on","exit","info","Promise","main","versionHelpResult","argv","handled","console","log","output","URL","url","pathname"],"mappings":"AAAA,SAASA,YAAY,EAAEC,iBAAiB,QAAQ,oBAAoB;AACpE,SAASC,gBAAgB,QAAQ,kBAAkB;AACnD,SAASC,iBAAiB,QAAQ,mBAAmB;AAGrD,SAASC,YAAY,QAAQ,iBAAiB;AAC9C,sBAAqB,iBAAiB;AAAtC,SAAO,QAAKC,GAAG,GAAuB;AACtC,0BAAyB,qBAAqB;AAA9C,SAAO,YAAKC,OAAO,GAA2B;AAC9C,wBAAuB,mBAAmB;AAA1C,SAAO,UAAKC,KAAK,GAAyB;AAC1C,cAAc,aAAa;AAE3B,OAAO,eAAeC,YAAYC,MAAoB;IACpD,MAAM,EAAEC,MAAM,EAAEC,KAAK,EAAE,GAAGF,OAAOG,SAAS,CAACC,IAAI,KAAK,UAAU,MAAMV,kBAAkBM,UAAU,MAAMP,iBAAiBO;IAEvHK,QAAQC,EAAE,CAAC,UAAU;QACnB,MAAMJ;QACNG,QAAQE,IAAI,CAAC;IACf;IAEAN,OAAOO,IAAI,CAAC,CAAC,oBAAoB,EAAER,OAAOG,SAAS,CAACC,IAAI,CAAC,UAAU,CAAC;IACpE,MAAM,IAAIK,QAAQ,KAAO;AAC3B;AAEA,eAAe,eAAeC;IAC5B,4DAA4D;IAC5D,MAAMC,oBAAoBnB,kBAAkBa,QAAQO,IAAI;IACxD,IAAID,kBAAkBE,OAAO,EAAE;QAC7BC,QAAQC,GAAG,CAACJ,kBAAkBK,MAAM;QACpCX,QAAQE,IAAI,CAAC;IACf;IAEA,6CAA6C;IAC7C,MAAMP,SAAST;IACf,MAAMQ,YAAYC;AACpB;AAEA,IAAIK,QAAQO,IAAI,CAAC,EAAE,KAAK,IAAIK,IAAI,YAAYC,GAAG,EAAEC,QAAQ,EAAE;IACzDT;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/mcp-drive/src/lib/create-store.ts"],"sourcesContent":["import type Keyv from 'keyv';\nimport keyvRegistry from 'keyv-registry';\n\nexport default async function createStore<T>(uri: string): Promise<Keyv<T>> {\n const store = await keyvRegistry<T>(uri);\n if (!store) throw new Error(`Failed to create store for URI: ${uri}`);\n return store;\n}\n"],"names":["keyvRegistry","createStore","uri","store","Error"],"mappings":"AACA,OAAOA,kBAAkB,gBAAgB;AAEzC,eAAe,eAAeC,YAAeC,GAAW;IACtD,MAAMC,QAAQ,MAAMH,aAAgBE;IACpC,IAAI,CAACC,OAAO,MAAM,IAAIC,MAAM,CAAC,gCAAgC,EAAEF,KAAK;IACpE,OAAOC;AACT"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/lib/create-store.ts"],"sourcesContent":["import type Keyv from 'keyv';\nimport keyvRegistry from 'keyv-registry';\n\nexport default async function createStore<T>(uri: string): Promise<Keyv<T>> {\n const store = await keyvRegistry<T>(uri);\n if (!store) throw new Error(`Failed to create store for URI: ${uri}`);\n return store;\n}\n"],"names":["keyvRegistry","createStore","uri","store","Error"],"mappings":"AACA,OAAOA,kBAAkB,gBAAgB;AAEzC,eAAe,eAAeC,YAAeC,GAAW;IACtD,MAAMC,QAAQ,MAAMH,aAAgBE;IACpC,IAAI,CAACC,OAAO,MAAM,IAAIC,MAAM,CAAC,gCAAgC,EAAEF,KAAK;IACpE,OAAOC;AACT"}
@@ -0,0 +1,35 @@
1
+ /** Streaming file source utilities for memory-efficient uploads (no temp files) */
2
+ import { Readable } from 'stream';
3
+ /** Resolved source for an upload URI: a readable stream plus naming/MIME hints */
4
+ export interface FileSource {
5
+ /** Binary read stream of the file content */
6
+ stream: Readable;
7
+ /** Best-effort file name (used as default Drive name) */
8
+ fileName: string;
9
+ /** MIME type from the Content-Type header (http/https sources only) */
10
+ contentType?: string;
11
+ /** File size in bytes when known (file:// via stat, http/https via Content-Length) */
12
+ size?: number;
13
+ }
14
+ /** Guess MIME type from file name extension (application/octet-stream fallback) */
15
+ export declare function guessMimeType(fileName: string): string;
16
+ /**
17
+ * Get readable stream and metadata from a file URI
18
+ *
19
+ * Memory efficiency:
20
+ * - file:// URIs stream directly from disk
21
+ * - http:// URIs stream directly from response (no temp files!)
22
+ *
23
+ * Unlike mcp-sheets' getCsvReadStream, this streams binary content
24
+ * (no text encoding) so arbitrary file types can be uploaded.
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * const source = await getFileReadStream('file:///path/to/report.pdf');
29
+ * await drive.files.create({
30
+ * requestBody: { name: source.fileName },
31
+ * media: { mimeType: guessMimeType(source.fileName), body: source.stream },
32
+ * });
33
+ * ```
34
+ */
35
+ export declare function getFileReadStream(fileUri: string): Promise<FileSource>;
@@ -0,0 +1,111 @@
1
+ /** Streaming file source utilities for memory-efficient uploads (no temp files) */ import { createReadStream } from 'fs';
2
+ import { stat } from 'fs/promises';
3
+ import { basename, extname, resolve } from 'path';
4
+ import { Readable } from 'stream';
5
+ /** Common extension → MIME map; falls back to application/octet-stream */ const MIME_BY_EXTENSION = {
6
+ '.csv': 'text/csv',
7
+ '.doc': 'application/msword',
8
+ '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
9
+ '.gif': 'image/gif',
10
+ '.gz': 'application/gzip',
11
+ '.html': 'text/html',
12
+ '.jpeg': 'image/jpeg',
13
+ '.jpg': 'image/jpeg',
14
+ '.json': 'application/json',
15
+ '.md': 'text/markdown',
16
+ '.mp3': 'audio/mpeg',
17
+ '.mp4': 'video/mp4',
18
+ '.pdf': 'application/pdf',
19
+ '.png': 'image/png',
20
+ '.ppt': 'application/vnd.ms-powerpoint',
21
+ '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
22
+ '.rtf': 'application/rtf',
23
+ '.svg': 'image/svg+xml',
24
+ '.tar': 'application/x-tar',
25
+ '.txt': 'text/plain',
26
+ '.webp': 'image/webp',
27
+ '.woff': 'font/woff',
28
+ '.woff2': 'font/woff2',
29
+ '.xls': 'application/vnd.ms-excel',
30
+ '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
31
+ '.xml': 'application/xml',
32
+ '.zip': 'application/zip'
33
+ };
34
+ /** Guess MIME type from file name extension (application/octet-stream fallback) */ export function guessMimeType(fileName) {
35
+ var _MIME_BY_EXTENSION_extname_toLowerCase;
36
+ return (_MIME_BY_EXTENSION_extname_toLowerCase = MIME_BY_EXTENSION[extname(fileName).toLowerCase()]) !== null && _MIME_BY_EXTENSION_extname_toLowerCase !== void 0 ? _MIME_BY_EXTENSION_extname_toLowerCase : 'application/octet-stream';
37
+ }
38
+ /**
39
+ * Get readable stream and metadata from a file URI
40
+ *
41
+ * Memory efficiency:
42
+ * - file:// URIs stream directly from disk
43
+ * - http:// URIs stream directly from response (no temp files!)
44
+ *
45
+ * Unlike mcp-sheets' getCsvReadStream, this streams binary content
46
+ * (no text encoding) so arbitrary file types can be uploaded.
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * const source = await getFileReadStream('file:///path/to/report.pdf');
51
+ * await drive.files.create({
52
+ * requestBody: { name: source.fileName },
53
+ * media: { mimeType: guessMimeType(source.fileName), body: source.stream },
54
+ * });
55
+ * ```
56
+ */ export async function getFileReadStream(fileUri) {
57
+ if (fileUri.startsWith('file://')) {
58
+ // Local file - stream directly from disk
59
+ const rawPath = fileUri.slice('file://'.length);
60
+ const filePath = rawPath.startsWith('/') ? rawPath : resolve(rawPath);
61
+ const fileSize = (await stat(filePath)).size;
62
+ return {
63
+ stream: createReadStream(filePath),
64
+ fileName: basename(filePath),
65
+ size: fileSize
66
+ };
67
+ }
68
+ if (fileUri.startsWith('http://') || fileUri.startsWith('https://')) {
69
+ var _response_headers_get_split_, _response_headers_get;
70
+ // Remote file - stream directly from fetch response
71
+ const response = await fetch(fileUri);
72
+ if (!response.ok) {
73
+ throw new Error(`Failed to fetch file from ${fileUri}: ${response.statusText}`);
74
+ }
75
+ if (!response.body) {
76
+ throw new Error(`No response body from ${fileUri}`);
77
+ }
78
+ // Convert web stream to Node.js stream
79
+ // response.body is ReadableStream<Uint8Array> from fetch API
80
+ // Cast to Node.js ReadableStream type for compatibility with Readable.fromWeb
81
+ const stream = Readable.fromWeb(response.body);
82
+ const contentType = (_response_headers_get = response.headers.get('content-type')) === null || _response_headers_get === void 0 ? void 0 : (_response_headers_get_split_ = _response_headers_get.split(';')[0]) === null || _response_headers_get_split_ === void 0 ? void 0 : _response_headers_get_split_.trim();
83
+ const contentLength = response.headers.get('content-length');
84
+ return {
85
+ stream,
86
+ fileName: getRemoteFileName(response.headers.get('content-disposition'), fileUri),
87
+ ...contentType && {
88
+ contentType
89
+ },
90
+ ...contentLength && {
91
+ size: Number.parseInt(contentLength, 10)
92
+ }
93
+ };
94
+ }
95
+ throw new Error(`Invalid file URI: ${fileUri}. Must start with file://, http://, or https://`);
96
+ }
97
+ /** Best-effort file name for a remote source: Content-Disposition, then URL path */ function getRemoteFileName(contentDisposition, fileUri) {
98
+ if (contentDisposition) {
99
+ var _ref;
100
+ const match = /filename="([^"]+)"|filename=([^;]+)/i.exec(contentDisposition);
101
+ const fromHeader = (_ref = match === null || match === void 0 ? void 0 : match[1]) !== null && _ref !== void 0 ? _ref : match === null || match === void 0 ? void 0 : match[2];
102
+ if (fromHeader) {
103
+ return fromHeader.trim();
104
+ }
105
+ }
106
+ try {
107
+ return decodeURIComponent(basename(new URL(fileUri).pathname)) || 'upload.bin';
108
+ } catch {
109
+ return 'upload.bin';
110
+ }
111
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/lib/file-streaming.ts"],"sourcesContent":["/** Streaming file source utilities for memory-efficient uploads (no temp files) */\n\nimport { createReadStream } from 'fs';\nimport { stat } from 'fs/promises';\nimport { basename, extname, resolve } from 'path';\nimport { Readable } from 'stream';\nimport type { ReadableStream as NodeReadableStream } from 'stream/web';\n\n/** Resolved source for an upload URI: a readable stream plus naming/MIME hints */\nexport interface FileSource {\n /** Binary read stream of the file content */\n stream: Readable;\n /** Best-effort file name (used as default Drive name) */\n fileName: string;\n /** MIME type from the Content-Type header (http/https sources only) */\n contentType?: string;\n /** File size in bytes when known (file:// via stat, http/https via Content-Length) */\n size?: number;\n}\n\n/** Common extension → MIME map; falls back to application/octet-stream */\nconst MIME_BY_EXTENSION: Record<string, string> = {\n '.csv': 'text/csv',\n '.doc': 'application/msword',\n '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n '.gif': 'image/gif',\n '.gz': 'application/gzip',\n '.html': 'text/html',\n '.jpeg': 'image/jpeg',\n '.jpg': 'image/jpeg',\n '.json': 'application/json',\n '.md': 'text/markdown',\n '.mp3': 'audio/mpeg',\n '.mp4': 'video/mp4',\n '.pdf': 'application/pdf',\n '.png': 'image/png',\n '.ppt': 'application/vnd.ms-powerpoint',\n '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n '.rtf': 'application/rtf',\n '.svg': 'image/svg+xml',\n '.tar': 'application/x-tar',\n '.txt': 'text/plain',\n '.webp': 'image/webp',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.xls': 'application/vnd.ms-excel',\n '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n '.xml': 'application/xml',\n '.zip': 'application/zip',\n};\n\n/** Guess MIME type from file name extension (application/octet-stream fallback) */\nexport function guessMimeType(fileName: string): string {\n return MIME_BY_EXTENSION[extname(fileName).toLowerCase()] ?? 'application/octet-stream';\n}\n\n/**\n * Get readable stream and metadata from a file URI\n *\n * Memory efficiency:\n * - file:// URIs stream directly from disk\n * - http:// URIs stream directly from response (no temp files!)\n *\n * Unlike mcp-sheets' getCsvReadStream, this streams binary content\n * (no text encoding) so arbitrary file types can be uploaded.\n *\n * @example\n * ```ts\n * const source = await getFileReadStream('file:///path/to/report.pdf');\n * await drive.files.create({\n * requestBody: { name: source.fileName },\n * media: { mimeType: guessMimeType(source.fileName), body: source.stream },\n * });\n * ```\n */\nexport async function getFileReadStream(fileUri: string): Promise<FileSource> {\n if (fileUri.startsWith('file://')) {\n // Local file - stream directly from disk\n const rawPath = fileUri.slice('file://'.length);\n const filePath = rawPath.startsWith('/') ? rawPath : resolve(rawPath);\n const fileSize = (await stat(filePath)).size;\n return {\n stream: createReadStream(filePath),\n fileName: basename(filePath),\n size: fileSize,\n };\n }\n\n if (fileUri.startsWith('http://') || fileUri.startsWith('https://')) {\n // Remote file - stream directly from fetch response\n const response = await fetch(fileUri);\n if (!response.ok) {\n throw new Error(`Failed to fetch file from ${fileUri}: ${response.statusText}`);\n }\n\n if (!response.body) {\n throw new Error(`No response body from ${fileUri}`);\n }\n\n // Convert web stream to Node.js stream\n // response.body is ReadableStream<Uint8Array> from fetch API\n // Cast to Node.js ReadableStream type for compatibility with Readable.fromWeb\n const stream = Readable.fromWeb(response.body as unknown as NodeReadableStream<Uint8Array>);\n const contentType = response.headers.get('content-type')?.split(';')[0]?.trim();\n const contentLength = response.headers.get('content-length');\n\n return {\n stream,\n fileName: getRemoteFileName(response.headers.get('content-disposition'), fileUri),\n ...(contentType && { contentType }),\n ...(contentLength && { size: Number.parseInt(contentLength, 10) }),\n };\n }\n\n throw new Error(`Invalid file URI: ${fileUri}. Must start with file://, http://, or https://`);\n}\n\n/** Best-effort file name for a remote source: Content-Disposition, then URL path */\nfunction getRemoteFileName(contentDisposition: string | null, fileUri: string): string {\n if (contentDisposition) {\n const match = /filename=\"([^\"]+)\"|filename=([^;]+)/i.exec(contentDisposition);\n const fromHeader = match?.[1] ?? match?.[2];\n if (fromHeader) {\n return fromHeader.trim();\n }\n }\n\n try {\n return decodeURIComponent(basename(new URL(fileUri).pathname)) || 'upload.bin';\n } catch {\n return 'upload.bin';\n }\n}\n"],"names":["createReadStream","stat","basename","extname","resolve","Readable","MIME_BY_EXTENSION","guessMimeType","fileName","toLowerCase","getFileReadStream","fileUri","startsWith","rawPath","slice","length","filePath","fileSize","size","stream","response","fetch","ok","Error","statusText","body","fromWeb","contentType","headers","get","split","trim","contentLength","getRemoteFileName","Number","parseInt","contentDisposition","match","exec","fromHeader","decodeURIComponent","URL","pathname"],"mappings":"AAAA,iFAAiF,GAEjF,SAASA,gBAAgB,QAAQ,KAAK;AACtC,SAASC,IAAI,QAAQ,cAAc;AACnC,SAASC,QAAQ,EAAEC,OAAO,EAAEC,OAAO,QAAQ,OAAO;AAClD,SAASC,QAAQ,QAAQ,SAAS;AAelC,wEAAwE,GACxE,MAAMC,oBAA4C;IAChD,QAAQ;IACR,QAAQ;IACR,SAAS;IACT,QAAQ;IACR,OAAO;IACP,SAAS;IACT,SAAS;IACT,QAAQ;IACR,SAAS;IACT,OAAO;IACP,QAAQ;IACR,QAAQ;IACR,QAAQ;IACR,QAAQ;IACR,QAAQ;IACR,SAAS;IACT,QAAQ;IACR,QAAQ;IACR,QAAQ;IACR,QAAQ;IACR,SAAS;IACT,SAAS;IACT,UAAU;IACV,QAAQ;IACR,SAAS;IACT,QAAQ;IACR,QAAQ;AACV;AAEA,iFAAiF,GACjF,OAAO,SAASC,cAAcC,QAAgB;QACrCF;IAAP,QAAOA,yCAAAA,iBAAiB,CAACH,QAAQK,UAAUC,WAAW,GAAG,cAAlDH,oDAAAA,yCAAsD;AAC/D;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,eAAeI,kBAAkBC,OAAe;IACrD,IAAIA,QAAQC,UAAU,CAAC,YAAY;QACjC,yCAAyC;QACzC,MAAMC,UAAUF,QAAQG,KAAK,CAAC,UAAUC,MAAM;QAC9C,MAAMC,WAAWH,QAAQD,UAAU,CAAC,OAAOC,UAAUT,QAAQS;QAC7D,MAAMI,WAAW,AAAC,CAAA,MAAMhB,KAAKe,SAAQ,EAAGE,IAAI;QAC5C,OAAO;YACLC,QAAQnB,iBAAiBgB;YACzBR,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C,IAAIE,YAAY;YACd,OAAOA,WAAWR,IAAI;QACxB;IACF;IAEA,IAAI;QACF,OAAOS,mBAAmBtC,SAAS,IAAIuC,IAAI9B,SAAS+B,QAAQ,MAAM;IACpE,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/mcp-drive/src/lib/query-builder.ts"],"sourcesContent":["import type { DriveQuery, DriveQueryObject } from '../schemas/drive-query-schema.ts';\n\n/**\n * Field operator interface for query filters\n */\nexport interface FieldOperator {\n $any?: string[];\n $all?: string[];\n $none?: string[];\n}\n\n/**\n * Filters object returned by toDriveQuery for debugging/logging\n */\ninterface FiltersObject {\n nameIncludes?: string[];\n mimeTypeIncludes?: string[];\n fullTextIncludes?: string[];\n parentIdIncludes?: string[];\n ownerIncludes?: string[];\n starred?: boolean;\n sharedWithMe?: boolean;\n trashed?: boolean;\n}\n\n/**\n * Convert structured DriveQuery to Google Drive query string\n *\n * Accepts either:\n * - A raw Drive query string (returned as-is)\n * - A structured DriveQueryObject (converted to Drive query syntax)\n *\n * Drive query syntax reference:\n * - name contains 'text' - Search by filename\n * - mimeType = 'type' - Filter by MIME type\n * - fullText contains 'text' - Search content and metadata\n * - 'parent_id' in parents - Search in folder\n * - starred = true/false - Filter by starred status\n * - sharedWithMe = true - Filter by shared status\n * - modifiedTime >= 'date' - Date filtering\n * - 'email' in owners - Filter by owner\n * - trashed = true/false - Filter by trash status\n */\nexport function toDriveQuery(query: DriveQuery | string): {\n q: string;\n filters: FiltersObject;\n} {\n // Handle string queries - return as raw query with empty filters\n if (typeof query === 'string') {\n return { q: query, filters: {} };\n }\n const nameIncludes: string[] = [];\n const mimeTypeIncludes: string[] = [];\n const fullTextIncludes: string[] = [];\n const parentIdIncludes: string[] = [];\n const ownerIncludes: string[] = [];\n\n let starredFlag: boolean | undefined;\n let sharedWithMeFlag: boolean | undefined;\n let trashedFlag: boolean | undefined;\n\n function p(s: unknown) {\n return `(${String(s ?? '')})`;\n }\n\n function quote(s?: unknown) {\n const str = String(s ?? '');\n // Escape single quotes for Drive query syntax\n return `'${str.replace(/'/g, \"\\\\'\")}'`;\n }\n\n function fv(field: string, raw?: unknown) {\n const rawVal = String(raw ?? '');\n const v = quote(rawVal);\n\n if (field === 'name') {\n nameIncludes.push(rawVal);\n return `name contains ${v}`;\n }\n if (field === 'mimeType') {\n mimeTypeIncludes.push(rawVal);\n return `mimeType = ${v}`;\n }\n if (field === 'fullText') {\n fullTextIncludes.push(rawVal);\n return `fullText contains ${v}`;\n }\n if (field === 'parentId') {\n parentIdIncludes.push(rawVal);\n return `${v} in parents`;\n }\n if (field === 'owner') {\n ownerIncludes.push(rawVal);\n return `${v} in owners`;\n }\n\n return '';\n }\n\n function chain(op: 'and' | 'or', arr: string[]) {\n const filtered = arr.filter((s) => s && s.trim() !== '');\n if (filtered.length === 0) return '';\n if (filtered.length === 1) {\n const first = filtered[0];\n return first ?? '';\n }\n return p(filtered.join(` ${op} `));\n }\n\n function fieldExpr(field: string, op: FieldOperator) {\n if (op.$any) {\n const nonEmpty = op.$any.filter((v: string) => String(v ?? '').trim() !== '');\n const results = nonEmpty.map((v: string) => fv(field, String(v ?? ''))).filter((result: string) => result.trim() !== '');\n return results.length > 0 ? chain('or', results) : '';\n }\n if (op.$all) {\n const nonEmpty = op.$all.filter((v: string) => String(v ?? '').trim() !== '');\n const results = nonEmpty.map((v: string) => fv(field, String(v ?? ''))).filter((result: string) => result.trim() !== '');\n return results.length > 0 ? chain('and', results) : '';\n }\n if (op.$none) {\n const nonEmpty = op.$none.filter((v: string) => String(v ?? '').trim() !== '');\n const results = nonEmpty.map((v: string) => fv(field, String(v ?? ''))).filter((result: string) => result.trim() !== '');\n return results.length > 0 ? `not ${p(chain('or', results))}` : '';\n }\n throw new Error(`Unknown field operator ${JSON.stringify(op)}`);\n }\n\n function dateExpr(d: { $gte?: string; $lt?: string }) {\n const parts: string[] = [];\n if (d.$gte) parts.push(`modifiedTime >= '${d.$gte}'`);\n if (d.$lt) parts.push(`modifiedTime < '${d.$lt}'`);\n return parts.length > 1 ? p(parts.join(' and ')) : (parts[0] ?? '');\n }\n\n function fieldKeys() {\n return ['name', 'mimeType', 'fullText', 'parentId', 'owner'];\n }\n\n function emit(n: DriveQueryObject): string {\n if (n.$and) return p(n.$and.map(emit).join(' and '));\n if (n.$or) return p(n.$or.map(emit).join(' or '));\n if (n.$not) return `not ${emit(n.$not)}`;\n\n const expressions: string[] = [];\n\n if (typeof n.starred === 'boolean') {\n starredFlag = n.starred;\n expressions.push(`starred = ${n.starred}`);\n }\n if (typeof n.sharedWithMe === 'boolean') {\n sharedWithMeFlag = n.sharedWithMe;\n expressions.push(`sharedWithMe = ${n.sharedWithMe}`);\n }\n if (typeof n.trashed === 'boolean') {\n trashedFlag = n.trashed;\n expressions.push(`trashed = ${n.trashed}`);\n }\n if (n.modifiedTime) {\n expressions.push(dateExpr(n.modifiedTime));\n }\n\n for (const k of fieldKeys()) {\n if (typeof n === 'object' && n !== null && k in n) {\n const op = (n as Record<string, string | FieldOperator>)[k];\n const normalizedOp: FieldOperator = typeof op === 'string' ? { $any: [op] } : (op ?? {});\n const result = fieldExpr(k, normalizedOp);\n if (result.trim() !== '') {\n expressions.push(result);\n }\n }\n }\n\n // Handle empty objects\n if (expressions.length === 0 && typeof n === 'object' && n !== null && Object.keys(n).length === 0) {\n return '';\n }\n\n // Combine multiple expressions with AND\n if (expressions.length > 1) {\n return chain('and', expressions);\n }\n if (expressions.length === 1) {\n return expressions[0] ?? '';\n }\n\n throw new Error(`Unknown node: ${JSON.stringify(n)}`);\n }\n\n function emitTop(n: DriveQueryObject): string {\n if (!n) return '';\n\n // Handle empty objects\n if (typeof n === 'object' && n !== null && Object.keys(n).length === 0) return '';\n\n if (n.$and) return n.$and.map(emit).join(' and ');\n if (n.$or) return n.$or.map(emit).join(' or ');\n if (n.$not) return `not ${emit(n.$not)}`;\n\n const result = emit(n);\n return result.trim() === '' ? '' : result;\n }\n\n const q = emitTop(query);\n const cleanedQuery = q.replace(/\\s+and\\s+$|\\s+or\\s+$|^\\s+and\\s+|^\\s+or\\s+/gi, '').trim();\n\n const filters: FiltersObject = {};\n if (nameIncludes.length) filters.nameIncludes = nameIncludes;\n if (mimeTypeIncludes.length) filters.mimeTypeIncludes = mimeTypeIncludes;\n if (fullTextIncludes.length) filters.fullTextIncludes = fullTextIncludes;\n if (parentIdIncludes.length) filters.parentIdIncludes = parentIdIncludes;\n if (ownerIncludes.length) filters.ownerIncludes = ownerIncludes;\n // Use tracked flags from emit() to capture nested boolean conditions\n if (typeof starredFlag === 'boolean') filters.starred = starredFlag;\n if (typeof sharedWithMeFlag === 'boolean') filters.sharedWithMe = sharedWithMeFlag;\n if (typeof trashedFlag === 'boolean') filters.trashed = trashedFlag;\n\n return { q: cleanedQuery ?? '', filters };\n}\n"],"names":["toDriveQuery","query","q","filters","nameIncludes","mimeTypeIncludes","fullTextIncludes","parentIdIncludes","ownerIncludes","starredFlag","sharedWithMeFlag","trashedFlag","p","s","String","quote","str","replace","fv","field","raw","rawVal","v","push","chain","op","arr","filtered","filter","trim","length","first","join","fieldExpr","$any","nonEmpty","results","map","result","$all","$none","Error","JSON","stringify","dateExpr","d","parts","$gte","$lt","fieldKeys","emit","n","$and","$or","$not","expressions","starred","sharedWithMe","trashed","modifiedTime","k","normalizedOp","Object","keys","emitTop","cleanedQuery"],"mappings":"AAyBA;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,SAASA,aAAaC,KAA0B;IAIrD,iEAAiE;IACjE,IAAI,OAAOA,UAAU,UAAU;QAC7B,OAAO;YAAEC,GAAGD;YAAOE,SAAS,CAAC;QAAE;IACjC;IACA,MAAMC,eAAyB,EAAE;IACjC,MAAMC,mBAA6B,EAAE;IACrC,MAAMC,mBAA6B,EAAE;IACrC,MAAMC,mBAA6B,EAAE;IACrC,MAAMC,gBAA0B,EAAE;IAElC,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IAEJ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ACzC,IAAImB,EAAEE,GAAG,EAAE,OAAOF,EAAEE,GAAG,CAAChB,GAAG,CAACa,MAAMlB,IAAI,CAAC;QACvC,IAAImB,EAAEG,IAAI,EAAE,OAAO,CAAC,IAAI,EAAEJ,KAAKC,EAAEG,IAAI,GAAG;QAExC,MAAMhB,SAASY,KAAKC;QACpB,OAAOb,OAAOT,IAAI,OAAO,KAAK,KAAKS;IACrC;IAEA,MAAMpC,IAAI8D,QAAQ/D;IAClB,MAAMgE,eAAe/D,EAAEe,OAAO,CAAC,+CAA+C,IAAIY,IAAI;IAEtF,MAAM1B,UAAyB,CAAC;IAChC,IAAIC,aAAa0B,MAAM,EAAE3B,QAAQC,YAAY,GAAGA;IAChD,IAAIC,iBAAiByB,MAAM,EAAE3B,QAAQE,gBAAgB,GAAGA;IACxD,IAAIC,iBAAiBwB,MAAM,EAAE3B,QAAQG,gBAAgB,GAAGA;IACxD,IAAIC,iBAAiBuB,MAAM,EAAE3B,QAAQI,gBAAgB,GAAGA;IACxD,IAAIC,cAAcsB,MAAM,EAAE3B,QAAQK,aAAa,GAAGA;IAClD,qEAAqE;IACrE,IAAI,OAAOC,gBAAgB,WAAWN,QAAQqD,OAAO,GAAG/C;IACxD,IAAI,OAAOC,qBAAqB,WAAWP,QAAQsD,YAAY,GAAG/C;IAClE,IAAI,OAAOC,gBAAgB,WAAWR,QAAQuD,OAAO,GAAG/C;IAExD,OAAO;QAAET,CAAC,EAAE+D,yBAAAA,0BAAAA,eAAgB;QAAI9D;IAAQ;AAC1C"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/lib/query-builder.ts"],"sourcesContent":["import type { DriveQuery, DriveQueryObject } from '../schemas/drive-query-schema.ts';\n\n/**\n * Field operator interface for query filters\n */\nexport interface FieldOperator {\n $any?: string[];\n $all?: string[];\n $none?: string[];\n}\n\n/**\n * Filters object returned by toDriveQuery for debugging/logging\n */\ninterface FiltersObject {\n nameIncludes?: string[];\n mimeTypeIncludes?: string[];\n fullTextIncludes?: string[];\n parentIdIncludes?: string[];\n ownerIncludes?: string[];\n starred?: boolean;\n sharedWithMe?: boolean;\n trashed?: boolean;\n}\n\n/**\n * Convert structured DriveQuery to Google Drive query string\n *\n * Accepts either:\n * - A raw Drive query string (returned as-is)\n * - A structured DriveQueryObject (converted to Drive query syntax)\n *\n * Drive query syntax reference:\n * - name contains 'text' - Search by filename\n * - mimeType = 'type' - Filter by MIME type\n * - fullText contains 'text' - Search content and metadata\n * - 'parent_id' in parents - Search in folder\n * - starred = true/false - Filter by starred status\n * - sharedWithMe = true - Filter by shared status\n * - modifiedTime >= 'date' - Date filtering\n * - 'email' in owners - Filter by owner\n * - trashed = true/false - Filter by trash status\n */\nexport function toDriveQuery(query: DriveQuery | string): {\n q: string;\n filters: FiltersObject;\n} {\n // Handle string queries - return as raw query with empty filters\n if (typeof query === 'string') {\n return { q: query, filters: {} };\n }\n const nameIncludes: string[] = [];\n const mimeTypeIncludes: string[] = [];\n const fullTextIncludes: string[] = [];\n const parentIdIncludes: string[] = [];\n const ownerIncludes: string[] = [];\n\n let starredFlag: boolean | undefined;\n let sharedWithMeFlag: boolean | undefined;\n let trashedFlag: boolean | undefined;\n\n function p(s: unknown) {\n return `(${String(s ?? '')})`;\n }\n\n function quote(s?: unknown) {\n const str = String(s ?? '');\n // Escape single quotes for Drive query syntax\n return `'${str.replace(/'/g, \"\\\\'\")}'`;\n }\n\n function fv(field: string, raw?: unknown) {\n const rawVal = String(raw ?? '');\n const v = quote(rawVal);\n\n if (field === 'name') {\n nameIncludes.push(rawVal);\n return `name contains ${v}`;\n }\n if (field === 'mimeType') {\n mimeTypeIncludes.push(rawVal);\n return `mimeType = ${v}`;\n }\n if (field === 'fullText') {\n fullTextIncludes.push(rawVal);\n return `fullText contains ${v}`;\n }\n if (field === 'parentId') {\n parentIdIncludes.push(rawVal);\n return `${v} in parents`;\n }\n if (field === 'owner') {\n ownerIncludes.push(rawVal);\n return `${v} in owners`;\n }\n\n return '';\n }\n\n function chain(op: 'and' | 'or', arr: string[]) {\n const filtered = arr.filter((s) => s && s.trim() !== '');\n if (filtered.length === 0) return '';\n if (filtered.length === 1) {\n const first = filtered[0];\n return first ?? '';\n }\n return p(filtered.join(` ${op} `));\n }\n\n function fieldExpr(field: string, op: FieldOperator) {\n if (op.$any) {\n const nonEmpty = op.$any.filter((v: string) => String(v ?? '').trim() !== '');\n const results = nonEmpty.map((v: string) => fv(field, String(v ?? ''))).filter((result: string) => result.trim() !== '');\n return results.length > 0 ? chain('or', results) : '';\n }\n if (op.$all) {\n const nonEmpty = op.$all.filter((v: string) => String(v ?? '').trim() !== '');\n const results = nonEmpty.map((v: string) => fv(field, String(v ?? ''))).filter((result: string) => result.trim() !== '');\n return results.length > 0 ? chain('and', results) : '';\n }\n if (op.$none) {\n const nonEmpty = op.$none.filter((v: string) => String(v ?? '').trim() !== '');\n const results = nonEmpty.map((v: string) => fv(field, String(v ?? ''))).filter((result: string) => result.trim() !== '');\n return results.length > 0 ? `not ${p(chain('or', results))}` : '';\n }\n throw new Error(`Unknown field operator ${JSON.stringify(op)}`);\n }\n\n function dateExpr(d: { $gte?: string; $lt?: string }) {\n const parts: string[] = [];\n if (d.$gte) parts.push(`modifiedTime >= '${d.$gte}'`);\n if (d.$lt) parts.push(`modifiedTime < '${d.$lt}'`);\n return parts.length > 1 ? p(parts.join(' and ')) : (parts[0] ?? '');\n }\n\n function fieldKeys() {\n return ['name', 'mimeType', 'fullText', 'parentId', 'owner'];\n }\n\n function emit(n: DriveQueryObject): string {\n if (n.$and) return p(n.$and.map(emit).join(' and '));\n if (n.$or) return p(n.$or.map(emit).join(' or '));\n if (n.$not) return `not ${emit(n.$not)}`;\n\n const expressions: string[] = [];\n\n if (typeof n.starred === 'boolean') {\n starredFlag = n.starred;\n expressions.push(`starred = ${n.starred}`);\n }\n if (typeof n.sharedWithMe === 'boolean') {\n sharedWithMeFlag = n.sharedWithMe;\n expressions.push(`sharedWithMe = ${n.sharedWithMe}`);\n }\n if (typeof n.trashed === 'boolean') {\n trashedFlag = n.trashed;\n expressions.push(`trashed = ${n.trashed}`);\n }\n if (n.modifiedTime) {\n expressions.push(dateExpr(n.modifiedTime));\n }\n\n for (const k of fieldKeys()) {\n if (typeof n === 'object' && n !== null && k in n) {\n const op = (n as Record<string, string | FieldOperator>)[k];\n const normalizedOp: FieldOperator = typeof op === 'string' ? { $any: [op] } : (op ?? {});\n const result = fieldExpr(k, normalizedOp);\n if (result.trim() !== '') {\n expressions.push(result);\n }\n }\n }\n\n // Handle empty objects\n if (expressions.length === 0 && typeof n === 'object' && n !== null && Object.keys(n).length === 0) {\n return '';\n }\n\n // Combine multiple expressions with AND\n if (expressions.length > 1) {\n return chain('and', expressions);\n }\n if (expressions.length === 1) {\n return expressions[0] ?? '';\n }\n\n throw new Error(`Unknown node: ${JSON.stringify(n)}`);\n }\n\n function emitTop(n: DriveQueryObject): string {\n if (!n) return '';\n\n // Handle empty objects\n if (typeof n === 'object' && n !== null && Object.keys(n).length === 0) return '';\n\n if (n.$and) return n.$and.map(emit).join(' and ');\n if (n.$or) return n.$or.map(emit).join(' or ');\n if (n.$not) return `not ${emit(n.$not)}`;\n\n const result = emit(n);\n return result.trim() === '' ? '' : result;\n }\n\n const q = emitTop(query);\n const cleanedQuery = q.replace(/\\s+and\\s+$|\\s+or\\s+$|^\\s+and\\s+|^\\s+or\\s+/gi, '').trim();\n\n const filters: FiltersObject = {};\n if (nameIncludes.length) filters.nameIncludes = nameIncludes;\n if (mimeTypeIncludes.length) filters.mimeTypeIncludes = mimeTypeIncludes;\n if (fullTextIncludes.length) filters.fullTextIncludes = fullTextIncludes;\n if (parentIdIncludes.length) filters.parentIdIncludes = parentIdIncludes;\n if (ownerIncludes.length) filters.ownerIncludes = ownerIncludes;\n // Use tracked flags from emit() to capture nested boolean conditions\n if (typeof starredFlag === 'boolean') filters.starred = starredFlag;\n if (typeof sharedWithMeFlag === 'boolean') filters.sharedWithMe = sharedWithMeFlag;\n if (typeof trashedFlag === 'boolean') filters.trashed = trashedFlag;\n\n return { q: cleanedQuery ?? '', filters };\n}\n"],"names":["toDriveQuery","query","q","filters","nameIncludes","mimeTypeIncludes","fullTextIncludes","parentIdIncludes","ownerIncludes","starredFlag","sharedWithMeFlag","trashedFlag","p","s","String","quote","str","replace","fv","field","raw","rawVal","v","push","chain","op","arr","filtered","filter","trim","length","first","join","fieldExpr","$any","nonEmpty","results","map","result","$all","$none","Error","JSON","stringify","dateExpr","d","parts","$gte","$lt","fieldKeys","emit","n","$and","$or","$not","expressions","starred","sharedWithMe","trashed","modifiedTime","k","normalizedOp","Object","keys","emitTop","cleanedQuery"],"mappings":"AAyBA;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,SAASA,aAAaC,KAA0B;IAIrD,iEAAiE;IACjE,IAAI,OAAOA,UAAU,UAAU;QAC7B,OAAO;YAAEC,GAAGD;YAAOE,SAAS,CAAC;QAAE;IACjC;IACA,MAAMC,eAAyB,EAAE;IACjC,MAAMC,mBAA6B,EAAE;IACrC,MAAMC,mBAA6B,EAAE;IACrC,MAAMC,mBAA6B,EAAE;IACrC,MAAMC,gBAA0B,EAAE;IAElC,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IAEJ,SAASC,EAAEC,CAAU;QACnB,OAAO,CAAC,CAAC,EAAEC,OAAOD,cAAAA,eAAAA,IAAK,IAAI,CAAC,CAAC;IAC/B;IAEA,SAASE,MAAMF,CAAW;QACxB,MAAMG,MAAMF,OAAOD,cAAAA,eAAAA,IAAK;QACxB,8CAA8C;QAC9C,OAAO,CAAC,CAAC,EAAEG,IAAIC,OAAO,CAAC,MAAM,OAAO,CAAC,CAAC;IACxC;IAEA,SAASC,GAAGC,KAAa,EAAEC,GAAa;QACtC,MAAMC,SAASP,OAAOM,gBAAAA,iBAAAA,MAAO;QAC7B,MAAME,IAAIP,MAAMM;QAEhB,IAAIF,UAAU,QAAQ;YACpBf,aAAamB,IAAI,CAACF;YAClB,OAAO,CAAC,cA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M,EAAE3B,QAAQE,gBAAgB,GAAGA;IACxD,IAAIC,iBAAiBwB,MAAM,EAAE3B,QAAQG,gBAAgB,GAAGA;IACxD,IAAIC,iBAAiBuB,MAAM,EAAE3B,QAAQI,gBAAgB,GAAGA;IACxD,IAAIC,cAAcsB,MAAM,EAAE3B,QAAQK,aAAa,GAAGA;IAClD,qEAAqE;IACrE,IAAI,OAAOC,gBAAgB,WAAWN,QAAQqD,OAAO,GAAG/C;IACxD,IAAI,OAAOC,qBAAqB,WAAWP,QAAQsD,YAAY,GAAG/C;IAClE,IAAI,OAAOC,gBAAgB,WAAWR,QAAQuD,OAAO,GAAG/C;IAExD,OAAO;QAAET,CAAC,EAAE+D,yBAAAA,0BAAAA,eAAgB;QAAI9D;IAAQ;AAC1C"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/mcp-drive/src/mcp/index.ts"],"sourcesContent":["export * as promptFactories from './prompts/index.ts';\nexport * as resourceFactories from './resources/index.ts';\nexport * as toolFactories from './tools/index.ts';\n"],"names":["promptFactories","resourceFactories","toolFactories"],"mappings":"AAAA,kCAAiC,qBAAqB;AAAtD,SAAO,oBAAKA,eAAe,GAA2B;AACtD,oCAAmC,uBAAuB;AAA1D,SAAO,sBAAKC,iBAAiB,GAA6B;AAC1D,gCAA+B,mBAAmB;AAAlD,SAAO,kBAAKC,aAAa,GAAyB"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/index.ts"],"sourcesContent":["export * as promptFactories from './prompts/index.ts';\nexport * as resourceFactories from './resources/index.ts';\nexport * as toolFactories from './tools/index.ts';\n"],"names":["promptFactories","resourceFactories","toolFactories"],"mappings":"AAAA,kCAAiC,qBAAqB;AAAtD,SAAO,oBAAKA,eAAe,GAA2B;AACtD,oCAAmC,uBAAuB;AAA1D,SAAO,sBAAKC,iBAAiB,GAA6B;AAC1D,gCAA+B,mBAAmB;AAAlD,SAAO,kBAAKC,aAAa,GAAyB"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/mcp-drive/src/mcp/prompts/index.ts"],"sourcesContent":["export { default as organizeFiles } from './organize-files.ts';\nexport { default as querySyntax } from './query-syntax.ts';\n"],"names":["default","organizeFiles","querySyntax"],"mappings":"AAAA,SAASA,WAAWC,aAAa,QAAQ,sBAAsB;AAC/D,SAASD,WAAWE,WAAW,QAAQ,oBAAoB"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/prompts/index.ts"],"sourcesContent":["export { default as organizeFiles } from './organize-files.ts';\nexport { default as querySyntax } from './query-syntax.ts';\n"],"names":["default","organizeFiles","querySyntax"],"mappings":"AAAA,SAASA,WAAWC,aAAa,QAAQ,sBAAsB;AAC/D,SAASD,WAAWE,WAAW,QAAQ,oBAAoB"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/mcp-drive/src/mcp/prompts/organize-files.ts"],"sourcesContent":["import type { PromptModule } from '@mcp-z/server';\n\nexport default function createPrompt() {\n const config = {\n description: 'Help organize and manage files in Google Drive',\n argsSchema: {} as const,\n };\n\n return {\n name: 'organize-files',\n config,\n handler: async () => ({\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: 'You are an expert file organizer assistant. Help me organize my Google Drive files.',\n },\n },\n ],\n }),\n } satisfies PromptModule;\n}\n"],"names":["createPrompt","config","description","argsSchema","name","handler","messages","role","content","type","text"],"mappings":"AAEA,eAAe,SAASA;IACtB,MAAMC,SAAS;QACbC,aAAa;QACbC,YAAY,CAAC;IACf;IAEA,OAAO;QACLC,MAAM;QACNH;QACAI,SAAS,UAAa,CAAA;gBACpBC,UAAU;oBACR;wBACEC,MAAM;wBACNC,SAAS;4BACPC,MAAM;4BACNC,MAAM;wBACR;oBACF;iBACD;YACH,CAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/prompts/organize-files.ts"],"sourcesContent":["import type { PromptModule } from '@mcp-z/server';\n\nexport default function createPrompt() {\n const config = {\n description: 'Help organize and manage files in Google Drive',\n argsSchema: {} as const,\n };\n\n return {\n name: 'organize-files',\n config,\n handler: async () => ({\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: 'You are an expert file organizer assistant. Help me organize my Google Drive files.',\n },\n },\n ],\n }),\n } satisfies PromptModule;\n}\n"],"names":["createPrompt","config","description","argsSchema","name","handler","messages","role","content","type","text"],"mappings":"AAEA,eAAe,SAASA;IACtB,MAAMC,SAAS;QACbC,aAAa;QACbC,YAAY,CAAC;IACf;IAEA,OAAO;QACLC,MAAM;QACNH;QACAI,SAAS,UAAa,CAAA;gBACpBC,UAAU;oBACR;wBACEC,MAAM;wBACNC,SAAS;4BACPC,MAAM;4BACNC,MAAM;wBACR;oBACF;iBACD;YACH,CAAA;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/mcp-drive/src/mcp/prompts/query-syntax.ts"],"sourcesContent":["import type { PromptModule } from '@mcp-z/server';\nimport type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport type { ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';\n\nexport default function createPrompt() {\n const config = {\n description: 'Reference guide for Google Drive query syntax',\n };\n\n const handler = async (_args: { [x: string]: unknown }, _extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => {\n return {\n messages: [\n {\n role: 'user' as const,\n content: {\n type: 'text' as const,\n text: `# Google Drive Query Syntax Reference\n\n## Logical Operators\n- \\`$and\\`: Array of conditions that ALL must match\n- \\`$or\\`: Array of conditions where ANY must match\n- \\`$not\\`: Condition that must NOT match\n\n## File/Folder Fields\n- \\`name\\`: Search by name (partial match, case-insensitive)\n- \\`mimeType\\`: Filter by MIME type\n- \\`fullText\\`: Search file content and metadata\n- \\`parentId\\`: Search within folder (use \"root\" for My Drive)\n- \\`owner\\`: Filter by owner email\n\n## Boolean Flags\n- \\`starred\\`: true/false\n- \\`sharedWithMe\\`: true/false\n- \\`trashed\\`: true/false\n\n## Date Range\n\\`\\`\\`json\n{ \"modifiedTime\": { \"$gte\": \"2024-01-01\", \"$lt\": \"2024-12-31\" } }\n\\`\\`\\`\n\n## Common MIME Types\n- \\`application/vnd.google-apps.folder\\`: Folders\n- \\`application/vnd.google-apps.document\\`: Google Docs\n- \\`application/vnd.google-apps.spreadsheet\\`: Google Sheets\n- \\`application/vnd.google-apps.presentation\\`: Google Slides\n- \\`application/pdf\\`: PDF files\n- \\`image/jpeg\\`, \\`image/png\\`: Images\n\n## Field Operators (for multi-value fields)\n- \\`$any\\`: OR - matches if ANY value matches\n- \\`$all\\`: AND - matches if ALL values match\n- \\`$none\\`: NOT - matches if NONE match\n\n## Escape Hatch\n- \\`rawDriveQuery\\`: Raw Google Drive query syntax\n\n## Example Queries\n\\`\\`\\`json\n// PDFs modified this year\n{ \"mimeType\": \"application/pdf\", \"modifiedTime\": { \"$gte\": \"2024-01-01\" } }\n\n// Starred spreadsheets\n{ \"mimeType\": \"application/vnd.google-apps.spreadsheet\", \"starred\": true }\n\n// Files in specific folder\n{ \"parentId\": \"1abc123xyz\" }\n\n// Search by name\n{ \"name\": \"budget\" }\n\n// Complex: shared PDFs or Docs\n{ \"$or\": [\n { \"mimeType\": \"application/pdf\", \"sharedWithMe\": true },\n { \"mimeType\": \"application/vnd.google-apps.document\", \"sharedWithMe\": true }\n]}\n\\`\\`\\``,\n },\n },\n ],\n };\n };\n\n return {\n name: 'query-syntax',\n config,\n handler,\n } satisfies PromptModule;\n}\n"],"names":["createPrompt","config","description","handler","_args","_extra","messages","role","content","type","text","name"],"mappings":"AAIA,eAAe,SAASA;IACtB,MAAMC,SAAS;QACbC,aAAa;IACf;IAEA,MAAMC,UAAU,OAAOC,OAAiCC;QACtD,OAAO;YACLC,UAAU;gBACR;oBACEC,MAAM;oBACNC,SAAS;wBACPC,MAAM;wBACNC,MAAM,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MA2Db,CAAC;oBACG;gBACF;aACD;QACH;IACF;IAEA,OAAO;QACLC,MAAM;QACNV;QACAE;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/prompts/query-syntax.ts"],"sourcesContent":["import type { PromptModule } from '@mcp-z/server';\nimport type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport type { ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';\n\nexport default function createPrompt() {\n const config = {\n description: 'Reference guide for Google Drive query syntax',\n };\n\n const handler = async (_args: { [x: string]: unknown }, _extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => {\n return {\n messages: [\n {\n role: 'user' as const,\n content: {\n type: 'text' as const,\n text: `# Google Drive Query Syntax Reference\n\n## Logical Operators\n- \\`$and\\`: Array of conditions that ALL must match\n- \\`$or\\`: Array of conditions where ANY must match\n- \\`$not\\`: Condition that must NOT match\n\n## File/Folder Fields\n- \\`name\\`: Search by name (partial match, case-insensitive)\n- \\`mimeType\\`: Filter by MIME type\n- \\`fullText\\`: Search file content and metadata\n- \\`parentId\\`: Search within folder (use \"root\" for My Drive)\n- \\`owner\\`: Filter by owner email\n\n## Boolean Flags\n- \\`starred\\`: true/false\n- \\`sharedWithMe\\`: true/false\n- \\`trashed\\`: true/false\n\n## Date Range\n\\`\\`\\`json\n{ \"modifiedTime\": { \"$gte\": \"2024-01-01\", \"$lt\": \"2024-12-31\" } }\n\\`\\`\\`\n\n## Common MIME Types\n- \\`application/vnd.google-apps.folder\\`: Folders\n- \\`application/vnd.google-apps.document\\`: Google Docs\n- \\`application/vnd.google-apps.spreadsheet\\`: Google Sheets\n- \\`application/vnd.google-apps.presentation\\`: Google Slides\n- \\`application/pdf\\`: PDF files\n- \\`image/jpeg\\`, \\`image/png\\`: Images\n\n## Field Operators (for multi-value fields)\n- \\`$any\\`: OR - matches if ANY value matches\n- \\`$all\\`: AND - matches if ALL values match\n- \\`$none\\`: NOT - matches if NONE match\n\n## Escape Hatch\n- \\`rawDriveQuery\\`: Raw Google Drive query syntax\n\n## Example Queries\n\\`\\`\\`json\n// PDFs modified this year\n{ \"mimeType\": \"application/pdf\", \"modifiedTime\": { \"$gte\": \"2024-01-01\" } }\n\n// Starred spreadsheets\n{ \"mimeType\": \"application/vnd.google-apps.spreadsheet\", \"starred\": true }\n\n// Files in specific folder\n{ \"parentId\": \"1abc123xyz\" }\n\n// Search by name\n{ \"name\": \"budget\" }\n\n// Complex: shared PDFs or Docs\n{ \"$or\": [\n { \"mimeType\": \"application/pdf\", \"sharedWithMe\": true },\n { \"mimeType\": \"application/vnd.google-apps.document\", \"sharedWithMe\": true }\n]}\n\\`\\`\\``,\n },\n },\n ],\n };\n };\n\n return {\n name: 'query-syntax',\n config,\n handler,\n } satisfies PromptModule;\n}\n"],"names":["createPrompt","config","description","handler","_args","_extra","messages","role","content","type","text","name"],"mappings":"AAIA,eAAe,SAASA;IACtB,MAAMC,SAAS;QACbC,aAAa;IACf;IAEA,MAAMC,UAAU,OAAOC,OAAiCC;QACtD,OAAO;YACLC,UAAU;gBACR;oBACEC,MAAM;oBACNC,SAAS;wBACPC,MAAM;wBACNC,MAAM,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MA2Db,CAAC;oBACG;gBACF;aACD;QACH;IACF;IAEA,OAAO;QACLC,MAAM;QACNV;QACAE;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/mcp-drive/src/mcp/resources/file.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport type { ResourceConfig, ResourceModule } from '@mcp-z/server';\nimport { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport type { ReadResourceResult, ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';\nimport { google } from 'googleapis';\n\nexport default function createResource() {\n const template = new ResourceTemplate('drive://files/{fileId}', {\n list: undefined,\n });\n const config: ResourceConfig = {\n description: 'Drive file resource',\n mimeType: 'application/json',\n };\n\n const handler = async (uri: URL, variables: Record<string, string | string[]>, extra: RequestHandlerExtra<ServerRequest, ServerNotification>): Promise<ReadResourceResult> => {\n // Extract fileId and handle both string and string[] cases\n const fileId = Array.isArray(variables.fileId) ? variables.fileId[0] : variables.fileId;\n\n try {\n // Validate fileId exists and is a string\n if (!fileId || typeof fileId !== 'string') {\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify({\n error: 'Missing or invalid fileId in resource URI',\n }),\n },\n ],\n };\n }\n\n // Safe type guard to access middleware-enriched extra\n const { logger, authContext } = extra as unknown as EnrichedExtra;\n const drive = google.drive({ version: 'v3', auth: authContext.auth });\n const resp = await drive.files.get({\n fileId,\n fields: 'id,name,mimeType,size,modifiedTime,owners,webViewLink',\n });\n const data = resp.data;\n logger.debug?.({ fileId, fileName: data?.name }, 'drive-file resource fetch success');\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify(data || {}),\n },\n ],\n };\n } catch (error) {\n const { logger } = extra as unknown as EnrichedExtra;\n logger.debug?.(error as Record<string, unknown>, 'drive resource fetch failed');\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify({ error: (error as Error).message }),\n },\n ],\n };\n }\n };\n\n return {\n name: 'file',\n template,\n config,\n handler,\n } satisfies ResourceModule;\n}\n"],"names":["ResourceTemplate","google","createResource","template","list","undefined","config","description","mimeType","handler","uri","variables","extra","fileId","Array","isArray","logger","contents","href","text","JSON","stringify","error","authContext","drive","version","auth","resp","files","get","fields","data","debug","fileName","name","message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J;aACnBI,iBAAAA,OAAOgB,KAAK,cAAZhB,qCAAAA,oBAAAA,QAAeM,OAAkC;YACjD,OAAO;gBACLL,UAAU;oBACR;wBACEP,KAAKA,IAAIQ,IAAI;wBACbV,UAAU;wBACVW,MAAMC,KAAKC,SAAS,CAAC;4BAAEC,OAAO,AAACA,MAAgBa,OAAO;wBAAC;oBACzD;iBACD;YACH;QACF;IACF;IAEA,OAAO;QACLD,MAAM;QACN/B;QACAG;QACAG;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/resources/file.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport type { ResourceConfig, ResourceModule } from '@mcp-z/server';\nimport { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport type { ReadResourceResult, ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';\nimport { google } from 'googleapis';\n\nexport default function createResource() {\n const template = new ResourceTemplate('drive://files/{fileId}', {\n list: undefined,\n });\n const config: ResourceConfig = {\n description: 'Drive file resource',\n mimeType: 'application/json',\n };\n\n const handler = async (uri: URL, variables: Record<string, string | string[]>, extra: RequestHandlerExtra<ServerRequest, ServerNotification>): Promise<ReadResourceResult> => {\n // Extract fileId and handle both string and string[] cases\n const fileId = Array.isArray(variables.fileId) ? variables.fileId[0] : variables.fileId;\n\n try {\n // Validate fileId exists and is a string\n if (!fileId || typeof fileId !== 'string') {\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify({\n error: 'Missing or invalid fileId in resource URI',\n }),\n },\n ],\n };\n }\n\n // Safe type guard to access middleware-enriched extra\n const { logger, authContext } = extra as unknown as EnrichedExtra;\n const drive = google.drive({ version: 'v3', auth: authContext.auth });\n const resp = await drive.files.get({\n fileId,\n fields: 'id,name,mimeType,size,modifiedTime,owners,webViewLink',\n });\n const data = resp.data;\n logger.debug?.({ fileId, fileName: data?.name }, 'drive-file resource fetch success');\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify(data || {}),\n },\n ],\n };\n } catch (error) {\n const { logger } = extra as unknown as EnrichedExtra;\n logger.debug?.(error as Record<string, unknown>, 'drive resource fetch failed');\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify({ error: (error as Error).message }),\n },\n ],\n };\n }\n };\n\n return {\n name: 'file',\n template,\n config,\n handler,\n } satisfies ResourceModule;\n}\n"],"names":["ResourceTemplate","google","createResource","template","list","undefined","config","description","mimeType","handler","uri","variables","extra","fileId","Array","isArray","logger","contents","href","text","JSON","stringify","error","authContext","drive","version","auth","resp","files","get","fields","data","debug","fileName","name","message"],"mappings":"AAEA,SAASA,gBAAgB,QAAQ,0CAA0C;AAG3E,SAASC,MAAM,QAAQ,aAAa;AAEpC,eAAe,SAASC;IACtB,MAAMC,WAAW,IAAIH,iBAAiB,0BAA0B;QAC9DI,MAAMC;IACR;IACA,MAAMC,SAAyB;QAC7BC,aAAa;QACbC,UAAU;IACZ;IAEA,MAAMC,UAAU,OAAOC,KAAUC,WAA8CC;QAC7E,2DAA2D;QAC3D,MAAMC,SAASC,MAAMC,OAAO,CAACJ,UAAUE,MAAM,IAAIF,UAAUE,MAAM,CAAC,EAAE,GAAGF,UAAUE,MAAM;QAEvF,IAAI;gBAwBFG;YAvBA,yCAAyC;YACzC,IAAI,CAACH,UAAU,OAAOA,WAAW,UAAU;gBACzC,OAAO;oBACLI,UAAU;wBACR;4BACEP,KAAKA,IAAIQ,IAAI;4BACbV,UAAU;4BACVW,MAAMC,KAAKC,SAAS,CAAC;gCACnBC,OAAO;4BACT;wBACF;qBACD;gBACH;YACF;YAEA,sDAAsD;YACtD,MAAM,EAAEN,MAAM,EAAEO,WAAW,EAAE,GAAGX;YAChC,MAAMY,QAAQvB,OAAOuB,KAAK,CAAC;gBAAEC,SAAS;gBAAMC,MAAMH,YAAYG,IAAI;YAAC;YACnE,MAAMC,OAAO,MAAMH,MAAMI,KAAK,CAACC,GAAG,CAAC;gBACjChB;gBACAiB,QAAQ;YACV;YACA,MAAMC,OAAOJ,KAAKI,IAAI;aACtBf,gBAAAA,OAAOgB,KAAK,cAAZhB,oCAAAA,mBAAAA,QAAe;gBAAEH;gBAAQoB,QAAQ,EAAEF,iBAAAA,2BAAAA,KAAMG,IAAI;YAAC,GAAG;YACjD,OAAO;gBACLjB,UAAU;oBACR;wBACEP,KAAKA,IAAIQ,IAAI;wBACbV,UAAU;wBACVW,MAAMC,KAAKC,SAAS,CAACU,QAAQ,CAAC;oBAChC;iBACD;YACH;QACF,EAAE,OAAOT,OAAO;gBAEdN;YADA,MAAM,EAAEA,MAAM,EAAE,GAAGJ;aACnBI,iBAAAA,OAAOgB,KAAK,cAAZhB,qCAAAA,oBAAAA,QAAeM,OAAkC;YACjD,OAAO;gBACLL,UAAU;oBACR;wBACEP,KAAKA,IAAIQ,IAAI;wBACbV,UAAU;wBACVW,MAAMC,KAAKC,SAAS,CAAC;4BAAEC,OAAO,AAACA,MAAgBa,OAAO;wBAAC;oBACzD;iBACD;YACH;QACF;IACF;IAEA,OAAO;QACLD,MAAM;QACN/B;QACAG;QACAG;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/mcp-drive/src/mcp/resources/index.ts"],"sourcesContent":["export { default as file } from './file.ts';\n"],"names":["default","file"],"mappings":"AAAA,SAASA,WAAWC,IAAI,QAAQ,YAAY"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/resources/index.ts"],"sourcesContent":["export { default as file } from './file.ts';\n"],"names":["default","file"],"mappings":"AAAA,SAASA,WAAWC,IAAI,QAAQ,YAAY"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/mcp-drive/src/mcp/tools/file-move-to-trash.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { type CallToolResult, ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\n\nconst MAX_BATCH_SIZE = 1000;\n\nconst inputSchema = z.object({\n ids: z.array(z.string().min(1)).min(1).max(MAX_BATCH_SIZE).describe('File IDs to soft delete (move to trash)'),\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n operationSummary: z.string().describe('Human-readable summary of the operation'),\n totalCount: z.number().describe('Total number of files requested to trash'),\n successCount: z.number().describe('Number of files successfully moved to trash'),\n failureCount: z.number().describe('Number of files that failed to move'),\n recoverable: z.boolean().describe('Whether trashed files can be restored'),\n recoverableDays: z.number().describe('Days until permanent deletion'),\n failures: z\n .array(\n z.object({\n id: z.string().describe('ID of the file that failed'),\n error: z.string().describe('Error message explaining the failure'),\n })\n )\n .optional()\n .describe('Details of any files that failed to trash'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n title: 'Move Files to Trash',\n description: 'Move files to trash (recoverable for 30 days).',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ ids }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('drive.file.moveToTrash called', { count: ids.length });\n\n try {\n const drive = google.drive({ version: 'v3', auth: extra.authContext.auth });\n\n const results = await Promise.allSettled(\n ids.map(async (id) => {\n await drive.files.update({\n fileId: id,\n requestBody: { trashed: true },\n });\n return id;\n })\n );\n\n // Separate successes and failures\n const failures: Array<{ id: string; error: string }> = [];\n\n results.forEach((result, index) => {\n const id = ids[index];\n if (!id) return;\n\n if (result.status === 'rejected') {\n const errorMessage = result.reason instanceof Error ? result.reason.message : String(result.reason);\n failures.push({ id, error: errorMessage });\n }\n });\n\n const successCount = ids.length - failures.length;\n const failureCount = failures.length;\n const totalCount = ids.length;\n\n logger.info('drive.file.moveToTrash completed', {\n totalCount,\n successCount,\n failureCount,\n });\n\n const operationSummary = failureCount === 0 ? `Moved ${successCount} file${successCount === 1 ? '' : 's'} to trash (recoverable for 30 days)` : `Moved ${successCount} of ${totalCount} file${totalCount === 1 ? '' : 's'} to trash (${failureCount} failed, recoverable for 30 days)`;\n\n const result: Output = {\n type: 'success' as const,\n operationSummary,\n totalCount,\n successCount,\n failureCount,\n recoverable: true,\n recoverableDays: 30,\n ...(failures.length > 0 && { failures }),\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('drive.file.moveToTrash error', { error: message });\n\n // Throw McpError\n throw new McpError(ErrorCode.InternalError, `Error moving files to trash: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'file-move-to-trash' as const,\n config,\n handler,\n };\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ErrorCode","McpError","google","z","MAX_BATCH_SIZE","inputSchema","object","ids","array","string","min","max","describe","successBranchSchema","type","literal","operationSummary","totalCount","number","successCount","failureCount","recoverable","boolean","recoverableDays","failures","id","error","optional","outputSchema","discriminatedUnion","config","title","description","result","handler","extra","logger","info","count","length","drive","version","auth","authContext","results","Promise","allSettled","map","files","update","fileId","requestBody","trashed","forEach","index","status","errorMessage","reason","Error","message","String","push","content","text","JSON","stringify","structuredContent","InternalError","stack","undefined","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAErC,SAA8BE,SAAS,EAAEC,QAA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MAAM,GAAG,KAAK;gBAAEf;YAAS,CAAC;QACzC;QAEA,OAAO;YACLsC,SAAS;gBACP;oBACEhD,MAAM;oBACNiD,MAAMC,KAAKC,SAAS,CAAChC;gBACvB;aACD;YACDiC,mBAAmB;gBAAEjC;YAAO;QAC9B;IACF,EAAE,OAAOP,OAAO;QACd,MAAMiC,UAAUjC,iBAAiBgC,QAAQhC,MAAMiC,OAAO,GAAGC,OAAOlC;QAChEU,OAAOV,KAAK,CAAC,gCAAgC;YAAEA,OAAOiC;QAAQ;QAE9D,iBAAiB;QACjB,MAAM,IAAI1D,SAASD,UAAUmE,aAAa,EAAE,CAAC,6BAA6B,EAAER,SAAS,EAAE;YACrFS,OAAO1C,iBAAiBgC,QAAQhC,MAAM0C,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QACLC,MAAM;QACNzC;QACAI;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/tools/file-move-to-trash.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { type CallToolResult, ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\n\nconst MAX_BATCH_SIZE = 1000;\n\nconst inputSchema = z.object({\n ids: z.array(z.string().min(1)).min(1).max(MAX_BATCH_SIZE).describe('File IDs to soft delete (move to trash)'),\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n operationSummary: z.string().describe('Human-readable summary of the operation'),\n totalCount: z.number().describe('Total number of files requested to trash'),\n successCount: z.number().describe('Number of files successfully moved to trash'),\n failureCount: z.number().describe('Number of files that failed to move'),\n recoverable: z.boolean().describe('Whether trashed files can be restored'),\n recoverableDays: z.number().describe('Days until permanent deletion'),\n failures: z\n .array(\n z.object({\n id: z.string().describe('ID of the file that failed'),\n error: z.string().describe('Error message explaining the failure'),\n })\n )\n .optional()\n .describe('Details of any files that failed to trash'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n title: 'Move Files to Trash',\n description: 'Move files to trash (recoverable for 30 days).',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ ids }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('drive.file.moveToTrash called', { count: ids.length });\n\n try {\n const drive = google.drive({ version: 'v3', auth: extra.authContext.auth });\n\n const results = await Promise.allSettled(\n ids.map(async (id) => {\n await drive.files.update({\n fileId: id,\n requestBody: { trashed: true },\n });\n return id;\n })\n );\n\n // Separate successes and failures\n const failures: Array<{ id: string; error: string }> = [];\n\n results.forEach((result, index) => {\n const id = ids[index];\n if (!id) return;\n\n if (result.status === 'rejected') {\n const errorMessage = result.reason instanceof Error ? result.reason.message : String(result.reason);\n failures.push({ id, error: errorMessage });\n }\n });\n\n const successCount = ids.length - failures.length;\n const failureCount = failures.length;\n const totalCount = ids.length;\n\n logger.info('drive.file.moveToTrash completed', {\n totalCount,\n successCount,\n failureCount,\n });\n\n const operationSummary = failureCount === 0 ? `Moved ${successCount} file${successCount === 1 ? '' : 's'} to trash (recoverable for 30 days)` : `Moved ${successCount} of ${totalCount} file${totalCount === 1 ? '' : 's'} to trash (${failureCount} failed, recoverable for 30 days)`;\n\n const result: Output = {\n type: 'success' as const,\n operationSummary,\n totalCount,\n successCount,\n failureCount,\n recoverable: true,\n recoverableDays: 30,\n ...(failures.length > 0 && { failures }),\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('drive.file.moveToTrash error', { error: message });\n\n // Throw McpError\n throw new McpError(ErrorCode.InternalError, `Error moving files to trash: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'file-move-to-trash' as const,\n config,\n handler,\n };\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ErrorCode","McpError","google","z","MAX_BATCH_SIZE","inputSchema","object","ids","array","string","min","max","describe","successBranchSchema","type","literal","operationSummary","totalCount","number","successCount","failureCount","recoverable","boolean","recoverableDays","failures","id","error","optional","outputSchema","discriminatedUnion","config","title","description","result","handler","extra","logger","info","count","length","drive","version","auth","authContext","results","Promise","allSettled","map","files","update","fileId","requestBody","trashed","forEach","index","status","errorMessage","reason","Error","message","String","push","content","text","JSON","stringify","structuredContent","InternalError","stack","undefined","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAErC,SAA8BE,SAAS,EAAEC,QAAQ,QAAQ,qCAAqC;AAC9F,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,CAAC,QAAQ,MAAM;AAExB,MAAMC,iBAAiB;AAEvB,MAAMC,cAAcF,EAAEG,MAAM,CAAC;IAC3BC,KAAKJ,EAAEK,KAAK,CAACL,EAAEM,MAAM,GAAGC,GAAG,CAAC,IAAIA,GAAG,CAAC,GAAGC,GAAG,CAACP,gBAAgBQ,QAAQ,CAAC;AACtE;AAEA,wBAAwB;AACxB,MAAMC,sBAAsBV,EAAEG,MAAM,CAAC;IACnCQ,MAAMX,EAAEY,OAAO,CAAC;IAChBC,kBAAkBb,EAAEM,MAAM,GAAGG,QAAQ,CAAC;IACtCK,YAAYd,EAAEe,MAAM,GAAGN,QAAQ,CAAC;IAChCO,cAAchB,EAAEe,MAAM,GAAGN,QAAQ,CAAC;IAClCQ,cAAcjB,EAAEe,MAAM,GAAGN,QAAQ,CAAC;IAClCS,aAAalB,EAAEmB,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["/Users/kevin/Dev/Projects/mcp-z/mcp-drive/src/mcp/tools/file-move.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { type CallToolResult, ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport type { drive_v3 } from 'googleapis';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport type { Logger } from '../../types.ts';\n\n// Type guard for Google Drive API errors\ninterface DriveApiError {\n message?: string;\n code?: number | string;\n}\n\nfunction isDriveApiError(error: unknown): error is DriveApiError {\n return typeof error === 'object' && error !== null && ('message' in error || 'code' in error);\n}\n\n// Types for results\ninterface MoveResult {\n fileId: string;\n fileName: string;\n oldParents: string[];\n newParent: string;\n webViewLink?: string;\n}\n\ninterface FailedMove {\n fileId: string;\n error: string;\n code?: string;\n}\n\nconst inputSchema = z.object({\n fileIds: z.union([z.string().min(1), z.array(z.string().min(1)).min(1).max(100)]).describe('File or folder ID(s) to move. Single ID or array (max 100 for batch)'),\n destinationFolderId: z.string().min(1).describe('Destination folder ID (use \"root\" for My Drive root)'),\n returnOldParents: z.boolean().optional().describe('Include old parent IDs in response for manual undo (recommended: true)'),\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n moved: z\n .array(\n z.object({\n fileId: z.string().describe('ID of the moved file'),\n fileName: z.string().describe('Name of the moved file'),\n oldParents: z.array(z.string()).describe('Previous parent folder IDs (for undo)'),\n newParent: z.string().describe('New parent folder ID'),\n webViewLink: z.string().optional().describe('URL to view the file'),\n })\n )\n .describe('Successfully moved files'),\n failed: z\n .array(\n z.object({\n fileId: z.string().describe('ID of the file that failed to move'),\n error: z.string().describe('Error message explaining the failure'),\n code: z.string().optional().describe('API error code if available'),\n })\n )\n .optional()\n .describe('Files that failed to move'),\n totalRequested: z.number().describe('Total number of files requested to move'),\n totalMoved: z.number().describe('Number of files successfully moved'),\n totalFailed: z.number().describe('Number of files that failed to move'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n title: 'Move Files',\n description: 'Move files/folders to destination folder. Returns oldParents for undo. Use \"root\" for My Drive root.',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\n/**\n * Move a single file to a new parent folder\n */\nasync function moveSingleFile(\n drive: drive_v3.Drive,\n fileId: string,\n destinationFolderId: string,\n returnOldParents: boolean,\n logger: Logger\n): Promise<{\n success: boolean;\n result?: MoveResult;\n error?: FailedMove;\n}> {\n try {\n // Get current file metadata to get old parents\n const fileMetadata = await drive.files.get({\n fileId: fileId,\n fields: 'id,name,parents,webViewLink',\n });\n\n const oldParents = (fileMetadata.data.parents as string[] | undefined) || [];\n const fileName = (fileMetadata.data.name as string | undefined) || fileId;\n const webViewLink = fileMetadata.data.webViewLink as string | undefined;\n\n // Move file using addParents and removeParents\n await drive.files.update({\n fileId: fileId,\n addParents: destinationFolderId,\n removeParents: oldParents.join(','),\n fields: 'id,name,parents,webViewLink',\n });\n\n const result: MoveResult = {\n fileId: fileId,\n fileName: fileName,\n oldParents: returnOldParents ? oldParents : [],\n newParent: destinationFolderId,\n ...(webViewLink && { webViewLink }),\n };\n\n return { success: true, result };\n } catch (e: unknown) {\n const errorMessage = isDriveApiError(e) && e.message ? e.message : 'Unknown error';\n const errorCode = isDriveApiError(e) && e.code ? String(e.code) : undefined;\n logger.info('Failed to move file', { fileId, error: errorMessage });\n return {\n success: false,\n error: {\n fileId: fileId,\n error: errorMessage,\n ...(errorCode && { code: errorCode }),\n },\n };\n }\n}\n\n/**\n * Move multiple files using batch requests\n */\nasync function moveBatchFiles(\n drive: drive_v3.Drive,\n fileIds: string[],\n destinationFolderId: string,\n returnOldParents: boolean,\n _logger: Logger\n): Promise<{\n moved: MoveResult[];\n failed: FailedMove[];\n}> {\n const moved: MoveResult[] = [];\n const failed: FailedMove[] = [];\n\n // First, fetch metadata for all files in batch\n const metadataResults = await Promise.allSettled(\n fileIds.map(async (fileId) => {\n try {\n const response = await drive.files.get({\n fileId: fileId,\n fields: 'id,name,parents,webViewLink',\n });\n const webViewLink = response.data.webViewLink as string | undefined;\n return {\n fileId: fileId,\n name: (response.data.name as string | undefined) || fileId,\n parents: (response.data.parents as string[] | undefined) || [],\n ...(webViewLink && { webViewLink }),\n };\n } catch (e: unknown) {\n const message = isDriveApiError(e) && e.message ? e.message : String(e);\n throw new Error(`Failed to fetch metadata: ${message}`);\n }\n })\n );\n\n // Process metadata results\n const filesToMove: Array<{\n fileId: string;\n name: string;\n parents: string[];\n webViewLink?: string;\n }> = [];\n for (let i = 0; i < metadataResults.length; i++) {\n const result = metadataResults[i];\n if (result && result.status === 'fulfilled') {\n filesToMove.push(result.value);\n } else if (result && result.status === 'rejected') {\n const fileId = fileIds[i];\n if (fileId) {\n const errorCode = result.reason?.code ? String(result.reason.code) : undefined;\n failed.push({\n fileId: fileId,\n error: result.reason?.message || 'Failed to fetch file metadata',\n ...(errorCode && { code: errorCode }),\n });\n }\n }\n }\n\n // Now move files in batch\n const moveResults = await Promise.allSettled(\n filesToMove.map(async (file) => {\n try {\n await drive.files.update({\n fileId: file.fileId,\n addParents: destinationFolderId,\n removeParents: file.parents.join(','),\n fields: 'id',\n });\n return {\n fileId: file.fileId,\n fileName: file.name,\n oldParents: returnOldParents ? file.parents : [],\n newParent: destinationFolderId,\n ...(file.webViewLink && { webViewLink: file.webViewLink }),\n };\n } catch (e: unknown) {\n const message = isDriveApiError(e) && e.message ? e.message : String(e);\n throw new Error(`Failed to move: ${message}`);\n }\n })\n );\n\n // Process move results\n for (let i = 0; i < moveResults.length; i++) {\n const result = moveResults[i];\n if (result && result.status === 'fulfilled') {\n moved.push(result.value);\n } else if (result && result.status === 'rejected') {\n const file = filesToMove[i];\n if (file) {\n const errorCode = result.reason?.code ? String(result.reason.code) : undefined;\n failed.push({\n fileId: file.fileId,\n error: result.reason?.message || 'Failed to move file',\n ...(errorCode && { code: errorCode }),\n });\n }\n }\n }\n\n return { moved, failed };\n}\n\nasync function handler({ fileIds, destinationFolderId, returnOldParents = true }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n const isBatch = Array.isArray(fileIds);\n const fileIdArray = Array.isArray(fileIds) ? fileIds : [fileIds];\n\n logger.info('drive.file.move called', {\n fileCount: fileIdArray.length,\n isBatch,\n destinationFolderId,\n returnOldParents,\n });\n\n try {\n const drive = google.drive({ version: 'v3', auth: extra.authContext.auth });\n\n let moved: MoveResult[] = [];\n let failed: FailedMove[] = [];\n\n if (isBatch && fileIdArray.length > 1) {\n // Use batch API for multiple files\n const batchResult = await moveBatchFiles(drive, fileIdArray, destinationFolderId, returnOldParents, logger);\n moved = batchResult.moved;\n failed = batchResult.failed;\n } else {\n // Single file operation\n const fileId = fileIdArray[0];\n if (fileId) {\n const singleResult = await moveSingleFile(drive, fileId, destinationFolderId, returnOldParents, logger);\n if (singleResult.success && singleResult.result) {\n moved.push(singleResult.result);\n } else if (singleResult.error) {\n failed.push(singleResult.error);\n }\n }\n }\n\n logger.info('drive.file.move returning', {\n totalRequested: fileIdArray.length,\n totalMoved: moved.length,\n totalFailed: failed.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n moved,\n ...(failed.length > 0 && { failed }),\n totalRequested: fileIdArray.length,\n totalMoved: moved.length,\n totalFailed: failed.length,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('drive.file.move error', { error: message });\n\n // Throw McpError\n throw new McpError(ErrorCode.InternalError, `Error moving files: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'file-move' as const,\n config,\n handler,\n };\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ErrorCode","McpError","google","z","isDriveApiError","error","inputSchema","object","fileIds","union","string","min","array","max","describe","destinationFolderId","returnOldParents","boolean","optional","successBranchSchema","type","literal","moved","fileId","fileName","oldParents","newParent","webViewLink","failed","code","totalRequested","number","totalMoved","totalFailed","outputSchema","discriminatedUnion","config","title","description","result","moveSingleFile","drive","logger","fileMetadata","files","get","fields","data","parents","name","update","addParents","removeParents","join","success","e","errorMessage","message","errorCode","String","undefined","info","moveBatchFiles","_logger","metadataResults","Promise","allSettled","map","response","Error","filesToMove","i","length","status","push","value","reason","moveResults","file","handler","extra","isBatch","Array","isArray","fileIdArray","fileCount","version","auth","authContext","batchResult","singleResult","content","text","JSON","stringify","structuredContent","InternalError","stack","createTool"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAErC,SAA8BE,SAAS,EAAEC,QAAQ,QAAQ,qCAAqC;AAE9F,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,CAAC,QAAQ,MAAM;AASxB,SAASC,gBAAgBC,KAAc;IACrC,OAAO,OAAOA,UAAU,YAAYA,UAAU,QAAS,CAAA,aAAaA,SAAS,UAAUA,KAAI;AAC7F;AAiBA,MAAMC,cAAcH,EAAEI,MAAM,CAAC;IAC3BC,SAASL,EAAEM,KAAK,CAAC;QAACN,EAAEO,MAAM,GAAGC,GAAG,CAAC;QAAIR,EAAES,KAAK,CAACT,EAAEO,MAAM,GAAGC,GAAG,CAAC,IAAIA,GAAG,CAAC,GAAGE,GAAG,CAAC;KAAK,EAAEC,QAAQ,CAAC;IAC3FC,qBAAqBZ,EAAEO,MAAM,GAAGC,GAAG,CAAC,GAAGG,QAAQ,CAAC;IAChDE,kBAAkBb,EAAEc,OAAO,GAAGC,QAAQ,GAAGJ,QAAQ,CAAC;AACpD;AAEA,wBAAwB;AACxB,MAAMK,sBAAsBhB,EAAEI,MAAM,CAAC;IACn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gBAChC;YACF;QACF;QAEAqC,OAAOmB,IAAI,CAAC,6BAA6B;YACvC/B,gBAAgBsD,YAAYZ,MAAM;YAClCxC,YAAYV,MAAMkD,MAAM;YACxBvC,aAAaL,OAAO4C,MAAM;QAC5B;QAEA,MAAMjC,SAAiB;YACrBnB,MAAM;YACNE;YACA,GAAIM,OAAO4C,MAAM,GAAG,KAAK;gBAAE5C;YAAO,CAAC;YACnCE,gBAAgBsD,YAAYZ,MAAM;YAClCxC,YAAYV,MAAMkD,MAAM;YACxBvC,aAAaL,OAAO4C,MAAM;QAC5B;QAEA,OAAO;YACLmB,SAAS;gBACP;oBACEvE,MAAM;oBACNwE,MAAMC,KAAKC,SAAS,CAACvD;gBACvB;aACD;YACDwD,mBAAmB;gBAAExD;YAAO;QAC9B;IACF,EAAE,OAAOlC,OAAO;QACd,MAAMoD,UAAUpD,iBAAiBgE,QAAQhE,MAAMoD,OAAO,GAAGE,OAAOtD;QAChEqC,OAAOrC,KAAK,CAAC,yBAAyB;YAAEA,OAAOoD;QAAQ;QAEvD,iBAAiB;QACjB,MAAM,IAAIxD,SAASD,UAAUgG,aAAa,EAAE,CAAC,oBAAoB,EAAEvC,SAAS,EAAE;YAC5EwC,OAAO5F,iBAAiBgE,QAAQhE,MAAM4F,KAAK,GAAGrC;QAChD;IACF;AACF;AAEA,eAAe,SAASsC;IACtB,OAAO;QACLjD,MAAM;QACNb;QACA2C;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/tools/file-move.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { type CallToolResult, ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport type { drive_v3 } from 'googleapis';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport type { Logger } from '../../types.ts';\n\n// Type guard for Google Drive API errors\ninterface DriveApiError {\n message?: string;\n code?: number | string;\n}\n\nfunction isDriveApiError(error: unknown): error is DriveApiError {\n return typeof error === 'object' && error !== null && ('message' in error || 'code' in error);\n}\n\n// Types for results\ninterface MoveResult {\n fileId: string;\n fileName: string;\n oldParents: string[];\n newParent: string;\n webViewLink?: string;\n}\n\ninterface FailedMove {\n fileId: string;\n error: string;\n code?: string;\n}\n\nconst inputSchema = z.object({\n fileIds: z.union([z.string().min(1), z.array(z.string().min(1)).min(1).max(100)]).describe('File or folder ID(s) to move. Single ID or array (max 100 for batch)'),\n destinationFolderId: z.string().min(1).describe('Destination folder ID (use \"root\" for My Drive root)'),\n returnOldParents: z.boolean().optional().describe('Include old parent IDs in response for manual undo (recommended: true)'),\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n moved: z\n .array(\n z.object({\n fileId: z.string().describe('ID of the moved file'),\n fileName: z.string().describe('Name of the moved file'),\n oldParents: z.array(z.string()).describe('Previous parent folder IDs (for undo)'),\n newParent: z.string().describe('New parent folder ID'),\n webViewLink: z.string().optional().describe('URL to view the file'),\n })\n )\n .describe('Successfully moved files'),\n failed: z\n .array(\n z.object({\n fileId: z.string().describe('ID of the file that failed to move'),\n error: z.string().describe('Error message explaining the failure'),\n code: z.string().optional().describe('API error code if available'),\n })\n )\n .optional()\n .describe('Files that failed to move'),\n totalRequested: z.number().describe('Total number of files requested to move'),\n totalMoved: z.number().describe('Number of files successfully moved'),\n totalFailed: z.number().describe('Number of files that failed to move'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n title: 'Move Files',\n description: 'Move files/folders to destination folder. Returns oldParents for undo. Use \"root\" for My Drive root.',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\n/**\n * Move a single file to a new parent folder\n */\nasync function moveSingleFile(\n drive: drive_v3.Drive,\n fileId: string,\n destinationFolderId: string,\n returnOldParents: boolean,\n logger: Logger\n): Promise<{\n success: boolean;\n result?: MoveResult;\n error?: FailedMove;\n}> {\n try {\n // Get current file metadata to get old parents\n const fileMetadata = await drive.files.get({\n fileId: fileId,\n fields: 'id,name,parents,webViewLink',\n });\n\n const oldParents = (fileMetadata.data.parents as string[] | undefined) || [];\n const fileName = (fileMetadata.data.name as string | undefined) || fileId;\n const webViewLink = fileMetadata.data.webViewLink as string | undefined;\n\n // Move file using addParents and removeParents\n await drive.files.update({\n fileId: fileId,\n addParents: destinationFolderId,\n removeParents: oldParents.join(','),\n fields: 'id,name,parents,webViewLink',\n });\n\n const result: MoveResult = {\n fileId: fileId,\n fileName: fileName,\n oldParents: returnOldParents ? oldParents : [],\n newParent: destinationFolderId,\n ...(webViewLink && { webViewLink }),\n };\n\n return { success: true, result };\n } catch (e: unknown) {\n const errorMessage = isDriveApiError(e) && e.message ? e.message : 'Unknown error';\n const errorCode = isDriveApiError(e) && e.code ? String(e.code) : undefined;\n logger.info('Failed to move file', { fileId, error: errorMessage });\n return {\n success: false,\n error: {\n fileId: fileId,\n error: errorMessage,\n ...(errorCode && { code: errorCode }),\n },\n };\n }\n}\n\n/**\n * Move multiple files using batch requests\n */\nasync function moveBatchFiles(\n drive: drive_v3.Drive,\n fileIds: string[],\n destinationFolderId: string,\n returnOldParents: boolean,\n _logger: Logger\n): Promise<{\n moved: MoveResult[];\n failed: FailedMove[];\n}> {\n const moved: MoveResult[] = [];\n const failed: FailedMove[] = [];\n\n // First, fetch metadata for all files in batch\n const metadataResults = await Promise.allSettled(\n fileIds.map(async (fileId) => {\n try {\n const response = await drive.files.get({\n fileId: fileId,\n fields: 'id,name,parents,webViewLink',\n });\n const webViewLink = response.data.webViewLink as string | undefined;\n return {\n fileId: fileId,\n name: (response.data.name as string | undefined) || fileId,\n parents: (response.data.parents as string[] | undefined) || [],\n ...(webViewLink && { webViewLink }),\n };\n } catch (e: unknown) {\n const message = isDriveApiError(e) && e.message ? e.message : String(e);\n throw new Error(`Failed to fetch metadata: ${message}`);\n }\n })\n );\n\n // Process metadata results\n const filesToMove: Array<{\n fileId: string;\n name: string;\n parents: string[];\n webViewLink?: string;\n }> = [];\n for (let i = 0; i < metadataResults.length; i++) {\n const result = metadataResults[i];\n if (result && result.status === 'fulfilled') {\n filesToMove.push(result.value);\n } else if (result && result.status === 'rejected') {\n const fileId = fileIds[i];\n if (fileId) {\n const errorCode = result.reason?.code ? String(result.reason.code) : undefined;\n failed.push({\n fileId: fileId,\n error: result.reason?.message || 'Failed to fetch file metadata',\n ...(errorCode && { code: errorCode }),\n });\n }\n }\n }\n\n // Now move files in batch\n const moveResults = await Promise.allSettled(\n filesToMove.map(async (file) => {\n try {\n await drive.files.update({\n fileId: file.fileId,\n addParents: destinationFolderId,\n removeParents: file.parents.join(','),\n fields: 'id',\n });\n return {\n fileId: file.fileId,\n fileName: file.name,\n oldParents: returnOldParents ? file.parents : [],\n newParent: destinationFolderId,\n ...(file.webViewLink && { webViewLink: file.webViewLink }),\n };\n } catch (e: unknown) {\n const message = isDriveApiError(e) && e.message ? e.message : String(e);\n throw new Error(`Failed to move: ${message}`);\n }\n })\n );\n\n // Process move results\n for (let i = 0; i < moveResults.length; i++) {\n const result = moveResults[i];\n if (result && result.status === 'fulfilled') {\n moved.push(result.value);\n } else if (result && result.status === 'rejected') {\n const file = filesToMove[i];\n if (file) {\n const errorCode = result.reason?.code ? String(result.reason.code) : undefined;\n failed.push({\n fileId: file.fileId,\n error: result.reason?.message || 'Failed to move file',\n ...(errorCode && { code: errorCode }),\n });\n }\n }\n }\n\n return { moved, failed };\n}\n\nasync function handler({ fileIds, destinationFolderId, returnOldParents = true }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n const isBatch = Array.isArray(fileIds);\n const fileIdArray = Array.isArray(fileIds) ? fileIds : [fileIds];\n\n logger.info('drive.file.move called', {\n fileCount: fileIdArray.length,\n isBatch,\n destinationFolderId,\n returnOldParents,\n });\n\n try {\n const drive = google.drive({ version: 'v3', auth: extra.authContext.auth });\n\n let moved: MoveResult[] = [];\n let failed: FailedMove[] = [];\n\n if (isBatch && fileIdArray.length > 1) {\n // Use batch API for multiple files\n const batchResult = await moveBatchFiles(drive, fileIdArray, destinationFolderId, returnOldParents, logger);\n moved = batchResult.moved;\n failed = batchResult.failed;\n } else {\n // Single file operation\n const fileId = fileIdArray[0];\n if (fileId) {\n const singleResult = await moveSingleFile(drive, fileId, destinationFolderId, returnOldParents, logger);\n if (singleResult.success && singleResult.result) {\n moved.push(singleResult.result);\n } else if (singleResult.error) {\n failed.push(singleResult.error);\n }\n }\n }\n\n logger.info('drive.file.move returning', {\n totalRequested: fileIdArray.length,\n totalMoved: moved.length,\n totalFailed: failed.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n moved,\n ...(failed.length > 0 && { failed }),\n totalRequested: fileIdArray.length,\n totalMoved: moved.length,\n totalFailed: failed.length,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('drive.file.move error', { error: message });\n\n // Throw McpError\n throw new McpError(ErrorCode.InternalError, `Error moving files: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'file-move' as const,\n config,\n handler,\n };\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ErrorCode","McpError","google","z","isDriveApiError","error","inputSchema","object","fileIds","union","string","min","array","max","describe","destinationFolderId","returnOldParents","boolean","optional","successBranchSchema","type","literal","moved","fileId","fileName","oldParents","newParent","webViewLink","failed","code","totalRequested","number","totalMoved","totalFailed","outputSchema","discriminatedUnion","config","title","description","result","moveSingleFile","drive","logger","fileMetadata","files","get","fields","data","parents","name","update","addParents","removeParents","join","success","e","errorMessage","message","errorCode","String","undefined","info","moveBatchFiles","_logger","metadataResults","Promise","allSettled","map","response","Error","filesToMove","i","length","status","push","value","reason","moveResults","file","handler","extra","isBatch","Array","isArray","fileIdArray","fileCount","version","auth","authContext","batchResult","singleResult","content","text","JSON","stringify","structuredContent","InternalError","stack","createTool"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAErC,SAA8BE,SAAS,EAAEC,QAAQ,QAAQ,qCAAqC;AAE9F,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,CAAC,QAAQ,MAAM;AASxB,SAASC,gBAAgBC,KAAc;IACrC,OAAO,OAAOA,UAAU,YAAYA,UAAU,QAAS,CAAA,aAAaA,SAAS,UAAUA,KAAI;AAC7F;AAiBA,MAAMC,cAAcH,EAAEI,MAAM,CAAC;IAC3BC,SAASL,EAAEM,KAAK,CAAC;QAACN,EAAEO,MAAM,GAAGC,GAAG,CAAC;QAAIR,EAAES,KAAK,CAACT,EAAEO,MAAM,GAAGC,GAAG,CAAC,IAAIA,GAAG,CAAC,GAAGE,GAAG,CAAC;KAAK,EAAEC,QAAQ,CAAC;IAC3FC,qBAAqBZ,EAAEO,MAAM,GAAGC,GAAG,CAAC,GAAGG,QAAQ,CAAC;IAChDE,kBAAkBb,EAAEc,OAAO,GAAGC,QAAQ,GAAGJ,QAAQ,CAAC;AACpD;AAEA,wBAAwB;AACxB,MAAMK,sBAAsBhB,EAAEI,MAAM,CAAC;IACnCa,MAAMjB,EAAEkB,OAAO,CAAC;IAChBC,OAAOnB,EACJS,KAAK,CACJT,EAAEI,MAAM,CAAC;QACPgB,QAAQpB,EAAEO,MAAM,GAAGI,QAAQ,CAAC;QAC5BU,UAAUrB,EAAEO,MAAM,GAAGI,QAAQ,CAAC;QAC9BW,YAAYtB,EAAES,KAAK,CAACT,EAAEO,MAAM,IAAII,QAAQ,CAAC;QACzCY,WAAWvB,EAAEO,MAAM,GAAGI,QAAQ,CAAC;QAC/Ba,aAAaxB,E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ACxBvC,aAAaL,OAAO4C,MAAM;QAC5B;QAEA,OAAO;YACLmB,SAAS;gBACP;oBACEvE,MAAM;oBACNwE,MAAMC,KAAKC,SAAS,CAACvD;gBACvB;aACD;YACDwD,mBAAmB;gBAAExD;YAAO;QAC9B;IACF,EAAE,OAAOlC,OAAO;QACd,MAAMoD,UAAUpD,iBAAiBgE,QAAQhE,MAAMoD,OAAO,GAAGE,OAAOtD;QAChEqC,OAAOrC,KAAK,CAAC,yBAAyB;YAAEA,OAAOoD;QAAQ;QAEvD,iBAAiB;QACjB,MAAM,IAAIxD,SAASD,UAAUgG,aAAa,EAAE,CAAC,oBAAoB,EAAEvC,SAAS,EAAE;YAC5EwC,OAAO5F,iBAAiBgE,QAAQhE,MAAM4F,KAAK,GAAGrC;QAChD;IACF;AACF;AAEA,eAAe,SAASsC;IACtB,OAAO;QACLjD,MAAM;QACNb;QACA2C;IACF;AACF"}
@@ -0,0 +1,69 @@
1
+ import type { EnrichedExtra } from '@mcp-z/oauth-google';
2
+ import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
3
+ import { z } from 'zod';
4
+ declare const inputSchema: z.ZodObject<{
5
+ sourceUri: z.ZodString;
6
+ name: z.ZodOptional<z.ZodString>;
7
+ mimeType: z.ZodOptional<z.ZodString>;
8
+ parentId: z.ZodOptional<z.ZodString>;
9
+ description: z.ZodOptional<z.ZodString>;
10
+ }, z.core.$strip>;
11
+ declare const outputSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
12
+ type: z.ZodLiteral<"success">;
13
+ operationSummary: z.ZodString;
14
+ itemsProcessed: z.ZodNumber;
15
+ itemsChanged: z.ZodNumber;
16
+ completedAt: z.ZodString;
17
+ id: z.ZodString;
18
+ name: z.ZodString;
19
+ mimeType: z.ZodString;
20
+ size: z.ZodString;
21
+ webViewLink: z.ZodString;
22
+ parentId: z.ZodOptional<z.ZodString>;
23
+ parentName: z.ZodOptional<z.ZodString>;
24
+ }, z.core.$strip>, z.ZodObject<{
25
+ type: z.ZodLiteral<"auth_required">;
26
+ provider: z.ZodString;
27
+ message: z.ZodString;
28
+ url: z.ZodOptional<z.ZodString>;
29
+ }, z.core.$strip>], "type">;
30
+ export type Input = z.infer<typeof inputSchema>;
31
+ export type Output = z.infer<typeof outputSchema>;
32
+ declare function handler({ sourceUri, name, mimeType, parentId, description }: Input, extra: EnrichedExtra): Promise<CallToolResult>;
33
+ export default function createTool(): {
34
+ name: "file-upload";
35
+ config: {
36
+ readonly title: "Upload File";
37
+ readonly description: "Upload a file to Google Drive from a file:// or http(s):// URI. Content is streamed from the source (no temp files) in a single multipart request. Returns file ID for use in other operations.";
38
+ readonly inputSchema: z.ZodObject<{
39
+ sourceUri: z.ZodString;
40
+ name: z.ZodOptional<z.ZodString>;
41
+ mimeType: z.ZodOptional<z.ZodString>;
42
+ parentId: z.ZodOptional<z.ZodString>;
43
+ description: z.ZodOptional<z.ZodString>;
44
+ }, z.core.$strip>;
45
+ readonly outputSchema: z.ZodObject<{
46
+ result: z.ZodDiscriminatedUnion<[z.ZodObject<{
47
+ type: z.ZodLiteral<"success">;
48
+ operationSummary: z.ZodString;
49
+ itemsProcessed: z.ZodNumber;
50
+ itemsChanged: z.ZodNumber;
51
+ completedAt: z.ZodString;
52
+ id: z.ZodString;
53
+ name: z.ZodString;
54
+ mimeType: z.ZodString;
55
+ size: z.ZodString;
56
+ webViewLink: z.ZodString;
57
+ parentId: z.ZodOptional<z.ZodString>;
58
+ parentName: z.ZodOptional<z.ZodString>;
59
+ }, z.core.$strip>, z.ZodObject<{
60
+ type: z.ZodLiteral<"auth_required">;
61
+ provider: z.ZodString;
62
+ message: z.ZodString;
63
+ url: z.ZodOptional<z.ZodString>;
64
+ }, z.core.$strip>], "type">;
65
+ }, z.core.$strip>;
66
+ };
67
+ handler: typeof handler;
68
+ };
69
+ export {};