@mcp-z/mcp-drive 2.4.2 → 2.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/bin/server.js +1 -1
  2. package/dist/cjs/constants.js.map +1 -1
  3. package/dist/cjs/index.js.map +1 -1
  4. package/dist/cjs/lib/create-store.js.map +1 -1
  5. package/dist/cjs/lib/file-streaming.js.map +1 -1
  6. package/dist/cjs/lib/google-auth.js.map +1 -1
  7. package/dist/cjs/lib/query-builder.js.map +1 -1
  8. package/dist/cjs/mcp/index.js.map +1 -1
  9. package/dist/cjs/mcp/prompts/index.js.map +1 -1
  10. package/dist/cjs/mcp/prompts/organize-files.js.map +1 -1
  11. package/dist/cjs/mcp/prompts/query-syntax.js.map +1 -1
  12. package/dist/cjs/mcp/resources/file.js.map +1 -1
  13. package/dist/cjs/mcp/resources/index.js.map +1 -1
  14. package/dist/cjs/mcp/tools/file-move-to-trash.js.map +1 -1
  15. package/dist/cjs/mcp/tools/file-move.js.map +1 -1
  16. package/dist/cjs/mcp/tools/file-upload.js.map +1 -1
  17. package/dist/cjs/mcp/tools/files-search.js.map +1 -1
  18. package/dist/cjs/mcp/tools/folder-contents.js.map +1 -1
  19. package/dist/cjs/mcp/tools/folder-create.js.map +1 -1
  20. package/dist/cjs/mcp/tools/folder-path.js.map +1 -1
  21. package/dist/cjs/mcp/tools/folder-search.js.map +1 -1
  22. package/dist/cjs/mcp/tools/index.js.map +1 -1
  23. package/dist/cjs/schemas/drive-query-schema.js.map +1 -1
  24. package/dist/cjs/schemas/drive-validation.js.map +1 -1
  25. package/dist/cjs/schemas/index.js.map +1 -1
  26. package/dist/cjs/setup/config.js.map +1 -1
  27. package/dist/cjs/setup/http.js.map +1 -1
  28. package/dist/cjs/setup/index.js.map +1 -1
  29. package/dist/cjs/setup/oauth-google.js.map +1 -1
  30. package/dist/cjs/setup/runtime.js.map +1 -1
  31. package/dist/cjs/setup/stdio.js.map +1 -1
  32. package/dist/cjs/setup/version-help.js.map +1 -1
  33. package/dist/esm/constants.js.map +1 -1
  34. package/dist/esm/index.js.map +1 -1
  35. package/dist/esm/lib/create-store.js.map +1 -1
  36. package/dist/esm/lib/file-streaming.js.map +1 -1
  37. package/dist/esm/lib/google-auth.js.map +1 -1
  38. package/dist/esm/lib/query-builder.js.map +1 -1
  39. package/dist/esm/mcp/index.js.map +1 -1
  40. package/dist/esm/mcp/prompts/index.js.map +1 -1
  41. package/dist/esm/mcp/prompts/organize-files.js.map +1 -1
  42. package/dist/esm/mcp/prompts/query-syntax.js.map +1 -1
  43. package/dist/esm/mcp/resources/file.js.map +1 -1
  44. package/dist/esm/mcp/resources/index.js.map +1 -1
  45. package/dist/esm/mcp/tools/file-move-to-trash.js.map +1 -1
  46. package/dist/esm/mcp/tools/file-move.js.map +1 -1
  47. package/dist/esm/mcp/tools/file-upload.js.map +1 -1
  48. package/dist/esm/mcp/tools/files-search.js.map +1 -1
  49. package/dist/esm/mcp/tools/folder-contents.js.map +1 -1
  50. package/dist/esm/mcp/tools/folder-create.js.map +1 -1
  51. package/dist/esm/mcp/tools/folder-path.js.map +1 -1
  52. package/dist/esm/mcp/tools/folder-search.js.map +1 -1
  53. package/dist/esm/mcp/tools/index.js.map +1 -1
  54. package/dist/esm/schemas/drive-query-schema.js.map +1 -1
  55. package/dist/esm/schemas/drive-validation.js.map +1 -1
  56. package/dist/esm/schemas/index.js.map +1 -1
  57. package/dist/esm/setup/config.js.map +1 -1
  58. package/dist/esm/setup/http.js.map +1 -1
  59. package/dist/esm/setup/index.js.map +1 -1
  60. package/dist/esm/setup/oauth-google.js.map +1 -1
  61. package/dist/esm/setup/runtime.js.map +1 -1
  62. package/dist/esm/setup/stdio.js.map +1 -1
  63. package/dist/esm/setup/version-help.js.map +1 -1
  64. package/dist/esm/types.js.map +1 -1
  65. package/package.json +8 -9
package/bin/server.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  // Checks --version/--help/`version` via the dependency-free version-help module before ever
4
4
  // touching index.js, which statically re-exports the mcp/setup/schemas namespaces (googleapis,
5
- // @modelcontextprotocol/sdk, @mcp-z/oauth-google, @mcp-z/server et al.) -- importing index.js at
5
+ // @mcp-z/oauth-google, @mcp-z/server et al.) -- importing index.js at
6
6
  // all, even without calling anything in it, evaluates that whole graph.
