@mcp-z/mcp-drive 2.2.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/cjs/mcp/resources/file.js +2 -1
  2. package/dist/cjs/mcp/resources/file.js.map +1 -1
  3. package/dist/cjs/mcp/tools/file-move-to-trash.js +2 -1
  4. package/dist/cjs/mcp/tools/file-move-to-trash.js.map +1 -1
  5. package/dist/cjs/mcp/tools/file-move.js +8 -4
  6. package/dist/cjs/mcp/tools/file-move.js.map +1 -1
  7. package/dist/cjs/mcp/tools/file-upload.js +2 -1
  8. package/dist/cjs/mcp/tools/file-upload.js.map +1 -1
  9. package/dist/cjs/mcp/tools/files-search.js +8 -2
  10. package/dist/cjs/mcp/tools/files-search.js.map +1 -1
  11. package/dist/cjs/mcp/tools/folder-contents.js +8 -2
  12. package/dist/cjs/mcp/tools/folder-contents.js.map +1 -1
  13. package/dist/cjs/mcp/tools/folder-create.js +4 -2
  14. package/dist/cjs/mcp/tools/folder-create.js.map +1 -1
  15. package/dist/cjs/mcp/tools/folder-path.js +2 -1
  16. package/dist/cjs/mcp/tools/folder-path.js.map +1 -1
  17. package/dist/cjs/mcp/tools/folder-search.js +12 -4
  18. package/dist/cjs/mcp/tools/folder-search.js.map +1 -1
  19. package/dist/cjs/setup/http.js +2 -0
  20. package/dist/cjs/setup/http.js.map +1 -1
  21. package/dist/cjs/setup/stdio.js +2 -0
  22. package/dist/cjs/setup/stdio.js.map +1 -1
  23. package/dist/esm/mcp/resources/file.js +2 -1
  24. package/dist/esm/mcp/resources/file.js.map +1 -1
  25. package/dist/esm/mcp/tools/file-move-to-trash.js +2 -1
  26. package/dist/esm/mcp/tools/file-move-to-trash.js.map +1 -1
  27. package/dist/esm/mcp/tools/file-move.js +8 -4
  28. package/dist/esm/mcp/tools/file-move.js.map +1 -1
  29. package/dist/esm/mcp/tools/file-upload.js +2 -1
  30. package/dist/esm/mcp/tools/file-upload.js.map +1 -1
  31. package/dist/esm/mcp/tools/files-search.js +8 -2
  32. package/dist/esm/mcp/tools/files-search.js.map +1 -1
  33. package/dist/esm/mcp/tools/folder-contents.js +8 -2
  34. package/dist/esm/mcp/tools/folder-contents.js.map +1 -1
  35. package/dist/esm/mcp/tools/folder-create.js +4 -2
  36. package/dist/esm/mcp/tools/folder-create.js.map +1 -1
  37. package/dist/esm/mcp/tools/folder-path.js +2 -1
  38. package/dist/esm/mcp/tools/folder-path.js.map +1 -1
  39. package/dist/esm/mcp/tools/folder-search.js +12 -4
  40. package/dist/esm/mcp/tools/folder-search.js.map +1 -1
  41. package/dist/esm/setup/http.js +3 -1
  42. package/dist/esm/setup/http.js.map +1 -1
  43. package/dist/esm/setup/stdio.js +3 -1
  44. package/dist/esm/setup/stdio.js.map +1 -1
  45. package/package.json +2 -3
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/tools/folder-create.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 { googleAuth } from '../../lib/google-auth.ts';\n\nconst inputSchema = z.object({\n name: z.string().trim().min(1).describe('Name for the new folder'),\n parentId: z.string().optional().describe('Parent folder ID (omit to create in My Drive root)'),\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n operationSummary: z.string().describe('Summary of the folder creation operation'),\n itemsProcessed: z.number().describe('Total items attempted (always 1 for single folder)'),\n itemsChanged: z.number().describe('Successfully created folders (always 1 on success)'),\n completedAt: z.string().describe('ISO datetime when operation completed'),\n id: z.string().describe('ID of the created folder'),\n name: z.string().describe('Name of the created folder'),\n webViewLink: z.string().describe('URL to view the folder 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: 'Create Folder',\n description: 'Create a new folder in Google Drive. Returns folder 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({ name: folderName, parentId }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('drive.folder.create called', {\n name: folderName,\n parentId: parentId || 'root',\n });\n\n try {\n const drive = driveApi({ version: 'v3', auth: googleAuth(extra.authContext.auth) });\n\n // Folder MIME type constant (consistent with folder-search.ts)\n const folderMimeType = 'application/vnd.google-apps.folder';\n\n // Create the folder\n const response = await drive.files.create({\n requestBody: {\n name: folderName,\n mimeType: folderMimeType,\n parents: parentId ? [parentId] : null,\n },\n fields: 'id,name,webViewLink,parents',\n });\n\n const res = response.data;\n const id = res.id ?? '';\n const name = res.name ?? folderName;\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 });\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.folder.create success', {\n id,\n name,\n parentId: actualParentId,\n });\n\n // Build result object with operation metadata\n const result: Output = {\n type: 'success' as const,\n operationSummary: `Created folder \"${name}\"${locationSummary}`,\n itemsProcessed: 1,\n itemsChanged: 1,\n completedAt: new Date().toISOString(),\n id,\n name,\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.folder.create error', { error: message });\n\n // Throw ProtocolError for proper MCP error handling\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error creating folder: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'folder-create' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","name","string","trim","min","describe","parentId","optional","successBranchSchema","type","literal","operationSummary","itemsProcessed","number","itemsChanged","completedAt","id","webViewLink","parentName","outputSchema","discriminatedUnion","config","title","description","result","handler","extra","folderName","logger","res","drive","folderMimeType","response","parents","actualParentId","parentResponse","e","locationSummary","error","message","info","driveApi","version","auth","googleAuth","authContext","files","create","requestBody","mimeType","fields","data","length","get","fileId","Date","toISOString","content","text","JSON","stringify","structuredContent","Error","String","ProtocolError","ProtocolErrorCode","InternalError","stack","undefined"],"mappings":";;;;+BA+IA;;;eAAwBA;;;2BA9IA;qBAIU;sBAEe;mBAC/B;4BACS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAN3B,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAQR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,MAAMF,MAAC,CAACG,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YAAW,OAAK;oBAE7DU,OAAOY,IAAI,CAAC,+BAA+B;wBACzCxB,IAAAA;wBACAf,MAAAA;wBACAK,UAAU4B;oBACZ;oBAEA,8CAA8C;oBACxCV,SAAiB;wBACrBf,MAAM;wBACNE,kBAAkB,AAAC,mBAA0B0B,OAARpC,MAAK,KAAmB,OAAhBoC;wBAC7CzB,gBAAgB;wBAChBE,cAAc;wBACdC,aAAa,IAAIwC,OAAOC,WAAW;wBACnCxC,IAAAA;wBACAf,MAAAA;wBACAgB,aAAAA;uBACIiB,kBAAkB;wBAAE5B,UAAU4B;oBAAe,GAC7ChB,cAAc;wBAAEA,YAAAA;oBAAW;oBAGjC;;wBAAO;4BACLuC,OAAO;gCACL;oCACEhD,MAAM;oCACNiD,MAAMC,KAAKC,SAAS,CAACpC;gCACvB;;4BAEFqC,mBAAmB;gCAAErC,QAAAA;4BAAO;wBAC9B;;;oBACOc;oBACDC,UAAUD,AAAK,YAALA,OAAiBwB,SAAQxB,MAAMC,OAAO,GAAGwB,OAAOzB;oBAChEV,OAAOU,KAAK,CAAC,6BAA6B;wBAAEA,OAAOC;oBAAQ;oBAE3D,oDAAoD;oBACpD,MAAM,IAAIyB,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,0BAAiC,OAAR3B,UAAW;wBAC5F4B,OAAO7B,AAAK,YAALA,OAAiBwB,SAAQxB,MAAM6B,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAASzE;IACtB,OAAO;QACLM,MAAM;QACNoB,QAAAA;QACAI,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/tools/folder-create.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 { googleAuth } from '../../lib/google-auth.ts';\n\nconst inputSchema = z.object({\n name: z.string().trim().min(1).describe('Name for the new folder'),\n parentId: z.string().optional().describe('Parent folder ID (omit to create in My Drive root)'),\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n operationSummary: z.string().describe('Summary of the folder creation operation'),\n itemsProcessed: z.number().describe('Total items attempted (always 1 for single folder)'),\n itemsChanged: z.number().describe('Successfully created folders (always 1 on success)'),\n completedAt: z.string().describe('ISO datetime when operation completed'),\n id: z.string().describe('ID of the created folder'),\n name: z.string().describe('Name of the created folder'),\n webViewLink: z.string().describe('URL to view the folder 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: 'Create Folder',\n description: 'Create a new folder in Google Drive. Returns folder 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({ name: folderName, parentId }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('drive.folder.create called', {\n name: folderName,\n parentId: parentId || 'root',\n });\n\n try {\n const drive = driveApi({ version: 'v3', auth: googleAuth(extra.authContext.auth) });\n\n // Folder MIME type constant (consistent with folder-search.ts)\n const folderMimeType = 'application/vnd.google-apps.folder';\n\n // Create the folder\n const response = await drive.files.create({\n requestBody: {\n name: folderName,\n mimeType: folderMimeType,\n parents: parentId ? [parentId] : null,\n },\n fields: 'id,name,webViewLink,parents',\n supportsAllDrives: true,\n });\n\n const res = response.data;\n const id = res.id ?? '';\n const name = res.name ?? folderName;\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.folder.create success', {\n id,\n name,\n parentId: actualParentId,\n });\n\n // Build result object with operation metadata\n const result: Output = {\n type: 'success' as const,\n operationSummary: `Created folder \"${name}\"${locationSummary}`,\n itemsProcessed: 1,\n itemsChanged: 1,\n completedAt: new Date().toISOString(),\n id,\n name,\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.folder.create error', { error: message });\n\n // Throw ProtocolError for proper MCP error handling\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error creating folder: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'folder-create' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","name","string","trim","min","describe","parentId","optional","successBranchSchema","type","literal","operationSummary","itemsProcessed","number","itemsChanged","completedAt","id","webViewLink","parentName","outputSchema","discriminatedUnion","config","title","description","result","handler","extra","folderName","logger","res","drive","folderMimeType","response","parents","actualParentId","parentResponse","e","locationSummary","error","message","info","driveApi","version","auth","googleAuth","authContext","files","create","requestBody","mimeType","fields","supportsAllDrives","data","length","get","fileId","Date","toISOString","content","text","JSON","stringify","structuredContent","Error","String","ProtocolError","ProtocolErrorCode","InternalError","stack","undefined"],"mappings":";;;;+BAiJA;;;eAAwBA;;;2BAhJA;qBAIU;sBAEe;mBAC/B;4BACS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAN3B,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAQR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,MAAMF,MAAC,CAACG,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IACxCC,UAAUP,MAAC,CAACG,MAAM,GAAGK,QAAQ,GAAGF,QAAQ,CAAC;AAC3C;AAEA,wBAAwB;AACxB,IAAMG,sBAAsBT,MAAC,CAACC,MAAM,CAAC;IACnCS,MAAMV,MAAC,CAACW,OAAO,CAAC;IAChBC,kBAAkBZ,MAAC,CAACG,MAAM,GAAGG,QAAQ,CAAC;IACtCO,gBAAgBb,MAAC,CAACc,MAAM,GAAGR,QAAQ,CAAC;IACpCS,cAAcf,MAAC,CAACc,MAAM,GAAGR,QAAQ,CAAC;IAClCU,aAAahB,MAAC,CAACG,MAAM,GAAGG,QAAQ,CAAC;IACjCW,IAAIjB,MAAC,CAACG,MAAM,GAAGG,QAAQ,CAAC;IACxBJ,MAAMF,MAAC,CAACG,MAAM,GAAGG,QAAQ,CAAC;IAC1BY,aAAalB,MAAC,CAACG,MAAM,GAAGG,QAAQ,CAAC;IACjCC,UAAUP,MAAC,CAACG,MAAM,GAAGK,QAAQ,GAAGF,QAAQ,CAAC;IACzCa,YAAYnB,MAAC,CAACG,MAAM,GAAGK,QAAQ,GAAGF,QAAQ,CAAC;AA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;oBACpD,MAAM,IAAI0B,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,0BAAiC,OAAR5B,UAAW;wBAC5F6B,OAAO9B,AAAK,YAALA,OAAiByB,SAAQzB,MAAM8B,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAAS1E;IACtB,OAAO;QACLM,MAAM;QACNoB,QAAAA;QACAI,SAAAA;IACF;AACF"}
@@ -226,7 +226,8 @@ var config = {
226
226
  4,
227
227
  drive.files.get({
228
228
  fileId: currentId,
229
- fields: 'id,name,parents'
229
+ fields: 'id,name,parents',
230
+ supportsAllDrives: true
230
231
  })
231
232
  ];
232
233
  case 3:
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/tools/folder-path.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\nconst inputSchema = z.object({\n folderId: z.string().min(1).describe('Folder ID to get path for (or \"root\")'),\n});\n\n// Success branch schema - uses items: for consistency with standard vocabulary\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n path: z.string().describe('Full path from root (e.g., /Work/Projects/2024)'),\n items: z\n .array(\n z.object({\n id: z.string().describe('Folder ID'),\n name: z.string().describe('Folder name'),\n })\n )\n .describe('Path items from root to target folder'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n title: 'Get Folder Path',\n description: 'Get full path from folder to root. Returns human-readable path and items with IDs.',\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 * Resolves the full path for a folder by walking up the parent chain.\n * Returns both the path string and structured segments with IDs and names.\n */\nasync function resolveFolderPath(drive: drive_v3.Drive, folderId: string, logger: Logger): Promise<{ path: string; segments: Array<{ id: string; name: string }> }> {\n // Handle root specially\n if (folderId === 'root') {\n return {\n path: '/',\n segments: [{ id: 'root', name: 'My Drive' }],\n };\n }\n\n const segments: Array<{ id: string; name: string }> = [];\n let currentId = folderId;\n const visited = new Set<string>();\n\n // Walk up the parent chain\n while (currentId && currentId !== 'root') {\n // Prevent infinite loops\n if (visited.has(currentId)) {\n logger.info('Circular folder reference detected', {\n folderId: currentId,\n });\n break;\n }\n visited.add(currentId);\n\n // Fetch folder metadata\n try {\n const response = await drive.files.get({\n fileId: currentId,\n fields: 'id,name,parents',\n });\n\n const id = response.data.id as string;\n const name = (response.data.name as string) || id;\n const parents = response.data.parents as string[] | undefined;\n\n // Add to segments at beginning (we're walking from child to root)\n segments.unshift({ id, name });\n\n // Move to parent\n currentId = (parents && parents.length > 0 ? parents[0] : '') || '';\n } catch (e) {\n logger.info('Failed to resolve folder path', {\n folderId: currentId,\n error: e,\n });\n break;\n }\n }\n\n // Add root if we reached it\n if (currentId === 'root') {\n segments.unshift({ id: 'root', name: 'My Drive' });\n }\n\n // Build path string\n const pathParts = segments.slice(1).map((seg) => seg.name); // Skip root\n const path = pathParts.length > 0 ? `/${pathParts.join('/')}` : '/';\n\n return { path, segments };\n}\n\nasync function handler({ folderId }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('drive.folder.path called', { folderId });\n\n try {\n const drive = driveApi({ version: 'v3', auth: googleAuth(extra.authContext.auth) });\n\n const pathResult = await resolveFolderPath(drive, folderId, logger);\n\n logger.info('drive.folder.path returning', {\n path: pathResult.path,\n segmentCount: pathResult.segments.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n path: pathResult.path,\n items: pathResult.segments,\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.folder.path error', { error: message });\n\n // Throw ProtocolError\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error getting folder path: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'folder-path' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","folderId","string","min","describe","successBranchSchema","type","literal","path","items","array","id","name","outputSchema","discriminatedUnion","config","title","description","result","resolveFolderPath","drive","logger","segments","currentId","visited","response","parents","e","pathParts","Set","has","info","add","files","get","fileId","fields","data","unshift","length","error","slice","map","seg","join","handler","extra","pathResult","message","driveApi","version","auth","googleAuth","authContext","segmentCount","content","text","JSON","stringify","structuredContent","Error","String","ProtocolError","ProtocolErrorCode","InternalError","stack","undefined"],"mappings":";;;;+BAsJA;;;eAAwBA;;;2BArJA;qBAKU;sBACoC;mBACpD;4BACS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAN3B,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AASR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,UAAUF,MAAC,CAACG,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;AACvC;AAEA,+EAA+E;AAC/E,IAAMC,sBAAsBN,MAAC,CAACC,MAAM,CAAC;IACnCM,MAAMP,MAAC,CAACQ,OAAO,CAAC;IAChBC,MAAMT,MAAC,CAACG,MAAM,GAAGE,QAAQ,CAAC;IAC1BK,OAAOV,MAAC,CACL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C,WAAWvC,IAAI;wBACrBC,OAAOsC,WAAWzB,QAAQ;oBAC5B;oBAEA;;wBAAO;4BACLiC,OAAO;gCACL;oCACEjD,MAAM;oCACNkD,MAAMC,KAAKC,SAAS,CAACxC;gCACvB;;4BAEFyC,mBAAmB;gCAAEzC,QAAAA;4BAAO;wBAC9B;;;oBACOsB;oBACDQ,UAAUR,AAAK,YAALA,OAAiBoB,SAAQpB,MAAMQ,OAAO,GAAGa,OAAOrB;oBAChEnB,OAAOmB,KAAK,CAAC,2BAA2B;wBAAEA,OAAOQ;oBAAQ;oBAEzD,sBAAsB;oBACtB,MAAM,IAAIc,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,8BAAqC,OAARhB,UAAW;wBAChGiB,OAAOzB,AAAK,YAALA,OAAiBoB,SAAQpB,MAAMyB,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAASvE;IACtB,OAAO;QACLiB,MAAM;QACNG,QAAAA;QACA8B,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/tools/folder-path.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\nconst inputSchema = z.object({\n folderId: z.string().min(1).describe('Folder ID to get path for (or \"root\")'),\n});\n\n// Success branch schema - uses items: for consistency with standard vocabulary\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n path: z.string().describe('Full path from root (e.g., /Work/Projects/2024)'),\n items: z\n .array(\n z.object({\n id: z.string().describe('Folder ID'),\n name: z.string().describe('Folder name'),\n })\n )\n .describe('Path items from root to target folder'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n title: 'Get Folder Path',\n description: 'Get full path from folder to root. Returns human-readable path and items with IDs.',\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 * Resolves the full path for a folder by walking up the parent chain.\n * Returns both the path string and structured segments with IDs and names.\n */\nasync function resolveFolderPath(drive: drive_v3.Drive, folderId: string, logger: Logger): Promise<{ path: string; segments: Array<{ id: string; name: string }> }> {\n // Handle root specially\n if (folderId === 'root') {\n return {\n path: '/',\n segments: [{ id: 'root', name: 'My Drive' }],\n };\n }\n\n const segments: Array<{ id: string; name: string }> = [];\n let currentId = folderId;\n const visited = new Set<string>();\n\n // Walk up the parent chain\n while (currentId && currentId !== 'root') {\n // Prevent infinite loops\n if (visited.has(currentId)) {\n logger.info('Circular folder reference detected', {\n folderId: currentId,\n });\n break;\n }\n visited.add(currentId);\n\n // Fetch folder metadata\n try {\n const response = await drive.files.get({\n fileId: currentId,\n fields: 'id,name,parents',\n supportsAllDrives: true,\n });\n\n const id = response.data.id as string;\n const name = (response.data.name as string) || id;\n const parents = response.data.parents as string[] | undefined;\n\n // Add to segments at beginning (we're walking from child to root)\n segments.unshift({ id, name });\n\n // Move to parent\n currentId = (parents && parents.length > 0 ? parents[0] : '') || '';\n } catch (e) {\n logger.info('Failed to resolve folder path', {\n folderId: currentId,\n error: e,\n });\n break;\n }\n }\n\n // Add root if we reached it\n if (currentId === 'root') {\n segments.unshift({ id: 'root', name: 'My Drive' });\n }\n\n // Build path string\n const pathParts = segments.slice(1).map((seg) => seg.name); // Skip root\n const path = pathParts.length > 0 ? `/${pathParts.join('/')}` : '/';\n\n return { path, segments };\n}\n\nasync function handler({ folderId }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('drive.folder.path called', { folderId });\n\n try {\n const drive = driveApi({ version: 'v3', auth: googleAuth(extra.authContext.auth) });\n\n const pathResult = await resolveFolderPath(drive, folderId, logger);\n\n logger.info('drive.folder.path returning', {\n path: pathResult.path,\n segmentCount: pathResult.segments.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n path: pathResult.path,\n items: pathResult.segments,\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.folder.path error', { error: message });\n\n // Throw ProtocolError\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error getting folder path: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'folder-path' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","folderId","string","min","describe","successBranchSchema","type","literal","path","items","array","id","name","outputSchema","discriminatedUnion","config","title","description","result","resolveFolderPath","drive","logger","segments","currentId","visited","response","parents","e","pathParts","Set","has","info","add","files","get","fileId","fields","supportsAllDrives","data","unshift","length","error","slice","map","seg","join","handler","extra","pathResult","message","driveApi","version","auth","googleAuth","authContext","segmentCount","content","text","JSON","stringify","structuredContent","Error","String","ProtocolError","ProtocolErrorCode","InternalError","stack","undefined"],"mappings":";;;;+BAuJA;;;eAAwBA;;;2BAtJA;qBAKU;sBACoC;mBACpD;4BACS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAN3B,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AASR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,UAAUF,MAAC,CAACG,MAAM,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I;oBAAE;oBAE9D;;wBAAMjC,kBAAkBC,OAAOnB,UAAUoB;;;oBAAtD2B,aAAa;oBAEnB3B,OAAOU,IAAI,CAAC,+BAA+B;wBACzCvB,MAAMwC,WAAWxC,IAAI;wBACrB+C,cAAcP,WAAW1B,QAAQ,CAACkB,MAAM;oBAC1C;oBAEMtB,SAAiB;wBACrBZ,MAAM;wBACNE,MAAMwC,WAAWxC,IAAI;wBACrBC,OAAOuC,WAAW1B,QAAQ;oBAC5B;oBAEA;;wBAAO;4BACLkC,OAAO;gCACL;oCACElD,MAAM;oCACNmD,MAAMC,KAAKC,SAAS,CAACzC;gCACvB;;4BAEF0C,mBAAmB;gCAAE1C,QAAAA;4BAAO;wBAC9B;;;oBACOuB;oBACDQ,UAAUR,AAAK,YAALA,OAAiBoB,SAAQpB,MAAMQ,OAAO,GAAGa,OAAOrB;oBAChEpB,OAAOoB,KAAK,CAAC,2BAA2B;wBAAEA,OAAOQ;oBAAQ;oBAEzD,sBAAsB;oBACtB,MAAM,IAAIc,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,8BAAqC,OAARhB,UAAW;wBAChGiB,OAAOzB,AAAK,YAALA,OAAiBoB,SAAQpB,MAAMyB,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAASxE;IACtB,OAAO;QACLiB,MAAM;QACNG,QAAAA;QACA+B,SAAAA;IACF;AACF"}
@@ -329,7 +329,8 @@ var config = {
329
329
  4,
330
330
  drive.files.get({
331
331
  fileId: currentId,
332
- fields: 'parents'
332
+ fields: 'parents',
333
+ supportsAllDrives: true
333
334
  })
334
335
  ];
335
336
  case 3:
@@ -365,7 +366,8 @@ var config = {
365
366
  4,
366
367
  drive.files.get({
367
368
  fileId: currentId,
368
- fields: 'name,parents'
369
+ fields: 'name,parents',
370
+ supportsAllDrives: true
369
371
  })
370
372
  ];
371
373
  case 7:
@@ -454,7 +456,12 @@ function handler(_0, _1) {
454
456
  q: qStr,
455
457
  pageSize: validPageSize,
456
458
  fields: 'files(id,name,mimeType,webViewLink,modifiedTime,parents,shared,starred,owners),nextPageToken',
457
- orderBy: 'modifiedTime desc'
459
+ orderBy: 'modifiedTime desc',
460
+ // All three are load-bearing for shared drives: the default `user` corpus omits
461
+ // them, and Drive rejects an `allDrives` corpus unless both flags are set too.
462
+ corpora: 'allDrives',
463
+ supportsAllDrives: true,
464
+ includeItemsFromAllDrives: true
458
465
  };
459
466
  if (pageToken && pageToken.trim().length > 0) {
460
467
  listOptions.pageToken = pageToken;
@@ -535,7 +542,8 @@ function handler(_0, _1) {
535
542
  4,
536
543
  drive.files.get({
537
544
  fileId: parentId,
538
- fields: 'id,name'
545
+ fields: 'id,name',
546
+ supportsAllDrives: true
539
547
  })
540
548
  ];
541
549
  case 1:
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/tools/folder-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 } from '@googleapis/drive';\nimport { 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';\nimport type { Logger } from '../../types.ts';\n\nconst inputSchema = z.object({\n query: DriveQueryParameterSchema.optional().describe('Structured Drive query object or JSON string. Use rawDriveQuery for raw Drive syntax.'),\n fields: createFieldsSchema({\n availableFields: [...DRIVE_FILE_FIELDS, 'path'] as const,\n fieldDescriptions: {\n ...DRIVE_FILE_FIELD_DESCRIPTIONS,\n path: 'Full folder path like /Work/Projects (requires resolvePaths=true)',\n },\n commonPatterns: DRIVE_FILE_COMMON_PATTERNS,\n resourceName: 'Drive folder',\n }),\n resolvePaths: z.boolean().optional().describe('Resolve full folder paths like /Work/Projects/2024 (requires additional API calls per result)'),\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.extend({ path: z.string().optional().describe('Full folder path (if resolvePaths=true)') })).describe('Matching Drive folders'),\n count: z.number().describe('Number of folders 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 folders 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 Folders',\n description: 'Search Google Drive folders with flexible field selection and optional path resolution.',\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 DriveFolder = {\n id?: string;\n name?: string;\n mimeType?: string;\n webViewLink?: string;\n modifiedTime?: string;\n parents?: string[];\n shared?: boolean;\n starred?: boolean;\n owners?: Array<{\n displayName?: string;\n emailAddress?: string;\n kind?: string;\n me?: boolean;\n permissionId?: string;\n photoLink?: string;\n }>;\n};\n\ntype DriveFolderResponse = {\n files?: DriveFolder[];\n nextPageToken?: string;\n};\n\n/**\n * Resolves the full path for a folder by walking up the parent chain\n * Caches folder names to reduce redundant API calls\n */\nasync function resolveFolderPath(drive: drive_v3.Drive, folderId: string, folderCache: Map<string, string>, logger: Logger): Promise<string> {\n if (folderId === 'root') return '/';\n\n const pathParts: string[] = [];\n let currentId = folderId;\n const visited = new Set<string>();\n\n while (currentId && currentId !== 'root') {\n // Prevent infinite loops\n if (visited.has(currentId)) {\n logger.info('Circular folder reference detected', {\n folderId: currentId,\n });\n break;\n }\n visited.add(currentId);\n\n // Check cache first\n if (folderCache.has(currentId)) {\n const cachedName = folderCache.get(currentId);\n if (cachedName) {\n pathParts.unshift(cachedName);\n }\n\n // Get parent of cached folder\n try {\n const response = await drive.files.get({\n fileId: currentId,\n fields: 'parents',\n });\n const parents = response.data.parents as string[] | undefined;\n currentId = (parents && parents.length > 0 ? parents[0] : '') || '';\n } catch (_e) {\n logger.info('Failed to get parent for cached folder', {\n folderId: currentId,\n });\n break;\n }\n } else {\n // Fetch folder metadata\n try {\n const response = await drive.files.get({\n fileId: currentId,\n fields: 'name,parents',\n });\n const folderName = response.data.name as string | undefined;\n const parents = response.data.parents as string[] | undefined;\n\n if (folderName) {\n folderCache.set(currentId, folderName);\n pathParts.unshift(folderName);\n }\n\n currentId = (parents && parents.length > 0 ? parents[0] : '') || '';\n } catch (e) {\n logger.info('Failed to resolve folder path', {\n folderId: currentId,\n error: e,\n });\n break;\n }\n }\n }\n\n return `/${pathParts.join('/')}`;\n}\n\nasync function handler({ query, resolvePaths = false, 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, 'path'] as const);\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.folder.search called', {\n query: parsedQuery,\n resolvePaths,\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 const folderMimeType = 'application/vnd.google-apps.folder';\n let qStr: string;\n\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 qStr = qStr ? `(${qStr}) and mimeType='${folderMimeType}'` : `mimeType='${folderMimeType}'`;\n\n const listOptions: {\n q: string;\n pageSize: number;\n fields: string;\n orderBy: string;\n pageToken?: string;\n } = {\n q: qStr,\n pageSize: validPageSize,\n fields: 'files(id,name,mimeType,webViewLink,modifiedTime,parents,shared,starred,owners),nextPageToken',\n orderBy: 'modifiedTime desc',\n };\n if (pageToken && pageToken.trim().length > 0) {\n listOptions.pageToken = pageToken;\n }\n\n const response = await drive.files.list(listOptions);\n\n const res = response.data as DriveFolderResponse;\n const folders = Array.isArray(res?.files) ? res.files : [];\n\n const parentIds = new Set<string>();\n for (const f of folders) {\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 });\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 // Cache for folder names to reduce API calls during path resolution\n const folderCache = new Map<string, string>();\n\n const items: (DriveFile & { path?: string })[] = await Promise.all(\n folders.map(async (f: DriveFolder) => {\n const id = f?.id ? String(f.id) : 'unknown';\n const name = f?.name || id;\n const result: DriveFile & { path?: string } = { 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 // Build parent objects with names\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 !== undefined) result.shared = f.shared;\n if (f?.starred !== undefined) 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 !== undefined) 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 // Resolve path if requested\n if (resolvePaths && id !== 'unknown') {\n result.path = await resolveFolderPath(drive, id, folderCache, logger);\n }\n\n return result;\n })\n );\n\n const filteredItems = items.map((item) => filterFields(item, requestedFields));\n\n logger.info('drive.folder.search returning', {\n query: parsedQuery,\n pageSize,\n resultCount: filteredItems.length,\n resolvePaths,\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, 'path'] as const),\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.folder.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 folders: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'folder-search' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","query","DriveQueryParameterSchema","optional","describe","fields","createFieldsSchema","availableFields","DRIVE_FILE_FIELDS","fieldDescriptions","DRIVE_FILE_FIELD_DESCRIPTIONS","path","commonPatterns","DRIVE_FILE_COMMON_PATTERNS","resourceName","resolvePaths","boolean","createPaginationSchema","defaultPageSize","maxPageSize","provider","shape","createShapeSchema","successObjectsBranchSchema","type","literal","items","array","DriveFileSchema","extend","string","count","number","nextPageToken","successArraysBranchSchema","columns","rows","unknown","outputSchema","union","config","title","description","result","resolveFolderPath","drive","folderId","folderCache","logger","pathParts","currentId","visited","cachedName","response","parents","_e","folderName","e","Set","has","info","add","get","unshift","files","fileId","data","length","name","set","error","join","handler","extra","pageSize","pageToken","parsedQuery","requestedFields","validPageSize","folderMimeType","qStr","q","listOptions","res","folders","parentIds","f","parentId","parentNameMap","parentFetches","filteredItems","message","parseDriveQueryParameter","parseFields","Math","max","min","floor","undefined","driveApi","version","auth","googleAuth","authContext","rawDriveQuery","toDriveQuery","orderBy","trim","list","Array","isArray","Map","size","from","map","parentRes","parentName","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":";;;;+BA+VA;;;eAAwBA;;;2BA9VA;qBAKU;sBACgJ;mBAChK;4BACS;8BACE;uBACsJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AARnL,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAWR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,OAAOC,kCAAyB,CAACC,QAAQ,GAAGC,QAAQ,CAAC;IACrDC,QAAQC,IAAAA,0BAAkB,EAAC;QACzBC,iBAAiB,AAAC,qBAAGC,0BAAiB,SAArB;YAAuB;SAAO;QAC/CC,mBAAmB,wCACdC,sCAA6B;YAChCC,MAAM;;QAERC,gBAAgBC,mCAA0B;QAC1CC,cAAc;IAChB;IACAC,cAAchB,MAAC,CAACiB,OAAO,GAAGb,QAAQ,GAAGC,QAAQ,CAAC;GAC3Ca,IAAAA,8BAAsB,EAAC;IACxBC,iBAAiB;IACjBC,aAAa;IACbC,UAAU;AACZ,GAAGC,KAAK;IACRA,OAAOC,IAAAA,yBAAiB;;AAG1B,8CAA8C;AAC9C,IAAMC,6BAA6BxB,MAAC,CAACC,MAAM,CAAC;IAC1CwB,MAAMzB,MAAC,CAAC0B,OAAO,CAAC;IAChBJ,OAAOtB,MAAC,CAAC0B,OAAO,CAAC;IACjBC,OAAO3B,MAAC,CAAC4B,KAAK,CAACC,wBAAe,CAACC,MAAM,CAAC;QAAElB,MAAMZ,MAAC,CAAC+B,MAAM,GAAG3B,QAAQ,GAAGC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oBAAQ;oBAE3D,iFAAiF;oBACjF,MAAM,IAAIsD,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,4BAAmC,OAARxD,UAAW;wBAC9FyD,OAAO9E,AAAK,YAALA,OAAiB0E,SAAQ1E,MAAM8E,KAAK,GAAGlD;oBAChD;;;;;;;IAEJ;;AAEe,SAASvG;IACtB,OAAO;QACLyE,MAAM;QACN5B,QAAAA;QACAgC,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/tools/folder-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 } from '@googleapis/drive';\nimport { 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';\nimport type { Logger } from '../../types.ts';\n\nconst inputSchema = z.object({\n query: DriveQueryParameterSchema.optional().describe('Structured Drive query object or JSON string. Use rawDriveQuery for raw Drive syntax.'),\n fields: createFieldsSchema({\n availableFields: [...DRIVE_FILE_FIELDS, 'path'] as const,\n fieldDescriptions: {\n ...DRIVE_FILE_FIELD_DESCRIPTIONS,\n path: 'Full folder path like /Work/Projects (requires resolvePaths=true)',\n },\n commonPatterns: DRIVE_FILE_COMMON_PATTERNS,\n resourceName: 'Drive folder',\n }),\n resolvePaths: z.boolean().optional().describe('Resolve full folder paths like /Work/Projects/2024 (requires additional API calls per result)'),\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.extend({ path: z.string().optional().describe('Full folder path (if resolvePaths=true)') })).describe('Matching Drive folders'),\n count: z.number().describe('Number of folders 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 folders 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 Folders',\n description: 'Search Google Drive folders with flexible field selection and optional path resolution.',\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 DriveFolder = {\n id?: string;\n name?: string;\n mimeType?: string;\n webViewLink?: string;\n modifiedTime?: string;\n parents?: string[];\n shared?: boolean;\n starred?: boolean;\n owners?: Array<{\n displayName?: string;\n emailAddress?: string;\n kind?: string;\n me?: boolean;\n permissionId?: string;\n photoLink?: string;\n }>;\n};\n\ntype DriveFolderResponse = {\n files?: DriveFolder[];\n nextPageToken?: string;\n};\n\n/**\n * Resolves the full path for a folder by walking up the parent chain\n * Caches folder names to reduce redundant API calls\n */\nasync function resolveFolderPath(drive: drive_v3.Drive, folderId: string, folderCache: Map<string, string>, logger: Logger): Promise<string> {\n if (folderId === 'root') return '/';\n\n const pathParts: string[] = [];\n let currentId = folderId;\n const visited = new Set<string>();\n\n while (currentId && currentId !== 'root') {\n // Prevent infinite loops\n if (visited.has(currentId)) {\n logger.info('Circular folder reference detected', {\n folderId: currentId,\n });\n break;\n }\n visited.add(currentId);\n\n // Check cache first\n if (folderCache.has(currentId)) {\n const cachedName = folderCache.get(currentId);\n if (cachedName) {\n pathParts.unshift(cachedName);\n }\n\n // Get parent of cached folder\n try {\n const response = await drive.files.get({\n fileId: currentId,\n fields: 'parents',\n supportsAllDrives: true,\n });\n const parents = response.data.parents as string[] | undefined;\n currentId = (parents && parents.length > 0 ? parents[0] : '') || '';\n } catch (_e) {\n logger.info('Failed to get parent for cached folder', {\n folderId: currentId,\n });\n break;\n }\n } else {\n // Fetch folder metadata\n try {\n const response = await drive.files.get({\n fileId: currentId,\n fields: 'name,parents',\n supportsAllDrives: true,\n });\n const folderName = response.data.name as string | undefined;\n const parents = response.data.parents as string[] | undefined;\n\n if (folderName) {\n folderCache.set(currentId, folderName);\n pathParts.unshift(folderName);\n }\n\n currentId = (parents && parents.length > 0 ? parents[0] : '') || '';\n } catch (e) {\n logger.info('Failed to resolve folder path', {\n folderId: currentId,\n error: e,\n });\n break;\n }\n }\n }\n\n return `/${pathParts.join('/')}`;\n}\n\nasync function handler({ query, resolvePaths = false, 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, 'path'] as const);\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.folder.search called', {\n query: parsedQuery,\n resolvePaths,\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 const folderMimeType = 'application/vnd.google-apps.folder';\n let qStr: string;\n\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 qStr = qStr ? `(${qStr}) and mimeType='${folderMimeType}'` : `mimeType='${folderMimeType}'`;\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 q: qStr,\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 (pageToken && pageToken.trim().length > 0) {\n listOptions.pageToken = pageToken;\n }\n\n const response = await drive.files.list(listOptions);\n\n const res = response.data as DriveFolderResponse;\n const folders = Array.isArray(res?.files) ? res.files : [];\n\n const parentIds = new Set<string>();\n for (const f of folders) {\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 // Cache for folder names to reduce API calls during path resolution\n const folderCache = new Map<string, string>();\n\n const items: (DriveFile & { path?: string })[] = await Promise.all(\n folders.map(async (f: DriveFolder) => {\n const id = f?.id ? String(f.id) : 'unknown';\n const name = f?.name || id;\n const result: DriveFile & { path?: string } = { 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 // Build parent objects with names\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 !== undefined) result.shared = f.shared;\n if (f?.starred !== undefined) 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 !== undefined) 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 // Resolve path if requested\n if (resolvePaths && id !== 'unknown') {\n result.path = await resolveFolderPath(drive, id, folderCache, logger);\n }\n\n return result;\n })\n );\n\n const filteredItems = items.map((item) => filterFields(item, requestedFields));\n\n logger.info('drive.folder.search returning', {\n query: parsedQuery,\n pageSize,\n resultCount: filteredItems.length,\n resolvePaths,\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, 'path'] as const),\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.folder.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 folders: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'folder-search' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","query","DriveQueryParameterSchema","optional","describe","fields","createFieldsSchema","availableFields","DRIVE_FILE_FIELDS","fieldDescriptions","DRIVE_FILE_FIELD_DESCRIPTIONS","path","commonPatterns","DRIVE_FILE_COMMON_PATTERNS","resourceName","resolvePaths","boolean","createPaginationSchema","defaultPageSize","maxPageSize","provider","shape","createShapeSchema","successObjectsBranchSchema","type","literal","items","array","DriveFileSchema","extend","string","count","number","nextPageToken","successArraysBranchSchema","columns","rows","unknown","outputSchema","union","config","title","description","result","resolveFolderPath","drive","folderId","folderCache","logger","pathParts","currentId","visited","cachedName","response","parents","_e","folderName","e","Set","has","info","add","get","unshift","files","fileId","supportsAllDrives","data","length","name","set","error","join","handler","extra","pageSize","pageToken","parsedQuery","requestedFields","validPageSize","folderMimeType","qStr","q","listOptions","res","folders","parentIds","f","parentId","parentNameMap","parentFetches","filteredItems","message","parseDriveQueryParameter","parseFields","Math","max","min","floor","undefined","driveApi","version","auth","googleAuth","authContext","rawDriveQuery","toDriveQuery","orderBy","corpora","includeItemsFromAllDrives","trim","list","Array","isArray","Map","size","from","map","parentRes","parentName","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":";;;;+BA0WA;;;eAAwBA;;;2BAzWA;qBAKU;sBACgJ;mBAChK;4BACS;8BACE;uBACsJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AARnL,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAWR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,OAAOC,kCAAyB,CAACC,QAAQ,GAAGC,QAAQ,CAAC;IACrDC,QAAQC,IAAAA,0BAAkB,EAAC;QACzBC,iBAAiB,AAAC,qBAAGC,0BAAiB,SAArB;YAAuB;SAAO;QAC/CC,mBAAmB,wCACdC,sCAA6B;YAChCC,MAAM;;QAERC,gBAAgBC,mCAA0B;QAC1CC,cAAc;IAChB;IACAC,cAAchB,MAAC,CAACiB,OAAO,GAAGb,QAAQ,GAAGC,QAAQ,CAAC;GAC3Ca,IAAAA,8BAAsB,EAAC;IACxBC,iBAAiB;IACjBC,aAAa;IACbC,UAAU;AACZ,GAAGC,KAAK;IACRA,OAAOC,IAAAA,yBAAiB;;AAG1B,8CAA8C;AAC9C,IAAMC,6BAA6BxB,MAAC,CAACC,MAAM,CAAC;IAC1CwB,MAAMzB,MAAC,CAAC0B,OAAO,CAAC;IAChBJ,OAAOtB,MAAC,CAAC0B,OAAO,CAAC;IACjBC,OAAO3B,MAAC,CAAC4B,KAAK,CAACC,wBAAe,CAACC,MAAM,CAAC;QAAElB,MAAM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AAEvG,QAAAA;4BAAO;wBAC9B;;;oBACO4B;oBACDqB,UAAUrB,AAAK,YAALA,OAAiB4E,SAAQ5E,MAAMqB,OAAO,GAAG+B,OAAOpD;oBAChEvB,OAAOuB,KAAK,CAAC,6BAA6B;wBAAEA,OAAOqB;oBAAQ;oBAE3D,iFAAiF;oBACjF,MAAM,IAAIwD,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,4BAAmC,OAAR1D,UAAW;wBAC9F2D,OAAOhF,AAAK,YAALA,OAAiB4E,SAAQ5E,MAAMgF,KAAK,GAAGpD;oBAChD;;;;;;;IAEJ;;AAEe,SAASxG;IACtB,OAAO;QACL0E,MAAM;QACN7B,QAAAA;QACAiC,SAAAA;IACF;AACF"}
@@ -199,6 +199,8 @@ function createHTTPServer(config, overrides) {
199
199
  var mcpServer = new _server.McpServer({
200
200
  name: config.name,
201
201
  version: config.version
202
+ }, {
203
+ cacheHints: _server.defaultCacheHints
202
204
  });
203
205
  (0, _server.registerTools)(mcpServer, tools);
204
206
  (0, _server.registerResources)(mcpServer, composed.resources);
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/setup/http.ts"],"sourcesContent":["import { composeMiddleware, connectHttp, McpServer, registerPrompts, registerResources, registerTools } from '@mcp-z/server';\nimport cors from 'cors';\nimport express from 'express';\nimport type { RuntimeOverrides, ServerConfig } from '../types.ts';\nimport { createDefaultRuntime } from './runtime.ts';\n\nexport async function createHTTPServer(config: ServerConfig, overrides?: RuntimeOverrides) {\n const runtime = await createDefaultRuntime(config, overrides);\n const modules = runtime.createDomainModules();\n const layers = runtime.middlewareFactories.map((factory) => factory(runtime.deps));\n const composed = composeMiddleware(modules, layers);\n const logger = runtime.deps.logger;\n const port = config.transport.port;\n if (!port) throw new Error('Port is required for HTTP transport');\n\n const tools = [...composed.tools, ...runtime.deps.oauthAdapters.accountTools];\n const prompts = [...composed.prompts, ...runtime.deps.oauthAdapters.accountPrompts];\n\n // Built per request (HTTP) and per connection (stdio), not shared. The SDK caches the\n // negotiated protocol revision on the McpServer instance - its own docs say a negotiated\n // session never re-routes a method onto the other era - so one shared instance pins itself\n // to whichever revision reaches it first and answers the other with -32601.\n const buildServer = () => {\n const mcpServer = new McpServer({ name: config.name, version: config.version });\n registerTools(mcpServer, tools);\n registerResources(mcpServer, composed.resources);\n registerPrompts(mcpServer, prompts);\n return mcpServer;\n };\n\n const app = express();\n app.use(express.json({ limit: '10mb' }));\n\n // Must mount '/mcp' before any permissive app-level cors(), or that layer answers its\n // preflight first; pass baseUrl's origin/host below or a public deployment 403s itself.\n const publicUrl = config.baseUrl ? new URL(config.baseUrl) : undefined;\n logger.info(`Starting ${config.name} MCP server (http)`);\n const { close, httpServer } = await connectHttp(buildServer, {\n logger,\n app,\n port,\n allowedOrigins: publicUrl ? [publicUrl.origin] : undefined,\n allowedHosts: publicUrl ? [publicUrl.host] : undefined,\n });\n\n // The loopback OAuth callback and the DCR discovery/registration endpoints are\n // meant to be reached from a browser on another origin. Keep cors() for them,\n // scoped to their own routes - never in front of '/mcp'.\n if (runtime.deps.oauthAdapters.loopbackRouter) {\n app.use('/', cors(), runtime.deps.oauthAdapters.loopbackRouter);\n logger.info('Mounted loopback OAuth callback router');\n }\n\n if (runtime.deps.oauthAdapters.dcrRouter) {\n app.use('/', cors(), runtime.deps.oauthAdapters.dcrRouter);\n logger.info('Mounted DCR router with OAuth endpoints');\n }\n\n logger.info('http transport ready');\n\n return {\n httpServer,\n logger,\n close: async () => {\n await close();\n await runtime.close();\n },\n };\n}\n"],"names":["createHTTPServer","config","overrides","runtime","modules","layers","composed","logger","port","tools","prompts","buildServer","app","publicUrl","close","httpServer","createDefaultRuntime","createDomainModules","middlewareFactories","map","factory","deps","composeMiddleware","transport","Error","oauthAdapters","accountTools","accountPrompts","mcpServer","McpServer","name","version","registerTools","registerResources","resources","registerPrompts","express","use","json","limit","baseUrl","URL","undefined","info","connectHttp","allowedOrigins","orig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;oDAAMX,QAAQW,KAAK;;;gDAAnB;;;;;;gCACF;;wBACF;;;;IACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/setup/http.ts"],"sourcesContent":["import { composeMiddleware, connectHttp, defaultCacheHints, McpServer, registerPrompts, registerResources, registerTools } from '@mcp-z/server';\nimport cors from 'cors';\nimport express from 'express';\nimport type { RuntimeOverrides, ServerConfig } from '../types.ts';\nimport { createDefaultRuntime } from './runtime.ts';\n\nexport async function createHTTPServer(config: ServerConfig, overrides?: RuntimeOverrides) {\n const runtime = await createDefaultRuntime(config, overrides);\n const modules = runtime.createDomainModules();\n const layers = runtime.middlewareFactories.map((factory) => factory(runtime.deps));\n const composed = composeMiddleware(modules, layers);\n const logger = runtime.deps.logger;\n const port = config.transport.port;\n if (!port) throw new Error('Port is required for HTTP transport');\n\n const tools = [...composed.tools, ...runtime.deps.oauthAdapters.accountTools];\n const prompts = [...composed.prompts, ...runtime.deps.oauthAdapters.accountPrompts];\n\n // Built per request (HTTP) and per connection (stdio), not shared. The SDK caches the\n // negotiated protocol revision on the McpServer instance - its own docs say a negotiated\n // session never re-routes a method onto the other era - so one shared instance pins itself\n // to whichever revision reaches it first and answers the other with -32601.\n const buildServer = () => {\n const mcpServer = new McpServer({ name: config.name, version: config.version }, { cacheHints: defaultCacheHints });\n registerTools(mcpServer, tools);\n registerResources(mcpServer, composed.resources);\n registerPrompts(mcpServer, prompts);\n return mcpServer;\n };\n\n const app = express();\n app.use(express.json({ limit: '10mb' }));\n\n // Must mount '/mcp' before any permissive app-level cors(), or that layer answers its\n // preflight first; pass baseUrl's origin/host below or a public deployment 403s itself.\n const publicUrl = config.baseUrl ? new URL(config.baseUrl) : undefined;\n logger.info(`Starting ${config.name} MCP server (http)`);\n const { close, httpServer } = await connectHttp(buildServer, {\n logger,\n app,\n port,\n allowedOrigins: publicUrl ? [publicUrl.origin] : undefined,\n allowedHosts: publicUrl ? [publicUrl.host] : undefined,\n });\n\n // The loopback OAuth callback and the DCR discovery/registration endpoints are\n // meant to be reached from a browser on another origin. Keep cors() for them,\n // scoped to their own routes - never in front of '/mcp'.\n if (runtime.deps.oauthAdapters.loopbackRouter) {\n app.use('/', cors(), runtime.deps.oauthAdapters.loopbackRouter);\n logger.info('Mounted loopback OAuth callback router');\n }\n\n if (runtime.deps.oauthAdapters.dcrRouter) {\n app.use('/', cors(), runtime.deps.oauthAdapters.dcrRouter);\n logger.info('Mounted DCR router with OAuth endpoints');\n }\n\n logger.info('http transport ready');\n\n return {\n httpServer,\n logger,\n close: async () => {\n await close();\n await runtime.close();\n },\n };\n}\n"],"names":["createHTTPServer","config","overrides","runtime","modules","layers","composed","logger","port","tools","prompts","buildServer","app","publicUrl","close","httpServer","createDefaultRuntime","createDomainModules","middlewareFactories","map","factory","deps","composeMiddleware","transport","Error","oauthAdapters","accountTools","accountPrompts","mcpServer","McpServer","name","version","cacheHints","defaultCacheHints","registerTools","registerResources","resources","registerPrompts","express","use","json","limit","baseUrl","URL","undefined","info","connectHttp","allowedOrigins","origin","allowedHosts","host","loopbackRouter","cors","dcrRouter"],"mappings":";;;;+BAMsBA;;;eAAAA;;;sBAN0G;2DAC/G;8DACG;yBAEiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE9B,SAAeA,iBAAiBC,MAAoB,EAAEC,SAA4B;;YACjFC,SACAC,SACAC,QACAC,UACAC,QACAC,MAGAC,OACAC,SAMAC,aAQAC,KAKAC,WAEwB,MAAtBC,OAAOC;;;;oBA9BC;;wBAAMC,IAAAA,+BAAoB,EAACf,QAAQC;;;oBAA7CC,UAAU;oBACVC,UAAUD,QAAQc,mBAAmB;oBACrCZ,SAASF,QAAQe,mBAAmB,CAACC,GAAG,C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BACjDK,cAAcpC;gCAAaA,UAAUqC,IAAI;gCAAIN;wBAC/C;;;oBAN8B,OAAA,eAAtB9B,QAAsB,KAAtBA,OAAOC,aAAe,KAAfA;oBAQf,+EAA+E;oBAC/E,8EAA8E;oBAC9E,yDAAyD;oBACzD,IAAIZ,QAAQkB,IAAI,CAACI,aAAa,CAAC0B,cAAc,EAAE;wBAC7CvC,IAAI2B,GAAG,CAAC,KAAKa,IAAAA,aAAI,KAAIjD,QAAQkB,IAAI,CAACI,aAAa,CAAC0B,cAAc;wBAC9D5C,OAAOsC,IAAI,CAAC;oBACd;oBAEA,IAAI1C,QAAQkB,IAAI,CAACI,aAAa,CAAC4B,SAAS,EAAE;wBACxCzC,IAAI2B,GAAG,CAAC,KAAKa,IAAAA,aAAI,KAAIjD,QAAQkB,IAAI,CAACI,aAAa,CAAC4B,SAAS;wBACzD9C,OAAOsC,IAAI,CAAC;oBACd;oBAEAtC,OAAOsC,IAAI,CAAC;oBAEZ;;wBAAO;4BACL9B,YAAAA;4BACAR,QAAAA;4BACAO,OAAO,SAAPA;;;;;gDACE;;oDAAMA;;;gDAAN;gDACA;;oDAAMX,QAAQW,KAAK;;;gDAAnB;;;;;;gCACF;;wBACF;;;;IACF"}
@@ -190,6 +190,8 @@ function createStdioServer(config, overrides) {
190
190
  var mcpServer = new _server.McpServer({
191
191
  name: config.name,
192
192
  version: config.version
193
+ }, {
194
+ cacheHints: _server.defaultCacheHints
193
195
  });
194
196
  (0, _server.registerTools)(mcpServer, tools);
195
197
  (0, _server.registerResources)(mcpServer, composed.resources);
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/setup/stdio.ts"],"sourcesContent":["import { composeMiddleware, connectStdio, McpServer, registerPrompts, registerResources, registerTools } from '@mcp-z/server';\nimport type { RuntimeOverrides, ServerConfig } from '../types.ts';\nimport { createDefaultRuntime } from './runtime.ts';\n\nexport async function createStdioServer(config: ServerConfig, overrides?: RuntimeOverrides) {\n const runtime = await createDefaultRuntime(config, overrides);\n const modules = runtime.createDomainModules();\n const layers = runtime.middlewareFactories.map((factory) => factory(runtime.deps));\n const composed = composeMiddleware(modules, layers);\n const logger = runtime.deps.logger;\n\n const tools = [...composed.tools, ...runtime.deps.oauthAdapters.accountTools];\n const prompts = [...composed.prompts, ...runtime.deps.oauthAdapters.accountPrompts];\n\n // Built per request (HTTP) and per connection (stdio), not shared. The SDK caches the\n // negotiated protocol revision on the McpServer instance - its own docs say a negotiated\n // session never re-routes a method onto the other era - so one shared instance pins itself\n // to whichever revision reaches it first and answers the other with -32601.\n const buildServer = () => {\n const mcpServer = new McpServer({ name: config.name, version: config.version });\n registerTools(mcpServer, tools);\n registerResources(mcpServer, composed.resources);\n registerPrompts(mcpServer, prompts);\n return mcpServer;\n };\n\n logger.info(`Starting ${config.name} MCP server (stdio)`);\n const { close } = await connectStdio(buildServer, { logger });\n logger.info('stdio transport ready');\n\n return {\n logger,\n close: async () => {\n await close();\n await runtime.close();\n },\n };\n}\n"],"names":["createStdioServer","config","overrides","runtime","modules","layers","composed","logger","tools","prompts","buildServer","close","createDefaultRuntime","createDomainModules","middlewareFactories","map","factory","deps","composeMiddleware","oauthAdapters","accountTools","accountPrompts","mcpServer","McpServer","name","version","registerTools","registerResources","resources","registerPrompts","info","connectStdio"],"mappings":";;;;+BAIsBA;;;eAAAA;;;sBAJwF;yBAEzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE9B,SAAeA,kBAAkBC,MAAoB,EAAEC,SAA4B;;YAClFC,SACAC,SACAC,QACAC,UACAC,QAEAC,OACAC,SAMAC,aASEC;;;;oBAtBQ;;wBAAMC,IAAAA,+BAAoB,EAACX,QAAQC;;;oBAA7CC,UAAU;oBACVC,UAAUD,QAAQU,mBAAmB;oBACrCR,SAASF,QAAQW,mBAAmB,CAACC,GAAG,CAAC,SAACC;+BAAYA,QAAQb,QAAQc,IAAI;;oBAC1EX,WAAWY,IAAAA,yBAAiB,EAACd,SAASC;oBACtCE,SAASJ,QAAQc,IAAI,CAACV,MAAM;oBAE5BC,QAAQ,AAAC,qBAAGF,SAASE,KAAK,SAAE,qBAAGL,QAAQc,IAAI,CAACE,aAAa,CAACC,YAAY;oBACtEX,UAAU,AAAC,qBAAGH,SAASG,OAAO,SAAE,qBAAGN,QAAQc,IAAI,CAACE,aAAa,CAACE,cAAc;oBAElF,sFAAsF;oBACtF,yFAAyF;oBACzF,2FAA2F;oBAC3F,4EAA4E;oBACtEX,cAAc;wBAClB,IAAMY,YAAY,IAAIC,iBAAS,CAAC;4BAAEC,MAAMvB,OAAOuB,IAAI;4BAAEC,SAASxB,OAAOwB,OAAO;wBAAC;wBAC7EC,IAAAA,qBAAa,EAACJ,WAAWd;wBACzBmB,IAAAA,yBAAiB,EAACL,WAAWhB,SAASsB,SAAS;wBAC/CC,IAAAA,uBAAe,EAACP,WAAWb;wBAC3B,OAAOa;oBACT;oBAEAf,OAAOuB,IAAI,CAAC,AAAC,YAAuB,OAAZ7B,OAAOuB,IAAI,EAAC;oBAClB;;wBAAMO,IAAAA,oBAAY,EAACrB,aAAa;4BAAEH,QAAAA;wBAAO;;;oBAAnDI,QAAU,cAAVA;oBACRJ,OAAOuB,IAAI,CAAC;oBAEZ;;wBAAO;4BACLvB,QAAAA;4BACAI,OAAO,SAAPA;;;;;gDACE;;oDAAMA;;;gDAAN;gDACA;;oDAAMR,QAAQQ,KAAK;;;gDAAnB;;;;;;gCACF;;wBACF;;;;IACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/setup/stdio.ts"],"sourcesContent":["import { composeMiddleware, connectStdio, defaultCacheHints, McpServer, registerPrompts, registerResources, registerTools } from '@mcp-z/server';\nimport type { RuntimeOverrides, ServerConfig } from '../types.ts';\nimport { createDefaultRuntime } from './runtime.ts';\n\nexport async function createStdioServer(config: ServerConfig, overrides?: RuntimeOverrides) {\n const runtime = await createDefaultRuntime(config, overrides);\n const modules = runtime.createDomainModules();\n const layers = runtime.middlewareFactories.map((factory) => factory(runtime.deps));\n const composed = composeMiddleware(modules, layers);\n const logger = runtime.deps.logger;\n\n const tools = [...composed.tools, ...runtime.deps.oauthAdapters.accountTools];\n const prompts = [...composed.prompts, ...runtime.deps.oauthAdapters.accountPrompts];\n\n // Built per request (HTTP) and per connection (stdio), not shared. The SDK caches the\n // negotiated protocol revision on the McpServer instance - its own docs say a negotiated\n // session never re-routes a method onto the other era - so one shared instance pins itself\n // to whichever revision reaches it first and answers the other with -32601.\n const buildServer = () => {\n const mcpServer = new McpServer({ name: config.name, version: config.version }, { cacheHints: defaultCacheHints });\n registerTools(mcpServer, tools);\n registerResources(mcpServer, composed.resources);\n registerPrompts(mcpServer, prompts);\n return mcpServer;\n };\n\n logger.info(`Starting ${config.name} MCP server (stdio)`);\n const { close } = await connectStdio(buildServer, { logger });\n logger.info('stdio transport ready');\n\n return {\n logger,\n close: async () => {\n await close();\n await runtime.close();\n },\n };\n}\n"],"names":["createStdioServer","config","overrides","runtime","modules","layers","composed","logger","tools","prompts","buildServer","close","createDefaultRuntime","createDomainModules","middlewareFactories","map","factory","deps","composeMiddleware","oauthAdapters","accountTools","accountPrompts","mcpServer","McpServer","name","version","cacheHints","defaultCacheHints","registerTools","registerResources","resources","registerPrompts","info","connectStdio"],"mappings":";;;;+BAIsBA;;;eAAAA;;;sBAJ2G;yBAE5F;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE9B,SAAeA,kBAAkBC,MAAoB,EAAE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ACF;;;;IACF"}
@@ -36,7 +36,8 @@ export default function createResource() {
36
36
  });
37
37
  const resp = await drive.files.get({
38
38
  fileId,
39
- fields: 'id,name,mimeType,size,modifiedTime,owners,webViewLink'
39
+ fields: 'id,name,mimeType,size,modifiedTime,owners,webViewLink',
40
+ supportsAllDrives: true
40
41
  });
41
42
  const data = resp.data;
42
43
  (_logger_debug = logger.debug) === null || _logger_debug === void 0 ? void 0 : _logger_debug.call(logger, {
@@ -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 });\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":["drive","driveApi","ResourceTemplate","googleAuth","createResource","template","list","undefined","config","description","mimeType","handler","uri","variables","extra","fileId","Array","isArray","logger","contents","href","text","JSON","stringify","error","authContext","version","auth","resp","files","get","fields","data","debug","fileName","name","message"],"mappings":"AAAA,SAASA,SAASC,QAAQ,QAAQ,oBAAoB;AAGtD,SAASC,gBAAgB,QAAQ,gBAAgB;AACjD,SAASC,UAAU,QAAQ,2BAA2B;AAEtD,eAAe,SAASC;IACtB,MAAMC,WAAW,IAAIH,iBAAiB,0BAA0B;QAC9DI,MAAMC;IACR;IACA,MAAMC,SAAyB;QAC7BC,aAAa;QACbC,UAAU;IACZ;IAEA,MAAMC,UAAU,OAAOC,KAAUC,WAA8CC;QAC7E,2DAA2D;QAC3D,MAAMC,SAASC,MAAMC,OAAO,CAACJ,UAAUE,MAAM,IAAIF,UAAUE,MAAM,CAAC,EAAE,GAAGF,UAAUE,MAAM;QAEvF,IAAI;gBAwBFG;YAvBA,yCAAyC;YACzC,IAAI,CAACH,UAAU,OAAOA,WAAW,UAAU;gBACzC,OAAO;oBACLI,UAAU;wBACR;4BACEP,KAAKA,IAAIQ,IAAI;4BACbV,UAAU;4BACVW,MAAMC,KAAKC,SAAS,CAAC;gCACnBC,OAAO;4BACT;wBACF;qBACD;gBACH;YACF;YAEA,sDAAsD;YACtD,MAAM,EAAEN,MAAM,EAAEO,WAAW,EAAE,GAAGX;YAChC,MAAMd,QAAQC,SAAS;gBAAEyB,SAAS;gBAAMC,MAAMxB,WAAWsB,YAAYE,IAAI;YAAE;YAC3E,MAAMC,OAAO,MAAM5B,MAAM6B,KAAK,CAACC,GAAG,CAAC;gBACjCf;gBACAgB,QAAQ;YACV;YACA,MAAMC,OAAOJ,KAAKI,IAAI;aACtBd,gBAAAA,OAAOe,KAAK,cAAZf,oCAAAA,mBAAAA,QAAe;gBAAEH;gBAAQmB,QAAQ,EAAEF,iBAAAA,2BAAAA,KAAMG,IAAI;YAAC,GAAG;YACjD,OAAO;gBACLhB,UAAU;oBACR;wBACEP,KAAKA,IAAIQ,IAAI;wBACbV,UAAU;wBACVW,MAAMC,KAAKC,SAAS,CAACS,QAAQ,CAAC;oBAChC;iBACD;YACH;QACF,EAAE,OAAOR,OAAO;gBAEdN;YADA,MAAM,EAAEA,MAAM,EAAE,GAAGJ;aACnBI,iBAAAA,OAAOe,KAAK,cAAZf,qCAAAA,oBAAAA,QAAeM,OAAkC;YACjD,OAAO;gBACLL,UAAU;oBACR;wBACEP,KAAKA,IAAIQ,IAAI;wBACbV,UAAU;wBACVW,MAAMC,KAAKC,SAAS,CAAC;4BAAEC,OAAO,AAACA,MAAgBY,OAAO;wBAAC;oBACzD;iBACD;YACH;QACF;IACF;IAEA,OAAO;QACLD,MAAM;QACN9B;QACAG;QACAG;IACF;AACF"}
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":["drive","driveApi","ResourceTemplate","googleAuth","createResource","template","list","undefined","config","description","mimeType","handler","uri","variables","extra","fileId","Array","isArray","logger","contents","href","text","JSON","stringify","error","authContext","version","auth","resp","files","get","fields","supportsAllDrives","data","debug","fileName","name","message"],"mappings":"AAAA,SAASA,SAASC,QAAQ,QAAQ,oBAAoB;AAGtD,SAASC,gBAAgB,QAAQ,gBAAgB;AACjD,SAASC,UAAU,QAAQ,2BAA2B;AAEtD,eAAe,SAASC;IACtB,MAAMC,WAAW,IAAIH,iBAAiB,0BAA0B;QAC9DI,MAAMC;IACR;IACA,MAAMC,SAAyB;QAC7BC,aAAa;QACbC,UAAU;IACZ;IAEA,MAAMC,UAAU,OAAOC,KAAUC,WAA8CC;Q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ACF;IACF;IAEA,OAAO;QACLD,MAAM;QACN/B;QACAG;QACAG;IACF;AACF"}
@@ -50,7 +50,8 @@ async function handler({ ids }, extra) {
50
50
  fileId: id,
51
51
  requestBody: {
52
52
  trashed: true
53
- }
53
+ },
54
+ supportsAllDrives: true
54
55
  });
55
56
  return id;
56
57
  }));
@@ -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 });\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":["schemas","AuthRequiredBranchSchema","drive","driveApi","ProtocolError","ProtocolErrorCode","z","googleAuth","MAX_BATCH_SIZE","inputSchema","object","ids","array","string","min","max","describe","successBranchSchema","type","literal","operationSummary","totalCount","number","successCount","failureCount","recoverable","boolean","recoverableDays","failures","id","error","optional","outputSchema","discriminatedUnion","config","title","description","result","handler","extra","logger","info","count","length","version","auth","authContext","results","Promise","allSettled","map","files","update","fileId","requestBody","trashed","forEach","index","status","errorMessage","reason","Error","message","String","push","content","text","JSON","stringify","structuredContent","InternalError","stack","undefined","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAErC,SAASE,SAASC,QAAQ,QAAQ,oBAAoB;AACtD,SAA8BC,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACtF,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,UAAU,QAAQ,2BAA2B;AAEtD,MAAMC,iBAAiB;AAEvB,MAAMC,cAAcH,EAAEI,MAAM,CAAC;IAC3BC,KAAKL,EAAEM,KAAK,CAACN,EAAEO,MAAM,GAAGC,GAAG,CAAC,IAAIA,GAAG,CAAC,GAAGC,GAAG,CAACP,gBAAgBQ,QAAQ,CAAC;AACtE;AAEA,wBAAwB;AACxB,MAAMC,sBAAsBX,EAAEI,MAAM,CAAC;IACnCQ,MAAMZ,EAAEa,OAAO,CAAC;IAChBC,kBAAkBd,EAAEO,MAAM,GAAGG,QAAQ,CAAC;IACtCK,YAAYf,EAAEgB,MAAM,GAAGN,QAAQ,CAAC;IAChCO,cAAcjB,EAAEgB,MAAM,GAAGN,QAAQ,CAAC;IAClCQ,cAAclB,EAAEgB,MAAM,GAAGN,QAAQ,CAAC;IAClCS,aAAanB,EAAEoB,OAAO,GAAGV,QAAQ,CAAC;IAClCW,iBAAiBrB,EAAEgB,MAAM,GAAGN,QAAQ,CAAC;IACrCY,UAAUtB,EACPM,KAAK,CACJN,EAAEI,MAAM,CAAC;QACPmB,IAAIvB,EAAEO,MAAM,GAAGG,QAAQ,CAAC;QACxBc,OAAOxB,EAAEO,MAAM,GAAGG,QAA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AIgC,MAAM;QAE7BH,OAAOC,IAAI,CAAC,oCAAoC;YAC9CpB;YACAE;YACAC;QACF;QAEA,MAAMJ,mBAAmBI,iBAAiB,IAAI,CAAC,MAAM,EAAED,aAAa,KAAK,EAAEA,iBAAiB,IAAI,KAAK,IAAI,mCAAmC,CAAC,GAAG,CAAC,MAAM,EAAEA,aAAa,IAAI,EAAEF,WAAW,KAAK,EAAEA,eAAe,IAAI,KAAK,IAAI,WAAW,EAAEG,aAAa,iCAAiC,CAAC;QAEtR,MAAMa,SAAiB;YACrBnB,MAAM;YACNE;YACAC;YACAE;YACAC;YACAC,aAAa;YACbE,iBAAiB;YACjB,GAAIC,SAASe,MAAM,GAAG,KAAK;gBAAEf;YAAS,CAAC;QACzC;QAEA,OAAO;YACLqC,SAAS;gBACP;oBACE/C,MAAM;oBACNgD,MAAMC,KAAKC,SAAS,CAAC/B;gBACvB;aACD;YACDgC,mBAAmB;gBAAEhC;YAAO;QAC9B;IACF,EAAE,OAAOP,OAAO;QACd,MAAMgC,UAAUhC,iBAAiB+B,QAAQ/B,MAAMgC,OAAO,GAAGC,OAAOjC;QAChEU,OAAOV,KAAK,CAAC,gCAAgC;YAAEA,OAAOgC;QAAQ;QAE9D,sBAAsB;QACtB,MAAM,IAAI1D,cAAcC,kBAAkBiE,aAAa,EAAE,CAAC,6BAA6B,EAAER,SAAS,EAAE;YAClGS,OAAOzC,iBAAiB+B,QAAQ/B,MAAMyC,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QACLC,MAAM;QACNxC;QACAI;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/tools/file-move-to-trash.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { 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":["schemas","AuthRequiredBranchSchema","drive","driveApi","ProtocolError","ProtocolErrorCode","z","googleAuth","MAX_BATCH_SIZE","inputSchema","object","ids","array","string","min","max","describe","successBranchSchema","type","literal","operationSummary","totalCount","number","successCount","failureCount","recoverable","boolean","recoverableDays","failures","id","error","optional","outputSchema","discriminatedUnion","config","title","description","result","handler","extra","logger","info","count","length","version","auth","authContext","results","Promise","allSettled","map","files","update","fileId","requestBody","trashed","supportsAllDrives","forEach","index","status","errorMessage","reason","Error","message","String","push","content","text","JSON","stringify","structuredContent","InternalError","stack","undefined","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAErC,SAASE,SAASC,QAAQ,QAAQ,oBAAoB;AACtD,SAA8BC,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AAC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ASe,MAAM,GAAG,KAAK;gBAAEf;YAAS,CAAC;QACzC;QAEA,OAAO;YACLsC,SAAS;gBACP;oBACEhD,MAAM;oBACNiD,MAAMC,KAAKC,SAAS,CAAChC;gBACvB;aACD;YACDiC,mBAAmB;gBAAEjC;YAAO;QAC9B;IACF,EAAE,OAAOP,OAAO;QACd,MAAMiC,UAAUjC,iBAAiBgC,QAAQhC,MAAMiC,OAAO,GAAGC,OAAOlC;QAChEU,OAAOV,KAAK,CAAC,gCAAgC;YAAEA,OAAOiC;QAAQ;QAE9D,sBAAsB;QACtB,MAAM,IAAI3D,cAAcC,kBAAkBkE,aAAa,EAAE,CAAC,6BAA6B,EAAER,SAAS,EAAE;YAClGS,OAAO1C,iBAAiBgC,QAAQhC,MAAM0C,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QACLC,MAAM;QACNzC;QACAI;IACF;AACF"}
@@ -54,7 +54,8 @@ const config = {
54
54
  // Get current file metadata to get old parents
55
55
  const fileMetadata = await drive.files.get({
56
56
  fileId: fileId,
57
- fields: 'id,name,parents,webViewLink'
57
+ fields: 'id,name,parents,webViewLink',
58
+ supportsAllDrives: true
58
59
  });
59
60
  const oldParents = fileMetadata.data.parents || [];
60
61
  const fileName = fileMetadata.data.name || fileId;
@@ -64,7 +65,8 @@ const config = {
64
65
  fileId: fileId,
65
66
  addParents: destinationFolderId,
66
67
  removeParents: oldParents.join(','),
67
- fields: 'id,name,parents,webViewLink'
68
+ fields: 'id,name,parents,webViewLink',
69
+ supportsAllDrives: true
68
70
  });
69
71
  const result = {
70
72
  fileId: fileId,
@@ -108,7 +110,8 @@ const config = {
108
110
  try {
109
111
  const response = await drive.files.get({
110
112
  fileId: fileId,
111
- fields: 'id,name,parents,webViewLink'
113
+ fields: 'id,name,parents,webViewLink',
114
+ supportsAllDrives: true
112
115
  });
113
116
  const webViewLink = response.data.webViewLink;
114
117
  return {
@@ -152,7 +155,8 @@ const config = {
152
155
  fileId: file.fileId,
153
156
  addParents: destinationFolderId,
154
157
  removeParents: file.parents.join(','),
155
- fields: 'id'
158
+ fields: 'id',
159
+ supportsAllDrives: true
156
160
  });
157
161
  return {
158
162
  fileId: file.fileId,