7
7
  if (typeof require === 'undefined') {
8
8
  // biome-ignore lint/security/noGlobalEval: dual esm and cjs
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/constants.ts"],"sourcesContent":["/**\n * Drive MCP Server Constants\n *\n * These scopes are required for Google Drive functionality and are hardcoded\n * rather than externally configured since this server knows its own requirements.\n */\n\n// Google OAuth scopes required for Drive operations\nexport const GOOGLE_SCOPE = 'openid https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/drive';\n"],"names":["GOOGLE_SCOPE"],"mappings":"AAAA;;;;;CAKC,GAED,oDAAoD;;;;;+BACvCA;;;eAAAA;;;AAAN,IAAMA,eAAe"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-drive/src/constants.ts"],"sourcesContent":["/**\n * Drive MCP Server Constants\n *\n * These scopes are required for Google Drive functionality and are hardcoded\n * rather than externally configured since this server knows its own requirements.\n */\n\n// Google OAuth scopes required for Drive operations\nexport const GOOGLE_SCOPE = 'openid https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/drive';\n"],"names":["GOOGLE_SCOPE"],"mappings":"AAAA;;;;;CAKC,GAED,oDAAoD;;;;;+BACvCA;;;eAAAA;;;AAAN,IAAMA,eAAe"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/index.ts"],"sourcesContent":["import { handleVersionHelp } from './setup/version-help.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 // createHTTPServer/createStdioServer pull in @mcp-z/server and every mcp/tools/*.ts\n // (googleapis included); deferred so a --version/--help run never reaches them.\n const { createHTTPServer } = await import('./setup/http.ts');\n const { createStdioServer } = await import('./setup/stdio.ts');\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. config.ts's own heavy imports (@mcp-z/oauth-google,\n // @mcp-z/server) are deferred internally, so this static-looking call stays cheap until here.\n const { createConfig } = await import('./setup/config.ts');\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":["GOOGLE_SCOPE","main","mcp","schemas","setup","startServer","config","createHTTPServer","createStdioServer","logger","close","transport","type","process","on","exit","info","Promise","versionHelpResult","createConfig","handleVersionHelp","argv","handled","console","log","output","URL","pathname"],"mappings":";;;;;;;;;;;QAGSA;eAAAA,yBAAY;;QAsBrB;eAA8BC;;QArBlBC;;;QACAC;;;QACAC;;;QAGUC;eAAAA;;;6BATY;2BAGL;+DACR;gEACI;gEACF;qBACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEP,SAAeA,YAAYC,MAAoB;;YAG5CC,kBACAC,mBACkBF,MAAlBG,QAAQC;;;;oBAFa;;wBAAM;2EAAA,QAAO;;;;oBAAlCH,mBAAqB,cAArBA;oBACsB;;wBAAM;2EAAA,QAAO;;;;oBAAnCC,oBAAsB,cAAtBA;yBACkBF,CAAAA,OAAOK,SAAS,CAACC,IAAI,KAAK,OAAM,GAAhCN;;;;oBAAoC;;wBAAME,kBAAkBF;;;2BAAxB;;;;;;oBAAkC;;wBAAMC,iBAAiBD;;;2BAAvB;;;oBAAtEA,aAAlBG,SAAkBH,KAAlBG,QAAQC,QAAUJ,KAAVI;oBAEhBG,QAAQC,EAAE,CAAC,UAAU;;;;;wCACnB;;4CAAMJ;;;wCAAN;wCACAG,QAAQE,IAAI,CAAC;;;;;;wBACf;;oBAEAN,OAAOO,IAAI,CAAC,AAAC,uBAA4C,OAAtBV,OAAOK,SAAS,CAACC,IAAI,EAAC;oBACzD;;wBAAM,IAAIK,QAAQ,YAAO;;;oBAAzB;;;;;;IACF;;AAEe,SAAehB;;YAEtBiB,mBAQEC,cACFb;;;;oBAVN,4DAA4D;oBACtDY,oBAAoBE,IAAAA,gCAAiB,EAACP,QAAQQ,IAAI;oBACxD,IAAIH,kBAAkBI,OAAO,EAAE;wBAC7BC,QAAQC,GAAG,CAACN,kBAAkBO,MAAM;wBACpCZ,QAAQE,IAAI,CAAC;oBACf;oBAIyB;;wBAAM;2EAAA,QAAO;;;;oBAA9BI,eAAiB,cAAjBA;oBACFb,SAASa;oBACf;;wBAAMd,YAAYC;;;oBAAlB;;;;;;IACF;;AAEA,IAAIO,QAAQQ,IAAI,CAAC,EAAE,KAAK,IAAIK,IAAI,qDAAiBC,QAAQ,EAAE;IACzD1B;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-drive/src/index.ts"],"sourcesContent":["import { handleVersionHelp } from './setup/version-help.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 // createHTTPServer/createStdioServer pull in @mcp-z/server and every mcp/tools/*.ts\n // (googleapis included); deferred so a --version/--help run never reaches them.\n const { createHTTPServer } = await import('./setup/http.ts');\n const { createStdioServer } = await import('./setup/stdio.ts');\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. config.ts's own heavy imports (@mcp-z/oauth-google,\n // @mcp-z/server) are deferred internally, so this static-looking call stays cheap until here.\n const { createConfig } = await import('./setup/config.ts');\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":["GOOGLE_SCOPE","main","mcp","schemas","setup","startServer","config","createHTTPServer","createStdioServer","logger","close","transport","type","process","on","exit","info","Promise","versionHelpResult","createConfig","handleVersionHelp","argv","handled","console","log","output","URL","pathname"],"mappings":";;;;;;;;;;;QAGSA;eAAAA,yBAAY;;QAsBrB;eAA8BC;;QArBlBC;;;QACAC;;;QACAC;;;QAGUC;eAAAA;;;6BATY;2BAGL;+DACR;gEACI;gEACF;qBACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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-registry';\n\n// keyv-file is a direct dependency so the default file:// URIs resolve; keyv-registry\n// loads adapters with require() rather than depending on any of them itself.\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":["createStore","uri","store","keyvRegistry","Error"],"mappings":";;;;+BAGA,sFAAsF;AACtF,6EAA6E;AAE7E;;;eAA8BA;;;mEALL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKV,SAAeA,YAAeC,GAAW;;YAChDC;;;;oBAAQ;;wBAAMC,IAAAA,qBAAY,EAAIF;;;oBAA9BC,QAAQ;oBACd,IAAI,CAACA,OAAO,MAAM,IAAIE,MAAM,AAAC,mCAAsC,OAAJH;oBAC/D;;wBAAOC;;;;IACT"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-drive/src/lib/create-store.ts"],"sourcesContent":["import type Keyv from 'keyv';\nimport keyvRegistry from 'keyv-registry';\n\n// keyv-file is a direct dependency so the default file:// URIs resolve; keyv-registry\n// loads adapters with require() rather than depending on any of them itself.\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":["createStore","uri","store","keyvRegistry","Error"],"mappings":";;;;+BAGA,sFAAsF;AACtF,6EAA6E;AAE7E;;;eAA8BA;;;mEALL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKV,SAAeA,YAAeC,GAAW;;YAChDC;;;;oBAAQ;;wBAAMC,IAAAA,qBAAY,EAAIF;;;oBAA9BC,QAAQ;oBACd,IAAI,CAACA,OAAO,MAAM,IAAIE,MAAM,AAAC,mCAAsC,OAAJH;oBAC/D;;wBAAOC;;;;IACT"}
@@ -1 +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":["getFileReadStream","guessMimeType","MIME_BY_EXTENSION","fileName","extname","toLowerCase","fileUri","rawPath","filePath","fileSize","response","stream","contentType","contentLength","startsWith","slice","length","resolve","stat","size","createReadStream","basename","fetch","ok","Error","statusText","body","Readable","fromWeb","headers","get","split","trim","getRemoteFileName","Number","parseInt","contentDisposition","match","exec","fromHeader","decodeURIComponent","URL","pathname"],"mappings":"AAAA,iFAAiF;;;;;;;;;;;QA2E3DA;eAAAA;;QAvBNC;eAAAA;;;kBAlDiB;wBACZ;oBACsB;sBAClB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAezB,wEAAwE,GACxE,IAAMC,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;AAGO,SAASD,cAAcE,QAAgB;QACrCD;IAAP,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AE3C;;wBAAO;4BACLnB,QAAAA;4BACAR,UAAU8B,kBAAkBvB,SAASmB,OAAO,CAACC,GAAG,CAAC,wBAAwBxB;2BACrEM,eAAe;4BAAEA,aAAAA;wBAAY,GAC7BC,iBAAiB;4BAAEM,MAAMe,OAAOC,QAAQ,CAACtB,eAAe;wBAAI;;;oBAIpE,MAAM,IAAIW,MAAM,AAAC,qBAA4B,OAARlB,SAAQ;;;IAC/C;;AAEA,kFAAkF,GAClF,SAAS2B,kBAAkBG,kBAAiC,EAAE9B,OAAe;IAC3E,IAAI8B,oBAAoB;;QACtB,IAAMC,QAAQ,uCAAuCC,IAAI,CAACF;QAC1D,IAAMG,qBAAaF,kBAAAA,4BAAAA,KAAO,CAAC,EAAE,uCAAIA,kBAAAA,4BAAAA,KAAO,CAAC,EAAE;QAC3C,IAAIE,YAAY;YACd,OAAOA,WAAWP,IAAI;QACxB;IACF;IAEA,IAAI;QACF,OAAOQ,mBAAmBnB,IAAAA,cAAQ,EAAC,IAAIoB,IAAInC,SAASoC,QAAQ,MAAM;IACpE,EAAE,eAAM;QACN,OAAO;IACT;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/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":["getFileReadStream","guessMimeType","MIME_BY_EXTENSION","fileName","extname","toLowerCase","fileUri","rawPath","filePath","fileSize","response","stream","contentType","contentLength","startsWith","slice","length","resolve","stat","size","createReadStream","basename","fetch","ok","Error","statusText","body","Readable","fromWeb","headers","get","split","trim","getRemoteFileName","Number","parseInt","contentDisposition","match","exec","fromHeader","decodeURIComponent","URL","pathname"],"mappings":"AAAA,iFAAiF;;;;;;;;;;;QA2E3DA;eAAAA;;QAvBNC;eAAAA;;;kBAlDiB;wBACZ;oBACsB;sBAClB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/lib/google-auth.ts"],"sourcesContent":["import { auth as googleAuthPlus } from '@googleapis/drive';\nimport { attachTokenProvider, type GoogleAuthProvider } from '@mcp-z/oauth-google';\n\n/**\n * A Google API client bound to this request's token provider.\n *\n * `@mcp-z/oauth-google` mints tokens and depends on no Google SDK, so the client\n * is built here, from this package's own SDK. That keeps one copy of\n * `google-auth-library` in the tree by construction rather than by matching pins.\n */\nexport function googleAuth(auth: GoogleAuthProvider) {\n return attachTokenProvider(new googleAuthPlus.OAuth2(), auth);\n}\n"],"names":["googleAuth","auth","attachTokenProvider","googleAuthPlus","OAuth2"],"mappings":";;;;+BAUgBA;;;eAAAA;;;qBAVuB;2BACsB;AAStD,SAASA,WAAWC,IAAwB;IACjD,OAAOC,IAAAA,gCAAmB,EAAC,IAAIC,WAAc,CAACC,MAAM,IAAIH;AAC1D"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-drive/src/lib/google-auth.ts"],"sourcesContent":["import { auth as googleAuthPlus } from '@googleapis/drive';\nimport { attachTokenProvider, type GoogleAuthProvider } from '@mcp-z/oauth-google';\n\n/**\n * A Google API client bound to this request's token provider.\n *\n * `@mcp-z/oauth-google` mints tokens and depends on no Google SDK, so the client\n * is built here, from this package's own SDK. That keeps one copy of\n * `google-auth-library` in the tree by construction rather than by matching pins.\n */\nexport function googleAuth(auth: GoogleAuthProvider) {\n return attachTokenProvider(new googleAuthPlus.OAuth2(), auth);\n}\n"],"names":["googleAuth","auth","attachTokenProvider","googleAuthPlus","OAuth2"],"mappings":";;;;+BAUgBA;;;eAAAA;;;qBAVuB;2BACsB;AAStD,SAASA,WAAWC,IAAwB;IACjD,OAAOC,IAAAA,gCAAmB,EAAC,IAAIC,WAAc,CAACC,MAAM,IAAIH;AAC1D"}
@@ -1 +1 @@
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":";;;;+BA2CgBA;;;eAAAA;;;;;;;AAAT,SAASA,aAAaC,KAA0B;IAIrD,iEAAiE;IACjE,IAAI,OAAOA,UAAU,UAAU;QAC7B,OAAO;YAAEC,GAAGD;YAAOE,SAAS,CAAC;QAAE;IACjC;IACA,IAAMC,eAAyB,EAAE;IACjC,IAAMC,mBAA6B,EAAE;IACrC,IAAMC,mBAA6B,EAAE;IACrC,IAAMC,mBAA6B,EAAE;IACrC,IAAMC,gBAA0B,EAAE;IAElC,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IAEJ,SAASC,EAAEC,CAAU;QACnB,OAAO,AAAC,IAAmB,OAAhBC,OAAOD,cAAAA,eAAAA,IAAK,KAAI;IAC7B;IAEA,SAASE,MAAMF,CAAW;QACxB,IAAMG,MAAMF,OAAOD,cAAAA,eAAAA,IAAK;QACxB,8CAA8C;QAC9C,OAAO,AAAC,IAA4B,OAAzBG,IAAIC,OAAO,CAAC,MAAM,QAAO;IACtC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AAO,AAAC,OAAmB,OAAbJ,KAAKC,EAAEG,IAAI;QAErC,IAAMhB,SAASY,KAAKC;QACpB,OAAOb,OAAOT,IAAI,OAAO,KAAK,KAAKS;IACrC;IAEA,IAAMpC,IAAI8D,QAAQ/D;IAClB,IAAMgE,eAAe/D,EAAEe,OAAO,CAAC,+CAA+C,IAAIY,IAAI;IAEtF,IAAM1B,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,SAAAA;IAAQ;AAC1C"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/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":";;;;+BA2CgBA;;;eAAAA;;;;;;;AAAT,SAASA,aAAaC,KAA0B;IAIrD,iEAAiE;IACjE,IAAI,OAAOA,UAAU,UAAU;QAC7B,OAAO;YAAEC,GAAGD;YAAOE,SAAS,CAAC;QAAE;IACjC;IACA,IAAMC,eAAyB,EAAE;IACjC,IAAMC,mBAA6B,EAAE;IACrC,IAAMC,mBAA6B,EAAE;IACrC,IAAMC,mBAA6B,EAAE;IACrC,IAAMC,gBAA0B,EAAE;IAElC,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IAEJ,SAASC,EAAEC,CAAU;QACnB,OAAO,AAAC,IAAmB,OAAhBC,OAAOD,cAAAA,eAAAA,IAAK,KAAI;IAC7B;IAEA,SAASE,MAAMF,CAAW;QACxB,IAAMG,MAAMF,OAAOD,cAAAA,eAAAA,IAAK;QACxB,8CAA8C;QAC9C,OAAO,AAAC,IAA4B,OAAzBG,IAAIC,OAAO,CAAC,MAAM,QAAO;IACtC;IAEA,SAASC,GAAGC,KAAa,EAAEC,GAAa;QACtC,IAAMC,SAASP,OAAOM,gBAAAA,iBAAAA,MAAO;QAC7B,IAAME,IAAIP,MAAMM;QAEhB,IAAIF,UAAU,QAAQ;YACpBf,aAAamB,IAAI,CAACF;YAClB,OAAO,AAAC,iBAAkB,OAAFC;QAC1B;QACA,IAAIH,UAAU,YAAY;YACxBd,iBAAiBkB,IAAI,CAACF;YACtB,OAAO,AAAC,cAAe,OAAFC;QACvB;QACA,IAAIH,UAAU,YAAY;YACxBb,iBAAiBi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B,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,SAAAA;IAAQ;AAC1C"}
@@ -1 +1 @@
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":";;;;;;;;;;;QAAYA;;;QACAC;;;QACAC;;;;+DAFqB;gEACE;gEACJ"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/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":";;;;;;;;;;;QAAYA;;;QACAC;;;QACAC;;;;+DAFqB;gEACE;gEACJ"}
@@ -1 +1 @@
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":["organizeFiles","querySyntax"],"mappings":";;;;;;;;;;;QAAoBA;eAAAA,wBAAa;;QACbC;eAAAA,sBAAW;;;sEADU;oEACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/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":["organizeFiles","querySyntax"],"mappings":";;;;;;;;;;;QAAoBA;eAAAA,wBAAa;;QACbC;eAAAA,sBAAW;;;sEADU;oEACF"}
@@ -1 +1 @@
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":";;;;+BAEA;;;eAAwBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAT,SAASA;IACtB,IAAMC,SAAS;QACbC,aAAa;QACbC,YAAY,CAAC;IACf;IAEA,OAAO;QACLC,MAAM;QACNH,QAAAA;QACAI,SAAS,SAATA;;;;;wBAAsB;4BACpBC,QAAQ;gCACN;oCACEC,MAAM;oCACNC,SAAS;wCACPC,MAAM;wCACNC,MAAM;oCACR;gCACF;;wBAEJ;;;;;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/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":";;;;+BAEA;;;eAAwBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAT,SAASA;IACtB,IAAMC,SAAS;QACbC,aAAa;QACbC,YAAY,CAAC;IACf;IAEA,OAAO;QACLC,MAAM;QACNH,QAAAA;QACAI,SAAS,SAATA;;;;;wBAAsB;4BACpBC,QAAQ;gCACN;oCACEC,MAAM;oCACNC,SAAS;wCACPC,MAAM;wCACNC,MAAM;oCACR;gCACF;;wBAEJ;;;;;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/prompts/query-syntax.ts"],"sourcesContent":["import type { PromptModule, ServerContext } from '@mcp-z/server';\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: ServerContext) => {\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":";;;;+BAEA;;;eAAwBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAT,SAASA;IACtB,IAAMC,SAAS;QACbC,aAAa;IACf;IAEA,IAAMC,UAAU,iBAAOC,OAAiCC;;;gBACtD;;oBAAO;wBACLC,QAAQ;4BACN;gCACEC,MAAM;gCACNC,SAAS;oCACPC,MAAM;oCACNC,MAAM;gCA4DR;4BACF;;oBAEJ;;;QACF;;IAEA,OAAO;QACLC,MAAM;QACNV,QAAAA;QACAE,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-drive/src/mcp/prompts/query-syntax.ts"],"sourcesContent":["import type { PromptModule, ServerContext } from '@mcp-z/server';\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: ServerContext) => {\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":";;;;+BAEA;;;eAAwBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAT,SAASA;IACtB,IAAMC,SAAS;QACbC,aAAa;IACf;IAEA,IAAMC,UAAU,iBAAOC,OAAiCC;;;gBACtD;;oBAAO;wBACLC,QAAQ;4BACN;gCACEC,MAAM;gCACNC,SAAS;oCACPC,MAAM;oCACNC,MAAM;gCA4DR;4BACF;;oBAEJ;;;QACF;;IAEA,OAAO;QACLC,MAAM;QACNV,QAAAA;QACAE,SAAAA;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/resources/file.ts"],"sourcesContent":["import { drive as driveApi } from '@googleapis/drive';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport type { ReadResourceResult, ResourceConfig, ResourceModule, ServerContext } from '@mcp-z/server';\nimport { ResourceTemplate } from '@mcp-z/server';\nimport { googleAuth } from '../../lib/google-auth.ts';\n\nexport default function createResource(): ResourceModule {\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: ServerContext): 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 = driveApi({ version: 'v3', auth: googleAuth(authContext.auth) });\n const resp = await drive.files.get({\n fileId,\n fields: 'id,name,mimeType,size,modifiedTime,owners,webViewLink',\n supportsAllDrives: true,\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":["createResource","template","ResourceTemplate","list","undefined","config","description","mimeType","handler","uri","variables","extra","fileId","logger","authContext","drive","resp","data","error","Array","isArray","contents","href","text","JSON","stringify","driveApi","version","auth","googleAuth","files","get","fields","supportsAllDrives","debug","fileName","name","message"],"mappings":";;;;+BAMA;;;eAAwBA;;;qBANU;sBAGD;4BACN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEZ,SAASA;IACtB,IAAMC,WAAW,IAAIC,wBAAgB,CAAC,0BAA0B;QAC9DC,MAAMC;IACR;IACA,IAAMC,SAAyB;QAC7BC,aAAa;QACbC,UAAU;IACZ;IAEA,IAAMC,UAAU,iBAAOC,KAAUC,WAA8CC;;gBAEvEC,QA2BJC,eARQA,QAAQC,aACVC,OACAC,MAKAC,MAWCC,OAEPL,gBADQA;;;;wBAvCV,2DAA2D;wBACrDD,SAASO,MAAMC,OAAO,CAACV,UAAUE,MAAM,IAAIF,UAAUE,MAAM,CAAC,EAAE,GAAGF,UAAUE,MAAM;;;;;;;;;wBAGrF,yCAAyC;wBACzC,IAAI,CAACA,UAAU,OAAOA,WAAW,UAAU;4BACzC;;gCAAO;oCACLS,QAAQ;wCACN;4CACEZ,KAAKA,IAAIa,IAAI;4CACbf,UAAU;4CACVgB,MAAMC,KAAKC,SAAS,CAAC;gDACnBP,OAAO;4CACT;wCACF;;gCAEJ;;wBACF;wBAEA,sDAAsD;wBAC9CL,SAAwBF,MAAxBE,QAAQC,cAAgBH,MAAhBG;wBACVC,QAAQW,IAAAA,YAAQ,EAAC;4BAAEC,SAAS;4BAAMC,MAAMC,IAAAA,wBAAU,EAACf,YAAYc,IAAI;wBAAE;wBAC9D;;4BAAMb,MAAMe,KAAK,CAACC,GAAG,CAAC;gCACjCnB,QAAAA;gCACAoB,QAAQ;gCACRC,mBAAmB;4BACrB;;;wBAJMjB,OAAO;wBAKPC,OAAOD,KAAKC,IAAI;yBACtBJ,gBAAAA,OAAOqB,KAAK,cAAZrB,oCAAAA,mBAAAA,QAAe;4BAAED,QAAAA;4BAAQuB,QAAQ,EAAElB,iBAAAA,2BAAAA,KAAMmB,IAAI;wBAAC,GAAG;wBACjD;;4BAAO;gCACLf,QAAQ;oCACN;wCACEZ,KAAKA,IAAIa,IAAI;wCACbf,UAAU;wCACVgB,MAAMC,KAAKC,SAAS,CAACR,QAAQ,CAAC;oCAChC;;4BAEJ;;;wBACOC;wBACCL,UAAWF,MAAXE;yBACRA,iBAAAA,QAAOqB,KAAK,cAAZrB,qCAAAA,oBAAAA,SAAeK,OAAkC;wBACjD;;4BAAO;gCACLG,QAAQ;oCACN;wCACEZ,KAAKA,IAAIa,IAAI;wCACbf,UAAU;wCACVgB,MAAMC,KAAKC,SAAS,CAAC;4CAAEP,OAAO,AAACA,MAAgBmB,OAAO;wCAAC;oCACzD;;4BAEJ;;;;;;;;QAEJ;;IAEA,OAAO;QACLD,MAAM;QACNnC,UAAAA;QACAI,QAAAA;QACAG,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-drive/src/mcp/resources/file.ts"],"sourcesContent":["import { drive as driveApi } from '@googleapis/drive';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport type { ReadResourceResult, ResourceConfig, ResourceModule, ServerContext } from '@mcp-z/server';\nimport { ResourceTemplate } from '@mcp-z/server';\nimport { googleAuth } from '../../lib/google-auth.ts';\n\nexport default function createResource(): ResourceModule {\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: ServerContext): 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 = driveApi({ version: 'v3', auth: googleAuth(authContext.auth) });\n const resp = await drive.files.get({\n fileId,\n fields: 'id,name,mimeType,size,modifiedTime,owners,webViewLink',\n supportsAllDrives: true,\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":["createResource","template","ResourceTemplate","list","undefined","config","description","mimeType","handler","uri","variables","extra","fileId","logger","authContext","drive","resp","data","error","Array","isArray","contents","href","text","JSON","stringify","driveApi","version","auth","googleAuth","files","get","fields","supportsAllDrives","debug","fileName","name","message"],"mappings":";;;;+BAMA;;;eAAwBA;;;qBANU;sBAGD;4BACN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEZ,SAASA;IACtB,IAAMC,WAAW,IAAIC,wBAAgB,CAAC,0BAA0B;QAC9DC,MAAMC;IACR;IACA,IAAMC,SAAyB;QAC7BC,aAAa;QACbC,UAAU;IACZ;IAEA,IAAMC,UAAU,iBAAOC,KAAUC,WAA8CC;;gBAEvEC,QA2BJC,eARQA,QAAQC,aACVC,OACAC,MAKAC,MAWCC,OAEPL,gBADQA;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J;;;;;;;;QAEJ;;IAEA,OAAO;QACLD,MAAM;QACNnC,UAAAA;QACAI,QAAAA;QACAG,SAAAA;IACF;AACF"}
@@ -1 +1 @@
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":["file"],"mappings":";;;;+BAAoBA;;;eAAAA,eAAI;;;6DAAQ"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-drive/src/mcp/resources/index.ts"],"sourcesContent":["export { default as file } from './file.ts';\n"],"names":["file"],"mappings":";;;;+BAAoBA;;;eAAAA,eAAI;;;6DAAQ"}
@@ -1 +1 @@
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 { drive as driveApi } from '@googleapis/drive';\nimport { type CallToolResult, ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\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 = driveApi({ version: 'v3', auth: googleAuth(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 supportsAllDrives: 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 ProtocolError\n throw new ProtocolError(ProtocolErrorCode.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":["createTool","AuthRequiredBranchSchema","schemas","MAX_BATCH_SIZE","inputSchema","z","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","drive","results","message","info","count","length","driveApi","version","auth","googleAuth","authContext","Promise","allSettled","map","files","update","fileId","requestBody","trashed","supportsAllDrives","forEach","index","status","errorMessage","reason","Error","String","push","content","text","JSON","stringify","structuredContent","ProtocolError","ProtocolErrorCode","InternalError","stack","undefined","name"],"mappings":";;;;+BA6HA;;;eAAwBA;;;2BA5HA;qBAIU;sBACoC;mBACpD;4BACS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAL3B,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAOR,IAAME,iBAAiB;AAEvB,IAAMC,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,KAAKF,MAAC,CAACG,KAAK,CAACH,MAAC,CAACI,MAAM,GAAGC,GAAG,CAAC,IAAIA,GAAG,CAAC,GAAGC,GAAG,CAACR,gBAAgBS,QAAQ,CAAC;AACtE;AAEA,wBAAwB;AACxB,IAAMC,sBAAsBR,MAAC,CAACC,MAAM,CAAC;IACnCQ,MAAMT,MAAC,CAACU,OAAO,CAAC;IAChBC,kBAAkBX,MAAC,CAACI,MAAM,GAAGG,QAAQ,CAAC;IACtCK,YAAYZ,MAAC,CAACa,MAAM,GAAGN,QAA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ACOP;oBACDa,UAAUb,AAAK,YAALA,OAAiBoC,SAAQpC,MAAMa,OAAO,GAAGwB,OAAOrC;oBAChEU,OAAOV,KAAK,CAAC,gCAAgC;wBAAEA,OAAOa;oBAAQ;oBAE9D,sBAAsB;oBACtB,MAAM,IAAI+B,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,gCAAuC,OAARjC,UAAW;wBAClGkC,OAAO/C,AAAK,YAALA,OAAiBoC,SAAQpC,MAAM+C,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAAS1E;IACtB,OAAO;QACL2E,MAAM;QACN7C,QAAAA;QACAI,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/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 { drive as driveApi } from '@googleapis/drive';\nimport { type CallToolResult, ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\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 = driveApi({ version: 'v3', auth: googleAuth(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 supportsAllDrives: 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 ProtocolError\n throw new ProtocolError(ProtocolErrorCode.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":["createTool","AuthRequiredBranchSchema","schemas","MAX_BATCH_SIZE","inputSchema","z","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","drive","results","message","info","count","length","driveApi","version","auth","googleAuth","authContext","Promise","allSettled","map","files","update","fileId","requestBody","trashed","supportsAllDrives","forEach","index","status","errorMessage","reason","Error","String","push","content","text","JSON","stringify","structuredContent","ProtocolError","ProtocolErrorCode","InternalError","stack","undefined","name"],"mappings":";;;;+BA6HA;;;eAAwBA;;;2BA5HA;qBAIU;sBACoC;mBACpD;4BACS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAL3B,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAOR,IAAME,iBAAiB;AAEvB,IAAMC,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,KAAKF,MAAC,CAACG,KAAK,CAACH,MAAC,CAACI,MAAM,GAAGC,GAAG,CAAC,IAAIA,GAAG,CAAC,GAAGC,GAAG,CAACR,gBAAgBS,QAAQ,CAAC;AACtE;AAEA,wBAAwB;AACxB,IAAMC,sBAAsBR,MAAC,CAACC,MAAM,CAAC;IACnCQ,MAAMT,MAAC,CAACU,OAAO,CAAC;IAChBC,kBAAkBX,MAAC,CAACI,MAAM,GAAGG,QAAQ,CAAC;IACtCK,YAAYZ,MAAC,CAACa,MAAM,GAAGN,QAAQ,CAAC;IAChCO,cAAcd,MAAC,CAACa,MA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C,SAAQpC,MAAMa,OAAO,GAAGwB,OAAOrC;oBAChEU,OAAOV,KAAK,CAAC,gCAAgC;wBAAEA,OAAOa;oBAAQ;oBAE9D,sBAAsB;oBACtB,MAAM,IAAI+B,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,gCAAuC,OAARjC,UAAW;wBAClGkC,OAAO/C,AAAK,YAALA,OAAiBoC,SAAQpC,MAAM+C,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAAS1E;IACtB,OAAO;QACL2E,MAAM;QACN7C,QAAAA;QACAI,SAAAA;IACF;AACF"}
@@ -1 +1 @@
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 { drive_v3 } from '@googleapis/drive';\nimport { drive as driveApi } from '@googleapis/drive';\nimport { type CallToolResult, ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\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 supportsAllDrives: true,\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 supportsAllDrives: true,\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 supportsAllDrives: true,\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 supportsAllDrives: true,\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 = driveApi({ version: 'v3', auth: googleAuth(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 ProtocolError\n throw new ProtocolError(ProtocolErrorCode.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":["createTool","AuthRequiredBranchSchema","schemas","isDriveApiError","error","inputSchema","z","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","e","errorMessage","errorCode","files","get","fields","supportsAllDrives","data","parents","name","update","addParents","removeParents","join","success","message","String","undefined","info","moveBatchFiles","_logger","metadataResults","filesToMove","i","moveResults","file","Promise","allSettled","map","response","Error","length","status","push","value","reason","handler","extra","isBatch","fileIdArray","batchResult","singleResult","Array","isArray","fileCount","driveApi","version","auth","googleAuth","authContext","content","text","JSON","stringify","structuredContent","ProtocolError","ProtocolErrorCode","InternalError","stack"],"mappings":";;;;+BAsUA;;;eAAwBA;;;2BArUA;qBAKU;sBACoC;mBACpD;4BACS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AO+C,MAAM;oBAC5B;oBAEMpC,SAAiB;wBACrBnB,MAAM;wBACNE,OAAAA;uBACIM,OAAO+C,MAAM,GAAG,KAAK;wBAAE/C,QAAAA;oBAAO;wBAClCE,gBAAgBqD,YAAYR,MAAM;wBAClC3C,YAAYV,MAAMqD,MAAM;wBACxB1C,aAAaL,OAAO+C,MAAM;;oBAG5B;;wBAAO;4BACLmB,OAAO;gCACL;oCACE1E,MAAM;oCACN2E,MAAMC,KAAKC,SAAS,CAAC1D;gCACvB;;4BAEF2D,mBAAmB;gCAAE3D,QAAAA;4BAAO;wBAC9B;;;oBACOnC;oBACDuD,UAAUvD,AAAK,YAALA,OAAiBsE,SAAQtE,MAAMuD,OAAO,GAAGC,OAAOxD;oBAChEsC,OAAOtC,KAAK,CAAC,yBAAyB;wBAAEA,OAAOuD;oBAAQ;oBAEvD,sBAAsB;oBACtB,MAAM,IAAIwC,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,uBAA8B,OAAR1C,UAAW;wBACzF2C,OAAOlG,AAAK,YAALA,OAAiBsE,SAAQtE,MAAMkG,KAAK,GAAGzC;oBAChD;;;;;;;IAEJ;;AAEe,SAAS7D;IACtB,OAAO;QACLqD,MAAM;QACNjB,QAAAA;QACA4C,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/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 { drive_v3 } from '@googleapis/drive';\nimport { drive as driveApi } from '@googleapis/drive';\nimport { type CallToolResult, ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\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 supportsAllDrives: true,\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 supportsAllDrives: true,\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 supportsAllDrives: true,\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 supportsAllDrives: true,\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 = driveApi({ version: 'v3', auth: googleAuth(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 ProtocolError\n throw new ProtocolError(ProtocolErrorCode.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":["createTool","AuthRequiredBranchSchema","schemas","isDriveApiError","error","inputSchema","z","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","e","errorMessage","errorCode","files","get","fields","supportsAllDrives","data","parents","name","update","addParents","removeParents","join","success","message","String","undefined","info","moveBatchFiles","_logger","metadataResults","filesToMove","i","moveResults","file","Promise","allSettled","map","response","Error","length","status","push","value","reason","handler","extra","isBatch","fileIdArray","batchResult","singleResult","Array","isArray","fileCount","driveApi","version","auth","googleAuth","authContext","content","text","JSON","stringify","structuredContent","ProtocolError","ProtocolErrorCode","InternalError","stack"],"mappings":";;;;+BAsUA;;;eAAwBA;;;2BArUA;qBAKU;sBACoC;mBACpD;4BACS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAN3B,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAeR,SAASE,gBAAgBC,KAAc;IACrC,OAAO,CAAA,OAAOA,sCAAP,SAAOA,MAAI,MAAM,YAAYA,UAAU,QAAS,CAAA,aAAaA,SAAS,UAAUA,KAAI;AAC7F;AAiBA,IAAMC,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,SAASF,MAAC,CAACG,KAAK,CAAC;QAACH,MAAC,CAACI,MAAM,GAAGC,GAAG,CAAC;QAAIL,MAAC,CAACM,KAAK,CAACN,MAAC,CAACI,MAAM,GAAGC,GAAG,CAAC,IAAIA,GAAG,CAAC,GAAGE,GAAG,CAAC;KAAK,EAAEC,QAAQ,CAAC;IAC3FC,qBAAqBT,MAAC,CAACI,MAAM,GAAGC,GAAG,CAAC,GAAGG,QAAQ,CAAC;IAChDE,kBAAkBV,MAAC,CAACW,OAAO,GAAGC,QAAQ,GAAGJ,QAAQ,CAAC;AACpD;AAEA,wBAAwB;AACxB,IAAMK,sBAAsBb,MAAC,CAACC,MAAM,CAAC;IACnCa,MAAMd,MAAC,CAACe,OAAO,CAAC;IAChBC,OAAOhB,MA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":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/tools/file-upload.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { drive as driveApi } from '@googleapis/drive';\nimport type { CallToolResult } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { getFileReadStream, guessMimeType } from '../../lib/file-streaming.ts';\nimport { googleAuth } from '../../lib/google-auth.ts';\n\nconst inputSchema = z.object({\n sourceUri: z.string().trim().min(1).describe('File URI to upload (file://, http://, https://)'),\n name: z.string().trim().min(1).optional().describe('File name in Drive, including extension (defaults to the source file name)'),\n mimeType: z.string().trim().min(1).optional().describe('MIME type, e.g. application/pdf (defaults to the Content-Type header or detection from the file extension)'),\n parentId: z.string().optional().describe('Parent folder ID (omit to upload to My Drive root)'),\n description: z.string().optional().describe('Description to store in the file metadata'),\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n operationSummary: z.string().describe('Summary of the file upload operation'),\n itemsProcessed: z.number().describe('Total items attempted (always 1 for single file)'),\n itemsChanged: z.number().describe('Successfully uploaded files (always 1 on success)'),\n completedAt: z.string().describe('ISO datetime when operation completed'),\n id: z.string().describe('ID of the uploaded file'),\n name: z.string().describe('Name of the uploaded file'),\n mimeType: z.string().describe('MIME type of the uploaded file'),\n size: z.string().describe('Size of the uploaded file in bytes'),\n webViewLink: z.string().describe('URL to view the file in Drive'),\n parentId: z.string().optional().describe('ID of the parent folder'),\n parentName: z.string().optional().describe('Name of the parent folder'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n title: 'Upload File',\n 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.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\n// Export types for strong typing in tests\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ sourceUri, name, mimeType, parentId, description }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('drive.file.upload called', {\n sourceUri,\n name: name || 'auto',\n parentId: parentId || 'root',\n });\n\n try {\n const drive = driveApi({ version: 'v3', auth: googleAuth(extra.authContext.auth) });\n\n // Stream source content directly from URI (no temp files)\n const source = await getFileReadStream(sourceUri);\n const finalName = name || source.fileName;\n const finalMimeType = mimeType || source.contentType || guessMimeType(finalName);\n\n // Create the file with streamed content (multipart upload; the client pipes the\n // stream body through without buffering it into memory)\n const response = await drive.files.create({\n requestBody: {\n name: finalName,\n mimeType: finalMimeType,\n parents: parentId ? [parentId] : null,\n ...(description && { description }),\n },\n media: { mimeType: finalMimeType, body: source.stream },\n supportsAllDrives: true,\n fields: 'id,name,mimeType,size,webViewLink,parents',\n });\n\n const res = response.data;\n const id = res.id ?? '';\n const resultName = res.name ?? finalName;\n const resultMimeType = res.mimeType ?? finalMimeType;\n const size = res.size ?? String(source.size ?? 0);\n const webViewLink = res.webViewLink ?? '';\n const parents = (res.parents as string[] | undefined) || [];\n\n // Fetch parent name if parentId was provided\n let parentName: string | undefined;\n let actualParentId: string | undefined;\n\n if (parents.length > 0) {\n actualParentId = parents[0];\n\n if (actualParentId === 'root') {\n parentName = 'My Drive';\n } else if (actualParentId) {\n try {\n const parentResponse = await drive.files.get({\n fileId: actualParentId,\n fields: 'name',\n supportsAllDrives: true,\n });\n parentName = (parentResponse.data.name as string | undefined) || actualParentId;\n } catch (e) {\n logger.info('Failed to fetch parent name', {\n parentId: actualParentId,\n error: e,\n });\n parentName = actualParentId; // Fallback to ID\n }\n }\n }\n\n const locationSummary = parentName ? ` in \"${parentName}\"` : ' in My Drive';\n\n logger.info('drive.file.upload success', {\n id,\n name: resultName,\n size,\n parentId: actualParentId,\n });\n\n // Build result object with operation metadata\n const result: Output = {\n type: 'success' as const,\n operationSummary: `Uploaded \"${resultName}\"${locationSummary}`,\n itemsProcessed: 1,\n itemsChanged: 1,\n completedAt: new Date().toISOString(),\n id,\n name: resultName,\n mimeType: resultMimeType,\n size,\n webViewLink,\n ...(actualParentId && { parentId: actualParentId }),\n ...(parentName && { parentName }),\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.upload error', { error: message });\n\n // Throw ProtocolError for proper MCP error handling\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error uploading file: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'file-upload' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","sourceUri","string","trim","min","describe","name","optional","mimeType","parentId","description","successBranchSchema","type","literal","operationSummary","itemsProcessed","number","itemsChanged","completedAt","id","size","webViewLink","parentName","outputSchema","discriminatedUnion","config","title","result","handler","extra","logger","res","source","drive","finalName","finalMimeType","response","resultName","resultMimeType","parents","actualParentId","parentResponse","e","locationSummary","error","message","info","driveApi","version","auth","googleAuth","authContext","getFileReadStream","fileName","contentType","guessMimeType","files","create","requestBody","media","body","stream","supportsAllDrives","fields","data","String","length","get","fileId","Date","toISOString","content","text","JSON","stringify","structuredContent","Error","ProtocolError","ProtocolErrorCode","InternalError","stack","undefined"],"mappings":";;;;+BAkKA;;;eAAwBA;;;2BAjKA;qBAIU;sBAEe;mBAC/B;+BAC+B;4BACtB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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+B;wBACNjB,MAAAA;wBACAX,UAAU+B;oBACZ;oBAEA,8CAA8C;oBACxCb,SAAiB;wBACrBf,MAAM;wBACNE,kBAAkB,AAAC,aAA0B6B,OAAdN,YAAW,KAAmB,OAAhBM;wBAC7C5B,gBAAgB;wBAChBE,cAAc;wBACdC,aAAa,IAAImD,OAAOC,WAAW;wBACnCnD,IAAAA;wBACAb,MAAM+B;wBACN7B,UAAU8B;wBACVlB,MAAAA;wBACAC,aAAAA;uBACImB,kBAAkB;wBAAE/B,UAAU+B;oBAAe,GAC7ClB,cAAc;wBAAEA,YAAAA;oBAAW;oBAGjC;;wBAAO;4BACLiD,OAAO;gCACL;oCACE3D,MAAM;oCACN4D,MAAMC,KAAKC,SAAS,CAAC/C;gCACvB;;4BAEFgD,mBAAmB;gCAAEhD,QAAAA;4BAAO;wBAC9B;;;oBACOiB;oBACDC,UAAUD,AAAK,YAALA,OAAiBgC,SAAQhC,MAAMC,OAAO,GAAGoB,OAAOrB;oBAChEd,OAAOc,KAAK,CAAC,2BAA2B;wBAAEA,OAAOC;oBAAQ;oBAEzD,oDAAoD;oBACpD,MAAM,IAAIgC,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,yBAAgC,OAARlC,UAAW;wBAC3FmC,OAAOpC,AAAK,YAALA,OAAiBgC,SAAQhC,MAAMoC,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAAStF;IACtB,OAAO;QACLW,MAAM;QACNmB,QAAAA;QACAG,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-drive/src/mcp/tools/file-upload.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { drive as driveApi } from '@googleapis/drive';\nimport type { CallToolResult } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { getFileReadStream, guessMimeType } from '../../lib/file-streaming.ts';\nimport { googleAuth } from '../../lib/google-auth.ts';\n\nconst inputSchema = z.object({\n sourceUri: z.string().trim().min(1).describe('File URI to upload (file://, http://, https://)'),\n name: z.string().trim().min(1).optional().describe('File name in Drive, including extension (defaults to the source file name)'),\n mimeType: z.string().trim().min(1).optional().describe('MIME type, e.g. application/pdf (defaults to the Content-Type header or detection from the file extension)'),\n parentId: z.string().optional().describe('Parent folder ID (omit to upload to My Drive root)'),\n description: z.string().optional().describe('Description to store in the file metadata'),\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n operationSummary: z.string().describe('Summary of the file upload operation'),\n itemsProcessed: z.number().describe('Total items attempted (always 1 for single file)'),\n itemsChanged: z.number().describe('Successfully uploaded files (always 1 on success)'),\n completedAt: z.string().describe('ISO datetime when operation completed'),\n id: z.string().describe('ID of the uploaded file'),\n name: z.string().describe('Name of the uploaded file'),\n mimeType: z.string().describe('MIME type of the uploaded file'),\n size: z.string().describe('Size of the uploaded file in bytes'),\n webViewLink: z.string().describe('URL to view the file in Drive'),\n parentId: z.string().optional().describe('ID of the parent folder'),\n parentName: z.string().optional().describe('Name of the parent folder'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n title: 'Upload File',\n 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.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\n// Export types for strong typing in tests\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ sourceUri, name, mimeType, parentId, description }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('drive.file.upload called', {\n sourceUri,\n name: name || 'auto',\n parentId: parentId || 'root',\n });\n\n try {\n const drive = driveApi({ version: 'v3', auth: googleAuth(extra.authContext.auth) });\n\n // Stream source content directly from URI (no temp files)\n const source = await getFileReadStream(sourceUri);\n const finalName = name || source.fileName;\n const finalMimeType = mimeType || source.contentType || guessMimeType(finalName);\n\n // Create the file with streamed content (multipart upload; the client pipes the\n // stream body through without buffering it into memory)\n const response = await drive.files.create({\n requestBody: {\n name: finalName,\n mimeType: finalMimeType,\n parents: parentId ? [parentId] : null,\n ...(description && { description }),\n },\n media: { mimeType: finalMimeType, body: source.stream },\n supportsAllDrives: true,\n fields: 'id,name,mimeType,size,webViewLink,parents',\n });\n\n const res = response.data;\n const id = res.id ?? '';\n const resultName = res.name ?? finalName;\n const resultMimeType = res.mimeType ?? finalMimeType;\n const size = res.size ?? String(source.size ?? 0);\n const webViewLink = res.webViewLink ?? '';\n const parents = (res.parents as string[] | undefined) || [];\n\n // Fetch parent name if parentId was provided\n let parentName: string | undefined;\n let actualParentId: string | undefined;\n\n if (parents.length > 0) {\n actualParentId = parents[0];\n\n if (actualParentId === 'root') {\n parentName = 'My Drive';\n } else if (actualParentId) {\n try {\n const parentResponse = await drive.files.get({\n fileId: actualParentId,\n fields: 'name',\n supportsAllDrives: true,\n });\n parentName = (parentResponse.data.name as string | undefined) || actualParentId;\n } catch (e) {\n logger.info('Failed to fetch parent name', {\n parentId: actualParentId,\n error: e,\n });\n parentName = actualParentId; // Fallback to ID\n }\n }\n }\n\n const locationSummary = parentName ? ` in \"${parentName}\"` : ' in My Drive';\n\n logger.info('drive.file.upload success', {\n id,\n name: resultName,\n size,\n parentId: actualParentId,\n });\n\n // Build result object with operation metadata\n const result: Output = {\n type: 'success' as const,\n operationSummary: `Uploaded \"${resultName}\"${locationSummary}`,\n itemsProcessed: 1,\n itemsChanged: 1,\n completedAt: new Date().toISOString(),\n id,\n name: resultName,\n mimeType: resultMimeType,\n size,\n webViewLink,\n ...(actualParentId && { parentId: actualParentId }),\n ...(parentName && { parentName }),\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.upload error', { error: message });\n\n // Throw ProtocolError for proper MCP error handling\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error uploading file: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'file-upload' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","sourceUri","string","trim","min","describe","name","optional","mimeType","parentId","description","successBranchSchema","type","literal","operationSummary","itemsProcessed","number","itemsChanged","completedAt","id","size","webViewLink","parentName","outputSchema","discriminatedUnion","config","title","result","handler","extra","logger","res","source","drive","finalName","finalMimeType","response","resultName","resultMimeType","parents","actualParentId","parentResponse","e","locationSummary","error","message","info","driveApi","version","auth","googleAuth","authContext","getFileReadStream","fileName","contentType","guessMimeType","files","create","requestBody","media","body","stream","supportsAllDrives","fields","data","String","length","get","fileId","Date","toISOString","content","text","JSON","stringify","structuredContent","Error","ProtocolError","ProtocolErrorCode","InternalError","stack","undefined"],"mappings":";;;;+BAkKA;;;eAAwBA;;;2BAjKA;qBAIU;sBAEe;mBAC/B;+BAC+B;4BACtB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAP3B,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AASR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,WAAWF,MAAC,CAACG,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IAC7CC,MAAMP,MAAC,CAACG,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGG,QAA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BACAC,aAAAA;uBACImB,kBAAkB;wBAAE/B,UAAU+B;oBAAe,GAC7ClB,cAAc;wBAAEA,YAAAA;oBAAW;oBAGjC;;wBAAO;4BACLiD,OAAO;gCACL;oCACE3D,MAAM;oCACN4D,MAAMC,KAAKC,SAAS,CAAC/C;gCACvB;;4BAEFgD,mBAAmB;gCAAEhD,QAAAA;4BAAO;wBAC9B;;;oBACOiB;oBACDC,UAAUD,AAAK,YAALA,OAAiBgC,SAAQhC,MAAMC,OAAO,GAAGoB,OAAOrB;oBAChEd,OAAOc,KAAK,CAAC,2BAA2B;wBAAEA,OAAOC;oBAAQ;oBAEzD,oDAAoD;oBACpD,MAAM,IAAIgC,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,yBAAgC,OAARlC,UAAW;wBAC3FmC,OAAOpC,AAAK,YAALA,OAAiBgC,SAAQhC,MAAMoC,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAAStF;IACtB,OAAO;QACLW,MAAM;QACNmB,QAAAA;QACAG,SAAAA;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/tools/files-search.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { type drive_v3, drive as driveApi } from '@googleapis/drive';\nimport { type CallToolResult, createFieldsSchema, createPaginationSchema, createShapeSchema, filterFields, ProtocolError, ProtocolErrorCode, parseFields, toColumnarFormat } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { toDriveQuery } from '../../lib/query-builder.ts';\nimport { DRIVE_FILE_COMMON_PATTERNS, DRIVE_FILE_FIELD_DESCRIPTIONS, DRIVE_FILE_FIELDS, type DriveFile, DriveFileSchema, DriveQueryParameterSchema, parseDriveQueryParameter } from '../../schemas/index.ts';\n\nconst inputSchema = z.object({\n query: DriveQueryParameterSchema.describe('Structured Drive query object or JSON string. Use rawDriveQuery for raw Drive syntax.'),\n fields: createFieldsSchema({\n availableFields: DRIVE_FILE_FIELDS,\n fieldDescriptions: DRIVE_FILE_FIELD_DESCRIPTIONS,\n commonPatterns: DRIVE_FILE_COMMON_PATTERNS,\n resourceName: 'Drive file',\n }),\n ...createPaginationSchema({\n defaultPageSize: 50,\n maxPageSize: 1000,\n provider: 'drive',\n }).shape,\n shape: createShapeSchema(),\n});\n\n// Success branch schemas for different shapes\nconst successObjectsBranchSchema = z.object({\n type: z.literal('success'),\n shape: z.literal('objects'),\n items: z.array(DriveFileSchema).describe('Matching Drive files'),\n count: z.number().describe('Number of files in this page'),\n nextPageToken: z.string().optional().describe('Token for fetching next page of results'),\n});\n\nconst successArraysBranchSchema = z.object({\n type: z.literal('success'),\n shape: z.literal('arrays'),\n columns: z.array(z.string()).describe('Column names in canonical order'),\n rows: z.array(z.array(z.unknown())).describe('Row data matching column order'),\n count: z.number().describe('Number of files in this page'),\n nextPageToken: z.string().optional().describe('Token for fetching next page of results'),\n});\n\n// Output schema with auth_required support\n// Using z.union instead of discriminatedUnion since we have two success branches with different shapes\nconst outputSchema = z.union([successObjectsBranchSchema, successArraysBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n title: 'Search Drive Files',\n description: 'Search Google Drive files with flexible field selection for optimal performance.',\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// Type for the raw Google Drive API response\ntype driveFile = drive_v3.Schema$File;\n\ntype driveResponse = drive_v3.Schema$FileList;\n\nasync function handler({ query, pageSize = 50, pageToken, fields, shape = 'arrays' }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n\n try {\n const parsedQuery = parseDriveQueryParameter(query);\n const requestedFields = parseFields(fields, DRIVE_FILE_FIELDS);\n\n // Validate and clamp pageSize to Google Drive API limits (1-1000)\n const validPageSize = Math.max(1, Math.min(1000, Math.floor(pageSize || 50)));\n\n logger.info('drive.files-search called', {\n query: parsedQuery,\n pageSize: validPageSize,\n pageToken: pageToken ? '[provided]' : undefined,\n fields: fields || 'all',\n });\n\n const drive = driveApi({ version: 'v3', auth: googleAuth(extra.authContext.auth) });\n\n // Handle query parameter\n let qStr: string;\n if (parsedQuery && 'rawDriveQuery' in parsedQuery && parsedQuery.rawDriveQuery) {\n // Object with rawDriveQuery field - use it directly\n qStr = parsedQuery.rawDriveQuery;\n } else if (parsedQuery) {\n // Structured query object - convert to Drive query string\n const { q } = toDriveQuery(parsedQuery);\n qStr = q || '';\n } else {\n qStr = '';\n }\n\n const listOptions: {\n q?: string;\n pageSize: number;\n fields: string;\n orderBy: string;\n pageToken?: string;\n corpora: string;\n supportsAllDrives: boolean;\n includeItemsFromAllDrives: boolean;\n } = {\n pageSize: validPageSize,\n fields: 'files(id,name,mimeType,webViewLink,modifiedTime,parents,shared,starred,owners),nextPageToken',\n orderBy: 'modifiedTime desc',\n // All three are load-bearing for shared drives: the default `user` corpus omits\n // them, and Drive rejects an `allDrives` corpus unless both flags are set too.\n corpora: 'allDrives',\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n };\n if (qStr.trim().length > 0) {\n listOptions.q = qStr;\n }\n if (pageToken && pageToken.trim().length > 0) {\n listOptions.pageToken = pageToken;\n }\n\n const response = await drive.files.list(listOptions);\n const res = response.data as driveResponse;\n const files = Array.isArray(res?.files) ? res.files : [];\n\n const parentIds = new Set<string>();\n for (const f of files) {\n if (f?.parents && f.parents.length > 0) {\n for (const parentId of f.parents) {\n if (parentId && parentId !== 'root') {\n parentIds.add(parentId);\n }\n }\n }\n }\n\n const parentNameMap = new Map<string, string>();\n if (parentIds.size > 0) {\n logger.info('Fetching parent names', { count: parentIds.size });\n const parentFetches = Array.from(parentIds).map(async (parentId) => {\n try {\n const parentRes = await drive.files.get({\n fileId: parentId,\n fields: 'id,name',\n supportsAllDrives: true,\n });\n const parentName = (parentRes.data.name as string | undefined) || parentId;\n parentNameMap.set(parentId, parentName);\n } catch (e) {\n logger.info('Failed to fetch parent name', { parentId, error: e });\n parentNameMap.set(parentId, parentId); // Fallback to ID\n }\n });\n await Promise.all(parentFetches);\n }\n\n const items: DriveFile[] = files.map((f: driveFile) => {\n const id = f?.id ? String(f.id) : 'unknown';\n const name = f?.name || id;\n const result: DriveFile = { id, name };\n\n // Only include properties that have actual values\n if (f?.mimeType) result.mimeType = f.mimeType;\n if (f?.webViewLink) result.webViewLink = f.webViewLink;\n if (f?.modifiedTime) result.modifiedTime = f.modifiedTime;\n\n if (f?.parents && f.parents.length > 0) {\n result.parents = f.parents.map((parentId) => {\n if (parentId === 'root') {\n return { id: 'root', name: 'My Drive' };\n }\n const parentName = parentNameMap.get(parentId) || parentId;\n return { id: parentId, name: parentName };\n });\n }\n\n if (f?.shared != null) result.shared = f.shared;\n if (f?.starred != null) result.starred = f.starred;\n\n if (f?.owners && f.owners.length > 0) {\n result.owners = f.owners.map((o) => {\n const owner: NonNullable<DriveFile['owners']>[number] = {};\n if (o?.displayName) owner.displayName = o.displayName;\n if (o?.emailAddress) owner.emailAddress = o.emailAddress;\n if (o?.kind) owner.kind = o.kind;\n if (o?.me != null) owner.me = o.me;\n if (o?.permissionId) owner.permissionId = o.permissionId;\n if (o?.photoLink) owner.photoLink = o.photoLink;\n return owner;\n });\n }\n\n return result;\n });\n\n const filteredItems = items.map((item) => filterFields(item, requestedFields));\n\n logger.info('drive.files-search returning', {\n query: parsedQuery,\n pageSize,\n resultCount: filteredItems.length,\n fields: fields || 'all',\n });\n\n const nextPageToken = res.nextPageToken && res.nextPageToken.trim().length > 0 ? res.nextPageToken : undefined;\n\n // Build result based on shape\n const result: Output =\n shape === 'arrays'\n ? {\n type: 'success' as const,\n shape: 'arrays' as const,\n ...toColumnarFormat(filteredItems, requestedFields, DRIVE_FILE_FIELDS),\n count: filteredItems.length,\n ...(nextPageToken && { nextPageToken }),\n }\n : {\n type: 'success' as const,\n shape: 'objects' as const,\n items: filteredItems,\n count: filteredItems.length,\n ...(nextPageToken && { nextPageToken }),\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.files-search error', { error: message });\n\n // Throw ProtocolError for all errors so callers can see Drive validation details\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error searching files: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'files-search' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","query","DriveQueryParameterSchema","describe","fields","createFieldsSchema","availableFields","DRIVE_FILE_FIELDS","fieldDescriptions","DRIVE_FILE_FIELD_DESCRIPTIONS","commonPatterns","DRIVE_FILE_COMMON_PATTERNS","resourceName","createPaginationSchema","defaultPageSize","maxPageSize","provider","shape","createShapeSchema","successObjectsBranchSchema","type","literal","items","array","DriveFileSchema","count","number","nextPageToken","string","optional","successArraysBranchSchema","columns","rows","unknown","outputSchema","union","config","title","description","result","handler","extra","pageSize","pageToken","logger","parsedQuery","requestedFields","validPageSize","drive","qStr","q","listOptions","response","res","files","parentIds","f","parentId","parentNameMap","parentFetches","filteredItems","error","message","parseDriveQueryParameter","parseFields","Math","max","min","floor","info","undefined","driveApi","version","auth","googleAuth","authContext","rawDriveQuery","toDriveQuery","orderBy","corpora","supportsAllDrives","includeItemsFromAllDrives","trim","length","list","data","Array","isArray","Set","parents","add","Map","size","from","map","parentRes","parentName","e","get","fileId","name","set","Promise","all","id","String","mimeType","webViewLink","modifiedTime","shared","starred","owners","o","owner","displayName","emailAddress","kind","me","permissionId","photoLink","item","filterFields","resultCount","toColumnarFormat","content","text","JSON","stringify","structuredContent","Error","ProtocolError","ProtocolErrorCode","InternalError","stack"],"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AKC,SAAS,CAACxF;gCACvB;;4BAEFyF,mBAAmB;gCAAEzF,QAAAA;4BAAO;wBAC9B;;;oBACOsB;oBACDC,UAAUD,AAAK,YAALA,OAAiBoE,SAAQpE,MAAMC,OAAO,GAAG2C,OAAO5C;oBAChEjB,OAAOiB,KAAK,CAAC,4BAA4B;wBAAEA,OAAOC;oBAAQ;oBAE1D,iFAAiF;oBACjF,MAAM,IAAIoE,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,0BAAiC,OAARtE,UAAW;wBAC5FuE,OAAOxE,AAAK,YAALA,OAAiBoE,SAAQpE,MAAMwE,KAAK,GAAG/D;oBAChD;;;;;;;IAEJ;;AAEe,SAAS3E;IACtB,OAAO;QACLyG,MAAM;QACNhE,QAAAA;QACAI,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-drive/src/mcp/tools/files-search.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { type drive_v3, drive as driveApi } from '@googleapis/drive';\nimport { type CallToolResult, createFieldsSchema, createPaginationSchema, createShapeSchema, filterFields, ProtocolError, ProtocolErrorCode, parseFields, toColumnarFormat } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { toDriveQuery } from '../../lib/query-builder.ts';\nimport { DRIVE_FILE_COMMON_PATTERNS, DRIVE_FILE_FIELD_DESCRIPTIONS, DRIVE_FILE_FIELDS, type DriveFile, DriveFileSchema, DriveQueryParameterSchema, parseDriveQueryParameter } from '../../schemas/index.ts';\n\nconst inputSchema = z.object({\n query: DriveQueryParameterSchema.describe('Structured Drive query object or JSON string. Use rawDriveQuery for raw Drive syntax.'),\n fields: createFieldsSchema({\n availableFields: DRIVE_FILE_FIELDS,\n fieldDescriptions: DRIVE_FILE_FIELD_DESCRIPTIONS,\n commonPatterns: DRIVE_FILE_COMMON_PATTERNS,\n resourceName: 'Drive file',\n }),\n ...createPaginationSchema({\n defaultPageSize: 50,\n maxPageSize: 1000,\n provider: 'drive',\n }).shape,\n shape: createShapeSchema(),\n});\n\n// Success branch schemas for different shapes\nconst successObjectsBranchSchema = z.object({\n type: z.literal('success'),\n shape: z.literal('objects'),\n items: z.array(DriveFileSchema).describe('Matching Drive files'),\n count: z.number().describe('Number of files in this page'),\n nextPageToken: z.string().optional().describe('Token for fetching next page of results'),\n});\n\nconst successArraysBranchSchema = z.object({\n type: z.literal('success'),\n shape: z.literal('arrays'),\n columns: z.array(z.string()).describe('Column names in canonical order'),\n rows: z.array(z.array(z.unknown())).describe('Row data matching column order'),\n count: z.number().describe('Number of files in this page'),\n nextPageToken: z.string().optional().describe('Token for fetching next page of results'),\n});\n\n// Output schema with auth_required support\n// Using z.union instead of discriminatedUnion since we have two success branches with different shapes\nconst outputSchema = z.union([successObjectsBranchSchema, successArraysBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n title: 'Search Drive Files',\n description: 'Search Google Drive files with flexible field selection for optimal performance.',\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// Type for the raw Google Drive API response\ntype driveFile = drive_v3.Schema$File;\n\ntype driveResponse = drive_v3.Schema$FileList;\n\nasync function handler({ query, pageSize = 50, pageToken, fields, shape = 'arrays' }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n\n try {\n const parsedQuery = parseDriveQueryParameter(query);\n const requestedFields = parseFields(fields, DRIVE_FILE_FIELDS);\n\n // Validate and clamp pageSize to Google Drive API limits (1-1000)\n const validPageSize = Math.max(1, Math.min(1000, Math.floor(pageSize || 50)));\n\n logger.info('drive.files-search called', {\n query: parsedQuery,\n pageSize: validPageSize,\n pageToken: pageToken ? '[provided]' : undefined,\n fields: fields || 'all',\n });\n\n const drive = driveApi({ version: 'v3', auth: googleAuth(extra.authContext.auth) });\n\n // Handle query parameter\n let qStr: string;\n if (parsedQuery && 'rawDriveQuery' in parsedQuery && parsedQuery.rawDriveQuery) {\n // Object with rawDriveQuery field - use it directly\n qStr = parsedQuery.rawDriveQuery;\n } else if (parsedQuery) {\n // Structured query object - convert to Drive query string\n const { q } = toDriveQuery(parsedQuery);\n qStr = q || '';\n } else {\n qStr = '';\n }\n\n const listOptions: {\n q?: string;\n pageSize: number;\n fields: string;\n orderBy: string;\n pageToken?: string;\n corpora: string;\n supportsAllDrives: boolean;\n includeItemsFromAllDrives: boolean;\n } = {\n pageSize: validPageSize,\n fields: 'files(id,name,mimeType,webViewLink,modifiedTime,parents,shared,starred,owners),nextPageToken',\n orderBy: 'modifiedTime desc',\n // All three are load-bearing for shared drives: the default `user` corpus omits\n // them, and Drive rejects an `allDrives` corpus unless both flags are set too.\n corpora: 'allDrives',\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n };\n if (qStr.trim().length > 0) {\n listOptions.q = qStr;\n }\n if (pageToken && pageToken.trim().length > 0) {\n listOptions.pageToken = pageToken;\n }\n\n const response = await drive.files.list(listOptions);\n const res = response.data as driveResponse;\n const files = Array.isArray(res?.files) ? res.files : [];\n\n const parentIds = new Set<string>();\n for (const f of files) {\n if (f?.parents && f.parents.length > 0) {\n for (const parentId of f.parents) {\n if (parentId && parentId !== 'root') {\n parentIds.add(parentId);\n }\n }\n }\n }\n\n const parentNameMap = new Map<string, string>();\n if (parentIds.size > 0) {\n logger.info('Fetching parent names', { count: parentIds.size });\n const parentFetches = Array.from(parentIds).map(async (parentId) => {\n try {\n const parentRes = await drive.files.get({\n fileId: parentId,\n fields: 'id,name',\n supportsAllDrives: true,\n });\n const parentName = (parentRes.data.name as string | undefined) || parentId;\n parentNameMap.set(parentId, parentName);\n } catch (e) {\n logger.info('Failed to fetch parent name', { parentId, error: e });\n parentNameMap.set(parentId, parentId); // Fallback to ID\n }\n });\n await Promise.all(parentFetches);\n }\n\n const items: DriveFile[] = files.map((f: driveFile) => {\n const id = f?.id ? String(f.id) : 'unknown';\n const name = f?.name || id;\n const result: DriveFile = { id, name };\n\n // Only include properties that have actual values\n if (f?.mimeType) result.mimeType = f.mimeType;\n if (f?.webViewLink) result.webViewLink = f.webViewLink;\n if (f?.modifiedTime) result.modifiedTime = f.modifiedTime;\n\n if (f?.parents && f.parents.length > 0) {\n result.parents = f.parents.map((parentId) => {\n if (parentId === 'root') {\n return { id: 'root', name: 'My Drive' };\n }\n const parentName = parentNameMap.get(parentId) || parentId;\n return { id: parentId, name: parentName };\n });\n }\n\n if (f?.shared != null) result.shared = f.shared;\n if (f?.starred != null) result.starred = f.starred;\n\n if (f?.owners && f.owners.length > 0) {\n result.owners = f.owners.map((o) => {\n const owner: NonNullable<DriveFile['owners']>[number] = {};\n if (o?.displayName) owner.displayName = o.displayName;\n if (o?.emailAddress) owner.emailAddress = o.emailAddress;\n if (o?.kind) owner.kind = o.kind;\n if (o?.me != null) owner.me = o.me;\n if (o?.permissionId) owner.permissionId = o.permissionId;\n if (o?.photoLink) owner.photoLink = o.photoLink;\n return owner;\n });\n }\n\n return result;\n });\n\n const filteredItems = items.map((item) => filterFields(item, requestedFields));\n\n logger.info('drive.files-search returning', {\n query: parsedQuery,\n pageSize,\n resultCount: filteredItems.length,\n fields: fields || 'all',\n });\n\n const nextPageToken = res.nextPageToken && res.nextPageToken.trim().length > 0 ? res.nextPageToken : undefined;\n\n // Build result based on shape\n const result: Output =\n shape === 'arrays'\n ? {\n type: 'success' as const,\n shape: 'arrays' as const,\n ...toColumnarFormat(filteredItems, requestedFields, DRIVE_FILE_FIELDS),\n count: filteredItems.length,\n ...(nextPageToken && { nextPageToken }),\n }\n : {\n type: 'success' as const,\n shape: 'objects' as const,\n items: filteredItems,\n count: filteredItems.length,\n ...(nextPageToken && { nextPageToken }),\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.files-search error', { error: message });\n\n // Throw ProtocolError for all errors so callers can see Drive validation details\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error searching files: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'files-search' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","query","DriveQueryParameterSchema","describe","fields","createFieldsSchema","availableFields","DRIVE_FILE_FIELDS","fieldDescriptions","DRIVE_FILE_FIELD_DESCRIPTIONS","commonPatterns","DRIVE_FILE_COMMON_PATTERNS","resourceName","createPaginationSchema","defaultPageSize","maxPageSize","provider","shape","createShapeSchema","successObjectsBranchSchema","type","literal","items","array","DriveFileSchema","count","number","nextPageToken","string","optional","successArraysBranchSchema","columns","rows","unknown","outputSchema","union","config","title","description","result","handler","extra","pageSize","pageToken","logger","parsedQuery","requestedFields","validPageSize","drive","qStr","q","listOptions","response","res","files","parentIds","f","parentId","parentNameMap","parentFetches","filteredItems","error","message","parseDriveQueryParameter","parseFields","Math","max","min","floor","info","undefined","driveApi","version","auth","googleAuth","authContext","rawDriveQuery","toDriveQuery","orderBy","corpora","supportsAllDrives","includeItemsFromAllDrives","trim","length","list","data","Array","isArray","Set","parents","add","Map","size","from","map","parentRes","parentName","e","get","fileId","name","set","Promise","all","id","String","mimeType","webViewLink","modifiedTime","shared","starred","owners","o","owner","displayName","emailAddress","kind","me","permissionId","photoLink","item","filterFields","resultCount","toColumnarFormat","content","text","JSON","stringify","structuredContent","Error","ProtocolError","ProtocolErrorCode","InternalError","stack"],"mappings":";;;;+BAwPA;;;eAAwBA;;;2BAvPA;qBAIyB;sBACiI;mBAChK;4BACS;8BACE;uBACsJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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