@mcp-z/mcp-drive 1.1.3 → 2.1.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 (93) hide show
  1. package/dist/cjs/index.js.map +1 -1
  2. package/dist/cjs/lib/google-auth.d.cts +9 -0
  3. package/dist/cjs/lib/google-auth.d.ts +9 -0
  4. package/dist/cjs/lib/google-auth.js +16 -0
  5. package/dist/cjs/lib/google-auth.js.map +1 -0
  6. package/dist/cjs/mcp/prompts/query-syntax.d.cts +2 -3
  7. package/dist/cjs/mcp/prompts/query-syntax.d.ts +2 -3
  8. package/dist/cjs/mcp/prompts/query-syntax.js.map +1 -1
  9. package/dist/cjs/mcp/resources/file.d.cts +2 -9
  10. package/dist/cjs/mcp/resources/file.d.ts +2 -9
  11. package/dist/cjs/mcp/resources/file.js +4 -3
  12. package/dist/cjs/mcp/resources/file.js.map +1 -1
  13. package/dist/cjs/mcp/tools/file-move-to-trash.d.cts +1 -1
  14. package/dist/cjs/mcp/tools/file-move-to-trash.d.ts +1 -1
  15. package/dist/cjs/mcp/tools/file-move-to-trash.js +5 -4
  16. package/dist/cjs/mcp/tools/file-move-to-trash.js.map +1 -1
  17. package/dist/cjs/mcp/tools/file-move.d.cts +1 -1
  18. package/dist/cjs/mcp/tools/file-move.d.ts +1 -1
  19. package/dist/cjs/mcp/tools/file-move.js +5 -4
  20. package/dist/cjs/mcp/tools/file-move.js.map +1 -1
  21. package/dist/cjs/mcp/tools/file-upload.d.cts +1 -1
  22. package/dist/cjs/mcp/tools/file-upload.d.ts +1 -1
  23. package/dist/cjs/mcp/tools/file-upload.js +5 -4
  24. package/dist/cjs/mcp/tools/file-upload.js.map +1 -1
  25. package/dist/cjs/mcp/tools/files-search.d.cts +1 -1
  26. package/dist/cjs/mcp/tools/files-search.d.ts +1 -1
  27. package/dist/cjs/mcp/tools/files-search.js +4 -4
  28. package/dist/cjs/mcp/tools/files-search.js.map +1 -1
  29. package/dist/cjs/mcp/tools/folder-contents.d.cts +1 -1
  30. package/dist/cjs/mcp/tools/folder-contents.d.ts +1 -1
  31. package/dist/cjs/mcp/tools/folder-contents.js +4 -4
  32. package/dist/cjs/mcp/tools/folder-contents.js.map +1 -1
  33. package/dist/cjs/mcp/tools/folder-create.d.cts +1 -1
  34. package/dist/cjs/mcp/tools/folder-create.d.ts +1 -1
  35. package/dist/cjs/mcp/tools/folder-create.js +5 -4
  36. package/dist/cjs/mcp/tools/folder-create.js.map +1 -1
  37. package/dist/cjs/mcp/tools/folder-path.d.cts +1 -1
  38. package/dist/cjs/mcp/tools/folder-path.d.ts +1 -1
  39. package/dist/cjs/mcp/tools/folder-path.js +5 -4
  40. package/dist/cjs/mcp/tools/folder-path.js.map +1 -1
  41. package/dist/cjs/mcp/tools/folder-search.d.cts +1 -1
  42. package/dist/cjs/mcp/tools/folder-search.d.ts +1 -1
  43. package/dist/cjs/mcp/tools/folder-search.js +4 -4
  44. package/dist/cjs/mcp/tools/folder-search.js.map +1 -1
  45. package/dist/cjs/setup/http.d.cts +1 -1
  46. package/dist/cjs/setup/http.d.ts +1 -1
  47. package/dist/cjs/setup/http.js +1 -2
  48. package/dist/cjs/setup/http.js.map +1 -1
  49. package/dist/cjs/setup/stdio.d.cts +1 -1
  50. package/dist/cjs/setup/stdio.d.ts +1 -1
  51. package/dist/cjs/setup/stdio.js +1 -2
  52. package/dist/cjs/setup/stdio.js.map +1 -1
  53. package/dist/esm/index.js +1 -1
  54. package/dist/esm/index.js.map +1 -1
  55. package/dist/esm/lib/google-auth.d.ts +9 -0
  56. package/dist/esm/lib/google-auth.js +11 -0
  57. package/dist/esm/lib/google-auth.js.map +1 -0
  58. package/dist/esm/mcp/prompts/query-syntax.d.ts +2 -3
  59. package/dist/esm/mcp/prompts/query-syntax.js.map +1 -1
  60. package/dist/esm/mcp/resources/file.d.ts +2 -9
  61. package/dist/esm/mcp/resources/file.js +3 -2
  62. package/dist/esm/mcp/resources/file.js.map +1 -1
  63. package/dist/esm/mcp/tools/file-move-to-trash.d.ts +1 -1
  64. package/dist/esm/mcp/tools/file-move-to-trash.js +5 -4
  65. package/dist/esm/mcp/tools/file-move-to-trash.js.map +1 -1
  66. package/dist/esm/mcp/tools/file-move.d.ts +1 -1
  67. package/dist/esm/mcp/tools/file-move.js +5 -4
  68. package/dist/esm/mcp/tools/file-move.js.map +1 -1
  69. package/dist/esm/mcp/tools/file-upload.d.ts +1 -1
  70. package/dist/esm/mcp/tools/file-upload.js +5 -4
  71. package/dist/esm/mcp/tools/file-upload.js.map +1 -1
  72. package/dist/esm/mcp/tools/files-search.d.ts +1 -1
  73. package/dist/esm/mcp/tools/files-search.js +5 -5
  74. package/dist/esm/mcp/tools/files-search.js.map +1 -1
  75. package/dist/esm/mcp/tools/folder-contents.d.ts +1 -1
  76. package/dist/esm/mcp/tools/folder-contents.js +5 -5
  77. package/dist/esm/mcp/tools/folder-contents.js.map +1 -1
  78. package/dist/esm/mcp/tools/folder-create.d.ts +1 -1
  79. package/dist/esm/mcp/tools/folder-create.js +5 -4
  80. package/dist/esm/mcp/tools/folder-create.js.map +1 -1
  81. package/dist/esm/mcp/tools/folder-path.d.ts +1 -1
  82. package/dist/esm/mcp/tools/folder-path.js +5 -4
  83. package/dist/esm/mcp/tools/folder-path.js.map +1 -1
  84. package/dist/esm/mcp/tools/folder-search.d.ts +1 -1
  85. package/dist/esm/mcp/tools/folder-search.js +5 -5
  86. package/dist/esm/mcp/tools/folder-search.js.map +1 -1
  87. package/dist/esm/setup/http.d.ts +1 -1
  88. package/dist/esm/setup/http.js +1 -2
  89. package/dist/esm/setup/http.js.map +1 -1
  90. package/dist/esm/setup/stdio.d.ts +1 -1
  91. package/dist/esm/setup/stdio.js +1 -2
  92. package/dist/esm/setup/stdio.js.map +1 -1
  93. package/package.json +8 -8
@@ -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 { createFieldsSchema, createPaginationSchema, createShapeSchema, filterFields, parseFields, toColumnarFormat } from '@mcp-z/server';\nimport { type CallToolResult, ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport type { drive_v3 } from 'googleapis';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { 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 = google.drive({ version: 'v3', auth: 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 McpError for all errors so callers can see Drive validation details\n throw new McpError(ErrorCode.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","google","version","auth","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","McpError","ErrorCode","InternalError","stack"],"mappings":";;;;+BA+VA;;;eAAwBA;;;2BA9VA;sBAImG;qBAClE;0BAElC;mBACL;8BACW;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;Y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AAAA,wBAAgB,EAAC/C,eAAeb,iBAAiB,AAAC,qBAAGrE,0BAAiB;wBAAE;;wBAC3EuB,OAAO2D,cAAcvB,MAAM;wBACvBlC,iBAAiB;wBAAEA,eAAAA;oBAAc,KAEvC;wBACET,MAAM;wBACNH,OAAO;wBACPK,OAAOgE;wBACP3D,OAAO2D,cAAcvB,MAAM;uBACvBlC,iBAAiB;wBAAEA,eAAAA;oBAAc;oBAG7C;;wBAAO;4BACLyG,OAAO;gCACL;oCACElH,MAAM;oCACNmH,MAAMC,KAAKC,SAAS,CAAClG;gCACvB;;4BAEFmG,mBAAmB;gCAAEnG,QAAAA;4BAAO;wBAC9B;;;oBACO2B;oBACDqB,UAAUrB,AAAK,YAALA,OAAiByE,SAAQzE,MAAMqB,OAAO,GAAG4B,OAAOjD;oBAChEtB,OAAOsB,KAAK,CAAC,6BAA6B;wBAAEA,OAAOqB;oBAAQ;oBAE3D,4EAA4E;oBAC5E,MAAM,IAAIqD,eAAQ,CAACC,gBAAS,CAACC,aAAa,EAAE,AAAC,4BAAmC,OAARvD,UAAW;wBACjFwD,OAAO7E,AAAK,YAALA,OAAiByE,SAAQzE,MAAM6E,KAAK,GAAGjD;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 CallToolResult, createFieldsSchema, createPaginationSchema, createShapeSchema, filterFields, ProtocolError, ProtocolErrorCode, parseFields, toColumnarFormat } from '@mcp-z/server';\nimport type { drive_v3 } from 'googleapis';\nimport { google } from 'googleapis';\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 = google.drive({ 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","google","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;sBAI0J;0BAE3J;mBACL;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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M;uBACvBlC,iBAAiB;wBAAEA,eAAAA;oBAAc;oBAG7C;;wBAAO;4BACL0G,OAAO;gCACL;oCACEnH,MAAM;oCACNoH,MAAMC,KAAKC,SAAS,CAACnG;gCACvB;;4BAEFoG,mBAAmB;gCAAEpG,QAAAA;4BAAO;wBAC9B;;;oBACO2B;oBACDqB,UAAUrB,AAAK,YAALA,OAAiB0E,SAAQ1E,MAAMqB,OAAO,GAAG6B,OAAOlD;oBAChEtB,OAAOsB,KAAK,CAAC,6BAA6B;wBAAEA,OAAOqB;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,4 +1,4 @@
1
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
1
+ import { McpServer } from '@mcp-z/server';
2
2
  import type { RuntimeOverrides, ServerConfig } from '../types.js';
3
3
  export declare function createHTTPServer(config: ServerConfig, overrides?: RuntimeOverrides): Promise<{
4
4
  httpServer: import("node:http").Server<typeof import("node:http").IncomingMessage, typeof import("node:http").ServerResponse>;
@@ -1,4 +1,4 @@
1
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
1
+ import { McpServer } from '@mcp-z/server';
2
2
  import type { RuntimeOverrides, ServerConfig } from '../types.js';
3
3
  export declare function createHTTPServer(config: ServerConfig, overrides?: RuntimeOverrides): Promise<{
4
4
  httpServer: import("node:http").Server<typeof import("node:http").IncomingMessage, typeof import("node:http").ServerResponse>;
@@ -9,7 +9,6 @@ Object.defineProperty(exports, "createHTTPServer", {
9
9
  }
10
10
  });
11
11
  var _server = require("@mcp-z/server");
12
- var _mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
13
12
  var _cors = /*#__PURE__*/ _interop_require_default(require("cors"));
14
13
  var _express = /*#__PURE__*/ _interop_require_default(require("express"));
15
14
  var _runtimets = require("./runtime.js");
@@ -192,7 +191,7 @@ function createHTTPServer(config, overrides) {
192
191
  if (!port) throw new Error('Port is required for HTTP transport');
193
192
  tools = _to_consumable_array(composed.tools).concat(_to_consumable_array(runtime.deps.oauthAdapters.accountTools));
194
193
  prompts = _to_consumable_array(composed.prompts).concat(_to_consumable_array(runtime.deps.oauthAdapters.accountPrompts));
195
- mcpServer = new _mcp.McpServer({
194
+ mcpServer = new _server.McpServer({
196
195
  name: config.name,
197
196
  version: config.version
198
197
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/setup/http.ts"],"sourcesContent":["import { composeMiddleware, connectHttp, registerPrompts, registerResources, registerTools } from '@mcp-z/server';\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\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 const mcpServer = new McpServer({ name: config.name, version: config.version });\n registerTools(mcpServer, tools);\n registerResources(mcpServer, composed.resources);\n registerPrompts(mcpServer, prompts);\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(mcpServer, {\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 mcpServer,\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","mcpServer","app","publicUrl","close","httpServer","createDefaultRuntime","createDomainModules","middlewareFactories","map","factory","deps","composeMiddleware","transport","Error","oauthAdapters","accountTools","accountPrompts","McpServer","name","version","registerTools","registerResources","resources","registerPrompts","express","use","json","limit","baseUrl","URL","undefined","info","connectHttp","allowedOrigins","origin","allowedHosts","host","loopbackRouter","cors","dcrRouter"],"mappings":";;;;+BAOsBA;;;eAAAA;;;sBAP4E;mBACxE;2DACT;8DACG;yBAEiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE9B,SAAeA,iBAAiBC,MAAoB,EAAEC,SAA4B;;YACjFC,SACAC,SACAC,Q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;4BACAJ,MAAAA;4BACAoC,gBAAgB/B;gCAAaA,UAAUgC,MAAM;gCAAIJ;4BACjDK,cAAcjC;gCAAaA,UAAUkC,IAAI;gCAAIN;wBAC/C;;;oBAN8B,OAAA,eAAtB3B,QAAsB,KAAtBA,OAAOC,aAAe,KAAfA;oBAQf,+EAA+E;oBAC/E,8EAA8E;oBAC9E,yDAAyD;oBACzD,IAAIZ,QAAQkB,IAAI,CAACI,aAAa,CAACuB,cAAc,EAAE;wBAC7CpC,IAAIwB,GAAG,CAAC,KAAKa,IAAAA,aAAI,KAAI9C,QAAQkB,IAAI,CAACI,aAAa,CAACuB,cAAc;wBAC9DzC,OAAOmC,IAAI,CAAC;oBACd;oBAEA,IAAIvC,QAAQkB,IAAI,CAACI,aAAa,CAACyB,SAAS,EAAE;wBACxCtC,IAAIwB,GAAG,CAAC,KAAKa,IAAAA,aAAI,KAAI9C,QAAQkB,IAAI,CAACI,aAAa,CAACyB,SAAS;wBACzD3C,OAAOmC,IAAI,CAAC;oBACd;oBAEAnC,OAAOmC,IAAI,CAAC;oBAEZ;;wBAAO;4BACL3B,YAAAA;4BACAJ,WAAAA;4BACAJ,QAAAA;4BACAO,OAAO,SAAPA;;;;;gDACE;;oDAAMA;;;gDAAN;gDACA;;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, 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 const mcpServer = new McpServer({ name: config.name, version: config.version });\n registerTools(mcpServer, tools);\n registerResources(mcpServer, composed.resources);\n registerPrompts(mcpServer, prompts);\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(mcpServer, {\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 mcpServer,\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","mcpServer","app","publicUrl","close","httpServer","createDefaultRuntime","createDomainModules","middlewareFactories","map","factory","deps","composeMiddleware","transport","Error","oauthAdapters","accountTools","accountPrompts","McpServer","name","version","registerTools","registerResources","resources","registerPrompts","express","use","json","limit","baseUrl","URL","undefined","info","connectHttp","allowedOrigins","origin","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'@modelcontextprotocol/sdk/server/mcp.js';
1
+ import { McpServer } from '@mcp-z/server';
2
2
  import type { RuntimeOverrides, ServerConfig } from '../types.js';
3
3
  export declare function createStdioServer(config: ServerConfig, overrides?: RuntimeOverrides): Promise<{
4
4
  mcpServer: McpServer;
@@ -1,4 +1,4 @@
1
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
1
+ import { McpServer } from '@mcp-z/server';
2
2
  import type { RuntimeOverrides, ServerConfig } from '../types.js';
3
3
  export declare function createStdioServer(config: ServerConfig, overrides?: RuntimeOverrides): Promise<{
4
4
  mcpServer: McpServer;
@@ -9,7 +9,6 @@ Object.defineProperty(exports, "createStdioServer", {
9
9
  }
10
10
  });
11
11
  var _server = require("@mcp-z/server");
12
- var _mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
13
12
  var _runtimets = require("./runtime.js");
14
13
  function _array_like_to_array(arr, len) {
15
14
  if (len == null || len > arr.length) len = arr.length;
@@ -183,7 +182,7 @@ function createStdioServer(config, overrides) {
183
182
  logger = runtime.deps.logger;
184
183
  tools = _to_consumable_array(composed.tools).concat(_to_consumable_array(runtime.deps.oauthAdapters.accountTools));
185
184
  prompts = _to_consumable_array(composed.prompts).concat(_to_consumable_array(runtime.deps.oauthAdapters.accountPrompts));
186
- mcpServer = new _mcp.McpServer({
185
+ mcpServer = new _server.McpServer({
187
186
  name: config.name,
188
187
  version: config.version
189
188
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/setup/stdio.ts"],"sourcesContent":["import { composeMiddleware, connectStdio, registerPrompts, registerResources, registerTools } from '@mcp-z/server';\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\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 const mcpServer = new McpServer({ name: config.name, version: config.version });\n registerTools(mcpServer, tools);\n registerResources(mcpServer, composed.resources);\n registerPrompts(mcpServer, prompts);\n\n logger.info(`Starting ${config.name} MCP server (stdio)`);\n const { close } = await connectStdio(mcpServer, { logger });\n logger.info('stdio transport ready');\n\n return {\n mcpServer,\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","mcpServer","close","createDefaultRuntime","createDomainModules","middlewareFactories","map","factory","deps","composeMiddleware","oauthAdapters","accountTools","accountPrompts","McpServer","name","version","registerTools","registerResources","resources","registerPrompts","info","connectStdio"],"mappings":";;;;+BAKsBA;;;eAAAA;;;sBAL6E;mBACzE;yBAEW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE9B,SAAeA,kBAAkBC,MAAoB,EAAEC,SAA4B;;YAClFC,SACAC,SACAC,QACAC,UACAC,QAEAC,OACAC,SAEAC,WAMEC;;;;oBAfQ;;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;oBAE5EX,YAAY,IAAIY,cAAS,CAAC;wBAAEC,MAAMtB,OAAOsB,IAAI;wBAAEC,SAASvB,OAAOuB,OAAO;oBAAC;oBAC7EC,IAAAA,qBAAa,EAACf,WAAWF;oBACzBkB,IAAAA,yBAAiB,EAAChB,WAAWJ,SAASqB,SAAS;oBAC/CC,IAAAA,uBAAe,EAAClB,WAAWD;oBAE3BF,OAAOsB,IAAI,CAAC,AAAC,YAAuB,OAAZ5B,OAAOsB,IAAI,EAAC;oBAClB;;wBAAMO,IAAAA,oBAAY,EAACpB,WAAW;4BAAEH,QAAAA;wBAAO;;;oBAAjDI,QAAU,cAAVA;oBACRJ,OAAOsB,IAAI,CAAC;oBAEZ;;wBAAO;4BACLnB,WAAAA;4BACAH,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, 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 const mcpServer = new McpServer({ name: config.name, version: config.version });\n registerTools(mcpServer, tools);\n registerResources(mcpServer, composed.resources);\n registerPrompts(mcpServer, prompts);\n\n logger.info(`Starting ${config.name} MCP server (stdio)`);\n const { close } = await connectStdio(mcpServer, { logger });\n logger.info('stdio transport ready');\n\n return {\n mcpServer,\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","mcpServer","close","createDefaultRuntime","createDomainModules","middlewareFactories","map","factory","deps","composeMiddleware","oauthAdapters","accountTools","accountPrompts","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,SAEAC,WAMEC;;;;oBAfQ;;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;oBAE5EX,YAAY,IAAIY,iBAAS,CAAC;wBAAEC,MAAMtB,OAAOsB,IAAI;wBAAEC,SAASvB,OAAOuB,OAAO;oBAAC;oBAC7EC,IAAAA,qBAAa,EAACf,WAAWF;oBACzBkB,IAAAA,yBAAiB,EAAChB,WAAWJ,SAASqB,SAAS;oBAC/CC,IAAAA,uBAAe,EAAClB,WAAWD;oBAE3BF,OAAOsB,IAAI,CAAC,AAAC,YAAuB,OAAZ5B,OAAOsB,IAAI,EAAC;oBAClB;;wBAAMO,IAAAA,oBAAY,EAACpB,WAAW;4BAAEH,QAAAA;wBAAO;;;oBAAjDI,QAAU,cAAVA;oBACRJ,OAAOsB,IAAI,CAAC;oBAEZ;;wBAAO;4BACLnB,WAAAA;4BACAH,QAAAA;4BACAI,OAAO,SAAPA;;;;;gDACE;;oDAAMA;;;gDAAN;gDACA;;oDAAMR,QAAQQ,KAAK;;;gDAAnB;;;;;;gCACF;;wBACF;;;;IACF"}
package/dist/esm/index.js CHANGED
@@ -8,7 +8,7 @@ import * as _setup from './setup/index.js';
8
8
  export { _setup as setup };
9
9
  export * from './types.js';
10
10
  export async function startServer(config) {
11
- // createHTTPServer/createStdioServer pull in @modelcontextprotocol/sdk and every mcp/tools/*.ts
11
+ // createHTTPServer/createStdioServer pull in @mcp-z/server and every mcp/tools/*.ts
12
12
  // (googleapis included); deferred so a --version/--help run never reaches them.
13
13
  const { createHTTPServer } = await import('./setup/http.js');
14
14
  const { createStdioServer } = await import('./setup/stdio.js');
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/index.ts"],"sourcesContent":["import { handleVersionHelp } from './setup/version-help.ts';\nimport type { ServerConfig } from './types.ts';\n\nexport { GOOGLE_SCOPE } from './constants.ts';\nexport * as mcp from './mcp/index.ts';\nexport * as schemas from './schemas/index.ts';\nexport * as setup from './setup/index.ts';\nexport * from './types.ts';\n\nexport async function startServer(config: ServerConfig): Promise<void> {\n // createHTTPServer/createStdioServer pull in @modelcontextprotocol/sdk and every mcp/tools/*.ts\n // (googleapis included); deferred so a --version/--help run never reaches them.\n const { createHTTPServer } = await import('./setup/http.ts');\n const { createStdioServer } = await import('./setup/stdio.ts');\n const { logger, close } = config.transport.type === 'stdio' ? await createStdioServer(config) : await createHTTPServer(config);\n\n process.on('SIGINT', async () => {\n await close();\n process.exit(0);\n });\n\n logger.info(`Server started with ${config.transport.type} transport`);\n await new Promise(() => {});\n}\n\nexport default async function main(): Promise<void> {\n // Check for help/version flags FIRST, before config parsing\n const versionHelpResult = handleVersionHelp(process.argv);\n if (versionHelpResult.handled) {\n console.log(versionHelpResult.output);\n process.exit(0);\n }\n\n // Only parse config if no help/version flags. config.ts's own heavy imports (@mcp-z/oauth-google,\n // @mcp-z/server) are deferred internally, so this static-looking call stays cheap until here.\n const { createConfig } = await import('./setup/config.ts');\n const config = createConfig();\n await startServer(config);\n}\n\nif (process.argv[1] === new URL(import.meta.url).pathname) {\n main();\n}\n"],"names":["handleVersionHelp","GOOGLE_SCOPE","mcp","schemas","setup","startServer","config","createHTTPServer","createStdioServer","logger","close","transport","type","process","on","exit","info","Promise","main","versionHelpResult","argv","handled","console","log","output","createConfig","URL","url","pathname"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,0BAA0B;AAG5D,SAASC,YAAY,QAAQ,iBAAiB;AAC9C,sBAAqB,iBAAiB;AAAtC,SAAO,QAAKC,GAAG,GAAuB;AACtC,0BAAyB,qBAAqB;AAA9C,SAAO,YAAKC,OAAO,GAA2B;AAC9C,wBAAuB,mBAAmB;AAA1C,SAAO,UAAKC,KAAK,GAAyB;AAC1C,cAAc,aAAa;AAE3B,OAAO,eAAeC,YAAYC,MAAoB;IACpD,gGAAgG;IAChG,gFAAgF;IAChF,MAAM,EAAEC,gBAAgB,EAAE,GAAG,MAAM,MAAM,CAAC;IAC1C,MAAM,EAAEC,iBAAiB,EAAE,GAAG,MAAM,MAAM,CAAC;IAC3C,MAAM,EAAEC,MAAM,EAAEC,KAAK,EAAE,GAAGJ,OAAOK,SAAS,CAACC,IAAI,KAAK,UAAU,MAAMJ,kBAAkBF,UAAU,MAAMC,iBAAiBD;IAEvHO,QAAQC,EAAE,CAAC,UAAU;QACnB,MAAMJ;QACNG,QAAQE,IAAI,CAAC;IACf;IAEAN,OAAOO,IAAI,CAAC,CAAC,oBAAoB,EAAEV,OAAOK,SAAS,CAACC,IAAI,CAAC,UAAU,CAAC;IACpE,MAAM,IAAIK,QAAQ,KAAO;AAC3B;AAEA,eAAe,eAAeC;IAC5B,4DAA4D;IAC5D,MAAMC,oBAAoBnB,kBAAkBa,QAAQO,IAAI;IACxD,IAAID,kBAAkBE,OAAO,EAAE;QAC7BC,QAAQC,GAAG,CAACJ,kBAAkBK,MAAM;QACpCX,QAAQE,IAAI,CAAC;IACf;IAEA,kGAAkG;IAClG,8FAA8F;IAC9F,MAAM,EAAEU,YAAY,EAAE,GAAG,MAAM,MAAM,CAAC;IACtC,MAAMnB,SAASmB;IACf,MAAMpB,YAAYC;AACpB;AAEA,IAAIO,QAAQO,IAAI,CAAC,EAAE,KAAK,IAAIM,IAAI,YAAYC,GAAG,EAAEC,QAAQ,EAAE;IACzDV;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/index.ts"],"sourcesContent":["import { handleVersionHelp } from './setup/version-help.ts';\nimport type { ServerConfig } from './types.ts';\n\nexport { GOOGLE_SCOPE } from './constants.ts';\nexport * as mcp from './mcp/index.ts';\nexport * as schemas from './schemas/index.ts';\nexport * as setup from './setup/index.ts';\nexport * from './types.ts';\n\nexport async function startServer(config: ServerConfig): Promise<void> {\n // createHTTPServer/createStdioServer pull in @mcp-z/server and every mcp/tools/*.ts\n // (googleapis included); deferred so a --version/--help run never reaches them.\n const { createHTTPServer } = await import('./setup/http.ts');\n const { createStdioServer } = await import('./setup/stdio.ts');\n const { logger, close } = config.transport.type === 'stdio' ? await createStdioServer(config) : await createHTTPServer(config);\n\n process.on('SIGINT', async () => {\n await close();\n process.exit(0);\n });\n\n logger.info(`Server started with ${config.transport.type} transport`);\n await new Promise(() => {});\n}\n\nexport default async function main(): Promise<void> {\n // Check for help/version flags FIRST, before config parsing\n const versionHelpResult = handleVersionHelp(process.argv);\n if (versionHelpResult.handled) {\n console.log(versionHelpResult.output);\n process.exit(0);\n }\n\n // Only parse config if no help/version flags. config.ts's own heavy imports (@mcp-z/oauth-google,\n // @mcp-z/server) are deferred internally, so this static-looking call stays cheap until here.\n const { createConfig } = await import('./setup/config.ts');\n const config = createConfig();\n await startServer(config);\n}\n\nif (process.argv[1] === new URL(import.meta.url).pathname) {\n main();\n}\n"],"names":["handleVersionHelp","GOOGLE_SCOPE","mcp","schemas","setup","startServer","config","createHTTPServer","createStdioServer","logger","close","transport","type","process","on","exit","info","Promise","main","versionHelpResult","argv","handled","console","log","output","createConfig","URL","url","pathname"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,0BAA0B;AAG5D,SAASC,YAAY,QAAQ,iBAAiB;AAC9C,sBAAqB,iBAAiB;AAAtC,SAAO,QAAKC,GAAG,GAAuB;AACtC,0BAAyB,qBAAqB;AAA9C,SAAO,YAAKC,OAAO,GAA2B;AAC9C,wBAAuB,mBAAmB;AAA1C,SAAO,UAAKC,KAAK,GAAyB;AAC1C,cAAc,aAAa;AAE3B,OAAO,eAAeC,YAAYC,MAAoB;IACpD,oFAAoF;IACpF,gFAAgF;IAChF,MAAM,EAAEC,gBAAgB,EAAE,GAAG,MAAM,MAAM,CAAC;IAC1C,MAAM,EAAEC,iBAAiB,EAAE,GAAG,MAAM,MAAM,CAAC;IAC3C,MAAM,EAAEC,MAAM,EAAEC,KAAK,EAAE,GAAGJ,OAAOK,SAAS,CAACC,IAAI,KAAK,UAAU,MAAMJ,kBAAkBF,UAAU,MAAMC,iBAAiBD;IAEvHO,QAAQC,EAAE,CAAC,UAAU;QACnB,MAAMJ;QACNG,QAAQE,IAAI,CAAC;IACf;IAEAN,OAAOO,IAAI,CAAC,CAAC,oBAAoB,EAAEV,OAAOK,SAAS,CAACC,IAAI,CAAC,UAAU,CAAC;IACpE,MAAM,IAAIK,QAAQ,KAAO;AAC3B;AAEA,eAAe,eAAeC;IAC5B,4DAA4D;IAC5D,MAAMC,oBAAoBnB,kBAAkBa,QAAQO,IAAI;IACxD,IAAID,kBAAkBE,OAAO,EAAE;QAC7BC,QAAQC,GAAG,CAACJ,kBAAkBK,MAAM;QACpCX,QAAQE,IAAI,CAAC;IACf;IAEA,kGAAkG;IAClG,8FAA8F;IAC9F,MAAM,EAAEU,YAAY,EAAE,GAAG,MAAM,MAAM,CAAC;IACtC,MAAMnB,SAASmB;IACf,MAAMpB,YAAYC;AACpB;AAEA,IAAIO,QAAQO,IAAI,CAAC,EAAE,KAAK,IAAIM,IAAI,YAAYC,GAAG,EAAEC,QAAQ,EAAE;IACzDV;AACF"}
@@ -0,0 +1,9 @@
1
+ import { type GoogleAuthProvider } from '@mcp-z/oauth-google';
2
+ /**
3
+ * A Google API client bound to this request's token provider.
4
+ *
5
+ * `@mcp-z/oauth-google` mints tokens and depends on no Google SDK, so the client
6
+ * is built here, from this package's own `googleapis`. That keeps one copy of
7
+ * `google-auth-library` in the tree by construction rather than by matching pins.
8
+ */
9
+ export declare function googleAuth(auth: GoogleAuthProvider): import("google-auth-library").OAuth2Client;
@@ -0,0 +1,11 @@
1
+ import { attachTokenProvider } from '@mcp-z/oauth-google';
2
+ import { google } from 'googleapis';
3
+ /**
4
+ * A Google API client bound to this request's token provider.
5
+ *
6
+ * `@mcp-z/oauth-google` mints tokens and depends on no Google SDK, so the client
7
+ * is built here, from this package's own `googleapis`. That keeps one copy of
8
+ * `google-auth-library` in the tree by construction rather than by matching pins.
9
+ */ export function googleAuth(auth) {
10
+ return attachTokenProvider(new google.auth.OAuth2(), auth);
11
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/lib/google-auth.ts"],"sourcesContent":["import { attachTokenProvider, type GoogleAuthProvider } from '@mcp-z/oauth-google';\nimport { google } from 'googleapis';\n\n/**\n * A Google API client bound to this request's token provider.\n *\n * `@mcp-z/oauth-google` mints tokens and depends on no Google SDK, so the client\n * is built here, from this package's own `googleapis`. That keeps one copy of\n * `google-auth-library` in the tree by construction rather than by matching pins.\n */\nexport function googleAuth(auth: GoogleAuthProvider) {\n return attachTokenProvider(new google.auth.OAuth2(), auth);\n}\n"],"names":["attachTokenProvider","google","googleAuth","auth","OAuth2"],"mappings":"AAAA,SAASA,mBAAmB,QAAiC,sBAAsB;AACnF,SAASC,MAAM,QAAQ,aAAa;AAEpC;;;;;;CAMC,GACD,OAAO,SAASC,WAAWC,IAAwB;IACjD,OAAOH,oBAAoB,IAAIC,OAAOE,IAAI,CAACC,MAAM,IAAID;AACvD"}
@@ -1,5 +1,4 @@
1
- import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';
2
- import type { ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';
1
+ import type { ServerContext } from '@mcp-z/server';
3
2
  export default function createPrompt(): {
4
3
  name: string;
5
4
  config: {
@@ -7,7 +6,7 @@ export default function createPrompt(): {
7
6
  };
8
7
  handler: (_args: {
9
8
  [x: string]: unknown;
10
- }, _extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => Promise<{
9
+ }, _extra: ServerContext) => Promise<{
11
10
  messages: {
12
11
  role: "user";
13
12
  content: {
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/prompts/query-syntax.ts"],"sourcesContent":["import type { PromptModule } from '@mcp-z/server';\nimport type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport type { ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';\n\nexport default function createPrompt() {\n const config = {\n description: 'Reference guide for Google Drive query syntax',\n };\n\n const handler = async (_args: { [x: string]: unknown }, _extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => {\n return {\n messages: [\n {\n role: 'user' as const,\n content: {\n type: 'text' as const,\n text: `# Google Drive Query Syntax Reference\n\n## Logical Operators\n- \\`$and\\`: Array of conditions that ALL must match\n- \\`$or\\`: Array of conditions where ANY must match\n- \\`$not\\`: Condition that must NOT match\n\n## File/Folder Fields\n- \\`name\\`: Search by name (partial match, case-insensitive)\n- \\`mimeType\\`: Filter by MIME type\n- \\`fullText\\`: Search file content and metadata\n- \\`parentId\\`: Search within folder (use \"root\" for My Drive)\n- \\`owner\\`: Filter by owner email\n\n## Boolean Flags\n- \\`starred\\`: true/false\n- \\`sharedWithMe\\`: true/false\n- \\`trashed\\`: true/false\n\n## Date Range\n\\`\\`\\`json\n{ \"modifiedTime\": { \"$gte\": \"2024-01-01\", \"$lt\": \"2024-12-31\" } }\n\\`\\`\\`\n\n## Common MIME Types\n- \\`application/vnd.google-apps.folder\\`: Folders\n- \\`application/vnd.google-apps.document\\`: Google Docs\n- \\`application/vnd.google-apps.spreadsheet\\`: Google Sheets\n- \\`application/vnd.google-apps.presentation\\`: Google Slides\n- \\`application/pdf\\`: PDF files\n- \\`image/jpeg\\`, \\`image/png\\`: Images\n\n## Field Operators (for multi-value fields)\n- \\`$any\\`: OR - matches if ANY value matches\n- \\`$all\\`: AND - matches if ALL values match\n- \\`$none\\`: NOT - matches if NONE match\n\n## Escape Hatch\n- \\`rawDriveQuery\\`: Raw Google Drive query syntax\n\n## Example Queries\n\\`\\`\\`json\n// PDFs modified this year\n{ \"mimeType\": \"application/pdf\", \"modifiedTime\": { \"$gte\": \"2024-01-01\" } }\n\n// Starred spreadsheets\n{ \"mimeType\": \"application/vnd.google-apps.spreadsheet\", \"starred\": true }\n\n// Files in specific folder\n{ \"parentId\": \"1abc123xyz\" }\n\n// Search by name\n{ \"name\": \"budget\" }\n\n// Complex: shared PDFs or Docs\n{ \"$or\": [\n { \"mimeType\": \"application/pdf\", \"sharedWithMe\": true },\n { \"mimeType\": \"application/vnd.google-apps.document\", \"sharedWithMe\": true }\n]}\n\\`\\`\\``,\n },\n },\n ],\n };\n };\n\n return {\n name: 'query-syntax',\n config,\n handler,\n } satisfies PromptModule;\n}\n"],"names":["createPrompt","config","description","handler","_args","_extra","messages","role","content","type","text","name"],"mappings":"AAIA,eAAe,SAASA;IACtB,MAAMC,SAAS;QACbC,aAAa;IACf;IAEA,MAAMC,UAAU,OAAOC,OAAiCC;QACtD,OAAO;YACLC,UAAU;gBACR;oBACEC,MAAM;oBACNC,SAAS;wBACPC,MAAM;wBACNC,MAAM,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MA2Db,CAAC;oBACG;gBACF;aACD;QACH;IACF;IAEA,OAAO;QACLC,MAAM;QACNV;QACAE;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/prompts/query-syntax.ts"],"sourcesContent":["import type { PromptModule, ServerContext } from '@mcp-z/server';\n\nexport default function createPrompt() {\n const config = {\n description: 'Reference guide for Google Drive query syntax',\n };\n\n const handler = async (_args: { [x: string]: unknown }, _extra: ServerContext) => {\n return {\n messages: [\n {\n role: 'user' as const,\n content: {\n type: 'text' as const,\n text: `# Google Drive Query Syntax Reference\n\n## Logical Operators\n- \\`$and\\`: Array of conditions that ALL must match\n- \\`$or\\`: Array of conditions where ANY must match\n- \\`$not\\`: Condition that must NOT match\n\n## File/Folder Fields\n- \\`name\\`: Search by name (partial match, case-insensitive)\n- \\`mimeType\\`: Filter by MIME type\n- \\`fullText\\`: Search file content and metadata\n- \\`parentId\\`: Search within folder (use \"root\" for My Drive)\n- \\`owner\\`: Filter by owner email\n\n## Boolean Flags\n- \\`starred\\`: true/false\n- \\`sharedWithMe\\`: true/false\n- \\`trashed\\`: true/false\n\n## Date Range\n\\`\\`\\`json\n{ \"modifiedTime\": { \"$gte\": \"2024-01-01\", \"$lt\": \"2024-12-31\" } }\n\\`\\`\\`\n\n## Common MIME Types\n- \\`application/vnd.google-apps.folder\\`: Folders\n- \\`application/vnd.google-apps.document\\`: Google Docs\n- \\`application/vnd.google-apps.spreadsheet\\`: Google Sheets\n- \\`application/vnd.google-apps.presentation\\`: Google Slides\n- \\`application/pdf\\`: PDF files\n- \\`image/jpeg\\`, \\`image/png\\`: Images\n\n## Field Operators (for multi-value fields)\n- \\`$any\\`: OR - matches if ANY value matches\n- \\`$all\\`: AND - matches if ALL values match\n- \\`$none\\`: NOT - matches if NONE match\n\n## Escape Hatch\n- \\`rawDriveQuery\\`: Raw Google Drive query syntax\n\n## Example Queries\n\\`\\`\\`json\n// PDFs modified this year\n{ \"mimeType\": \"application/pdf\", \"modifiedTime\": { \"$gte\": \"2024-01-01\" } }\n\n// Starred spreadsheets\n{ \"mimeType\": \"application/vnd.google-apps.spreadsheet\", \"starred\": true }\n\n// Files in specific folder\n{ \"parentId\": \"1abc123xyz\" }\n\n// Search by name\n{ \"name\": \"budget\" }\n\n// Complex: shared PDFs or Docs\n{ \"$or\": [\n { \"mimeType\": \"application/pdf\", \"sharedWithMe\": true },\n { \"mimeType\": \"application/vnd.google-apps.document\", \"sharedWithMe\": true }\n]}\n\\`\\`\\``,\n },\n },\n ],\n };\n };\n\n return {\n name: 'query-syntax',\n config,\n handler,\n } satisfies PromptModule;\n}\n"],"names":["createPrompt","config","description","handler","_args","_extra","messages","role","content","type","text","name"],"mappings":"AAEA,eAAe,SAASA;IACtB,MAAMC,SAAS;QACbC,aAAa;IACf;IAEA,MAAMC,UAAU,OAAOC,OAAiCC;QACtD,OAAO;YACLC,UAAU;gBACR;oBACEC,MAAM;oBACNC,SAAS;wBACPC,MAAM;wBACNC,MAAM,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MA2Db,CAAC;oBACG;gBACF;aACD;QACH;IACF;IAEA,OAAO;QACLC,MAAM;QACNV;QACAE;IACF;AACF"}
@@ -1,9 +1,2 @@
1
- import { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
2
- import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';
3
- import type { ReadResourceResult, ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';
4
- export default function createResource(): {
5
- name: string;
6
- template: ResourceTemplate;
7
- config: import("@modelcontextprotocol/sdk/server/mcp.js").ResourceMetadata;
8
- handler: (uri: URL, variables: Record<string, string | string[]>, extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => Promise<ReadResourceResult>;
9
- };
1
+ import type { ResourceModule } from '@mcp-z/server';
2
+ export default function createResource(): ResourceModule;
@@ -1,5 +1,6 @@
1
- import { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
1
+ import { ResourceTemplate } from '@mcp-z/server';
2
2
  import { google } from 'googleapis';
3
+ import { googleAuth } from '../../lib/google-auth.js';
3
4
  export default function createResource() {
4
5
  const template = new ResourceTemplate('drive://files/{fileId}', {
5
6
  list: undefined
@@ -31,7 +32,7 @@ export default function createResource() {
31
32
  const { logger, authContext } = extra;
32
33
  const drive = google.drive({
33
34
  version: 'v3',
34
- auth: authContext.auth
35
+ auth: googleAuth(authContext.auth)
35
36
  });
36
37
  const resp = await drive.files.get({
37
38
  fileId,
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/resources/file.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport type { ResourceConfig, ResourceModule } from '@mcp-z/server';\nimport { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport type { ReadResourceResult, ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';\nimport { google } from 'googleapis';\n\nexport default function createResource() {\n const template = new ResourceTemplate('drive://files/{fileId}', {\n list: undefined,\n });\n const config: ResourceConfig = {\n description: 'Drive file resource',\n mimeType: 'application/json',\n };\n\n const handler = async (uri: URL, variables: Record<string, string | string[]>, extra: RequestHandlerExtra<ServerRequest, ServerNotification>): Promise<ReadResourceResult> => {\n // Extract fileId and handle both string and string[] cases\n const fileId = Array.isArray(variables.fileId) ? variables.fileId[0] : variables.fileId;\n\n try {\n // Validate fileId exists and is a string\n if (!fileId || typeof fileId !== 'string') {\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify({\n error: 'Missing or invalid fileId in resource URI',\n }),\n },\n ],\n };\n }\n\n // Safe type guard to access middleware-enriched extra\n const { logger, authContext } = extra as unknown as EnrichedExtra;\n const drive = google.drive({ version: 'v3', auth: authContext.auth });\n const resp = await drive.files.get({\n fileId,\n fields: 'id,name,mimeType,size,modifiedTime,owners,webViewLink',\n });\n const data = resp.data;\n logger.debug?.({ fileId, fileName: data?.name }, 'drive-file resource fetch success');\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify(data || {}),\n },\n ],\n };\n } catch (error) {\n const { logger } = extra as unknown as EnrichedExtra;\n logger.debug?.(error as Record<string, unknown>, 'drive resource fetch failed');\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify({ error: (error as Error).message }),\n },\n ],\n };\n }\n };\n\n return {\n name: 'file',\n template,\n config,\n handler,\n } satisfies ResourceModule;\n}\n"],"names":["ResourceTemplate","google","createResource","template","list","undefined","config","description","mimeType","handler","uri","variables","extra","fileId","Array","isArray","logger","contents","href","text","JSON","stringify","error","authContext","drive","version","auth","resp","files","get","fields","data","debug","fileName","name","message"],"mappings":"AAEA,SAASA,gBAAgB,QAAQ,0CAA0C;AAG3E,SAASC,MAAM,QAAQ,aAAa;AAEpC,eAAe,SAASC;IACtB,MAAMC,WAAW,IAAIH,iBAAiB,0BAA0B;QAC9DI,MAAMC;IACR;IACA,MAAMC,SAAyB;QAC7BC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,OAAO,AAACA,MAAgBa,OAAO;wBAAC;oBACzD;iBACD;YACH;QACF;IACF;IAEA,OAAO;QACLD,MAAM;QACN/B;QACAG;QACAG;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/resources/file.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport type { ReadResourceResult, ResourceConfig, ResourceModule, ServerContext } from '@mcp-z/server';\nimport { ResourceTemplate } from '@mcp-z/server';\nimport { google } from 'googleapis';\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 = google.drive({ 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":["ResourceTemplate","google","googleAuth","createResource","template","list","undefined","config","description","mimeType","handler","uri","variables","extra","fileId","Array","isArray","logger","contents","href","text","JSON","stringify","error","authContext","drive","version","auth","resp","files","get","fields","data","debug","fileName","name","message"],"mappings":"AAEA,SAASA,gBAAgB,QAAQ,gBAAgB;AACjD,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,UAAU,QAAQ,2BAA2B;AAEtD,eAAe,SAASC;IACtB,MAAMC,WAAW,IAAIJ,iBAAiB,0BAA0B;QAC9DK,MAAMC;IACR;IACA,MAAMC,SAAyB;QAC7BC,aAAa;QACbC,UAAU;IACZ;IAEA,MAAMC,UAAU,OAAOC,KAAUC,WAA8CC;QAC7E,2DAA2D;QAC3D,MAAMC,SAASC,MAAMC,OAAO,CAACJ,UAAUE,MAAM,IAAIF,UAAUE,MAAM,CAAC,EAAE,GAAGF,UAAUE,MAAM;QAEvF,IAAI;gBAwBFG;YAvBA,yCAAyC;YACzC,IAAI,CAACH,UAAU,OAAOA,WAAW,UAAU;gBACzC,OAAO;oBACLI,UAAU;wBACR;4BACEP,KAAKA,IAAIQ,IAAI;4BACbV,UAAU;4BACVW,MAAMC,KAAKC,SAAS,CAAC;gCACnBC,OAAO;4BACT;wBACF;qBACD;gBACH;YACF;YAEA,sDAAsD;YACtD,MAAM,EAAEN,MAAM,EAAEO,WAAW,EAAE,GAAGX;YAChC,MAAMY,QAAQxB,OAAOwB,KAAK,CAAC;gBAAEC,SAAS;gBAAMC,MAAMzB,WAAWsB,YAAYG,IAAI;YAAE;YAC/E,MAAMC,OAAO,MAAMH,MAAMI,KAAK,CAACC,GAAG,CAAC;gBACjChB;gBACAiB,QAAQ;YACV;YACA,MAAMC,OAAOJ,KAAKI,IAAI;aACtBf,gBAAAA,OAAOgB,KAAK,cAAZhB,oCAAAA,mBAAAA,QAAe;gBAAEH;gBAAQoB,QAAQ,EAAEF,iBAAAA,2BAAAA,KAAMG,IAAI;YAAC,GAAG;YACjD,OAAO;gBACLjB,UAAU;oBACR;wBACEP,KAAKA,IAAIQ,IAAI;wBACbV,UAAU;wBACVW,MAAMC,KAAKC,SAAS,CAACU,QAAQ,CAAC;oBAChC;iBACD;YACH;QACF,EAAE,OAAOT,OAAO;gBAEdN;YADA,MAAM,EAAEA,MAAM,EAAE,GAAGJ;aACnBI,iBAAAA,OAAOgB,KAAK,cAAZhB,qCAAAA,oBAAAA,QAAeM,OAAkC;YACjD,OAAO;gBACLL,UAAU;oBACR;wBACEP,KAAKA,IAAIQ,IAAI;wBACbV,UAAU;wBACVW,MAAMC,KAAKC,SAAS,CAAC;4BAAEC,OAAO,AAACA,MAAgBa,OAAO;wBAAC;oBACzD;iBACD;YACH;QACF;IACF;IAEA,OAAO;QACLD,MAAM;QACN/B;QACAG;QACAG;IACF;AACF"}
@@ -1,5 +1,5 @@
1
1
  import type { EnrichedExtra } from '@mcp-z/oauth-google';
2
- import { type CallToolResult } from '@modelcontextprotocol/sdk/types.js';
2
+ import { type CallToolResult } from '@mcp-z/server';
3
3
  import { z } from 'zod';
4
4
  declare const inputSchema: z.ZodObject<{
5
5
  ids: z.ZodArray<z.ZodString>;
@@ -1,8 +1,9 @@
1
1
  import { schemas } from '@mcp-z/oauth-google';
2
2
  const { AuthRequiredBranchSchema } = schemas;
3
- import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
3
+ import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';
4
4
  import { google } from 'googleapis';
5
5
  import { z } from 'zod';
6
+ import { googleAuth } from '../../lib/google-auth.js';
6
7
  const MAX_BATCH_SIZE = 1000;
7
8
  const inputSchema = z.object({
8
9
  ids: z.array(z.string().min(1)).min(1).max(MAX_BATCH_SIZE).describe('File IDs to soft delete (move to trash)')
@@ -42,7 +43,7 @@ async function handler({ ids }, extra) {
42
43
  try {
43
44
  const drive = google.drive({
44
45
  version: 'v3',
45
- auth: extra.authContext.auth
46
+ auth: googleAuth(extra.authContext.auth)
46
47
  });
47
48
  const results = await Promise.allSettled(ids.map(async (id)=>{
48
49
  await drive.files.update({
@@ -103,8 +104,8 @@ async function handler({ ids }, extra) {
103
104
  logger.error('drive.file.moveToTrash error', {
104
105
  error: message
105
106
  });
106
- // Throw McpError
107
- throw new McpError(ErrorCode.InternalError, `Error moving files to trash: ${message}`, {
107
+ // Throw ProtocolError
108
+ throw new ProtocolError(ProtocolErrorCode.InternalError, `Error moving files to trash: ${message}`, {
108
109
  stack: error instanceof Error ? error.stack : undefined
109
110
  });
110
111
  }
@@ -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 { type CallToolResult, ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\n\nconst MAX_BATCH_SIZE = 1000;\n\nconst inputSchema = z.object({\n ids: z.array(z.string().min(1)).min(1).max(MAX_BATCH_SIZE).describe('File IDs to soft delete (move to trash)'),\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n operationSummary: z.string().describe('Human-readable summary of the operation'),\n totalCount: z.number().describe('Total number of files requested to trash'),\n successCount: z.number().describe('Number of files successfully moved to trash'),\n failureCount: z.number().describe('Number of files that failed to move'),\n recoverable: z.boolean().describe('Whether trashed files can be restored'),\n recoverableDays: z.number().describe('Days until permanent deletion'),\n failures: z\n .array(\n z.object({\n id: z.string().describe('ID of the file that failed'),\n error: z.string().describe('Error message explaining the failure'),\n })\n )\n .optional()\n .describe('Details of any files that failed to trash'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n title: 'Move Files to Trash',\n description: 'Move files to trash (recoverable for 30 days).',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ ids }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('drive.file.moveToTrash called', { count: ids.length });\n\n try {\n const drive = google.drive({ version: 'v3', auth: extra.authContext.auth });\n\n const results = await Promise.allSettled(\n ids.map(async (id) => {\n await drive.files.update({\n fileId: id,\n requestBody: { trashed: true },\n });\n return id;\n })\n );\n\n // Separate successes and failures\n const failures: Array<{ id: string; error: string }> = [];\n\n results.forEach((result, index) => {\n const id = ids[index];\n if (!id) return;\n\n if (result.status === 'rejected') {\n const errorMessage = result.reason instanceof Error ? result.reason.message : String(result.reason);\n failures.push({ id, error: errorMessage });\n }\n });\n\n const successCount = ids.length - failures.length;\n const failureCount = failures.length;\n const totalCount = ids.length;\n\n logger.info('drive.file.moveToTrash completed', {\n totalCount,\n successCount,\n failureCount,\n });\n\n const operationSummary = failureCount === 0 ? `Moved ${successCount} file${successCount === 1 ? '' : 's'} to trash (recoverable for 30 days)` : `Moved ${successCount} of ${totalCount} file${totalCount === 1 ? '' : 's'} to trash (${failureCount} failed, recoverable for 30 days)`;\n\n const result: Output = {\n type: 'success' as const,\n operationSummary,\n totalCount,\n successCount,\n failureCount,\n recoverable: true,\n recoverableDays: 30,\n ...(failures.length > 0 && { failures }),\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('drive.file.moveToTrash error', { error: message });\n\n // Throw McpError\n throw new McpError(ErrorCode.InternalError, `Error moving files to trash: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'file-move-to-trash' as const,\n config,\n handler,\n };\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ErrorCode","McpError","google","z","MAX_BATCH_SIZE","inputSchema","object","ids","array","string","min","max","describe","successBranchSchema","type","literal","operationSummary","totalCount","number","successCount","failureCount","recoverable","boolean","recoverableDays","failures","id","error","optional","outputSchema","discriminatedUnion","config","title","description","result","handler","extra","logger","info","count","length","drive","version","auth","authContext","results","Promise","allSettled","map","files","update","fileId","requestBody","trashed","forEach","index","status","errorMessage","reason","Error","message","String","push","content","text","JSON","stringify","structuredContent","InternalError","stack","undefined","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAErC,SAA8BE,SAAS,EAAEC,QAAQ,QAAQ,qCAAqC;AAC9F,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,CAAC,QAAQ,MAAM;AAExB,MAAMC,iBAAiB;AAEvB,MAAMC,cAAcF,EAAEG,MAAM,CAAC;IAC3BC,KAAKJ,EAAEK,KAAK,CAACL,EAAEM,MAAM,GAAGC,GAAG,CAAC,IAAIA,GAAG,CAAC,GAAGC,GAAG,CAACP,gBAAgBQ,QAAQ,CAAC;AACtE;AAEA,wBAAwB;AACxB,MAAMC,sBAAsBV,EAAEG,MAAM,CAAC;IACnCQ,MAAMX,EAAEY,OAAO,CAAC;IAChBC,kBAAkBb,EAAEM,MAAM,GAAGG,QAAQ,CAAC;IACtCK,YAAYd,EAAEe,MAAM,GAAGN,QAAQ,CAAC;IAChCO,cAAchB,EAAEe,MAAM,GAAGN,QAAQ,CAAC;IAClCQ,cAAcjB,EAAEe,MAAM,GAAGN,QAAQ,CAAC;IAClCS,aAAalB,EAAEmB,OAAO,GAAGV,QAAQ,CAAC;IAClCW,iBAAiBpB,EAAEe,MAAM,GAAGN,QAAQ,CAAC;IACrCY,UAAUrB,EACPK,KAAK,CACJL,EAAEG,MAAM,CAAC;QACPmB,IAAItB,EAAEM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ASe,MAAM;QACjD,MAAMnB,eAAeI,SAASe,MAAM;QACpC,MAAMtB,aAAaV,IAAIgC,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;YACLsC,SAAS;gBACP;oBACEhD,MAAM;oBACNiD,MAAMC,KAAKC,SAAS,CAAChC;gBACvB;aACD;YACDiC,mBAAmB;gBAAEjC;YAAO;QAC9B;IACF,EAAE,OAAOP,OAAO;QACd,MAAMiC,UAAUjC,iBAAiBgC,QAAQhC,MAAMiC,OAAO,GAAGC,OAAOlC;QAChEU,OAAOV,KAAK,CAAC,gCAAgC;YAAEA,OAAOiC;QAAQ;QAE9D,iBAAiB;QACjB,MAAM,IAAI1D,SAASD,UAAUmE,aAAa,EAAE,CAAC,6BAA6B,EAAER,SAAS,EAAE;YACrFS,OAAO1C,iBAAiBgC,QAAQhC,MAAM0C,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QACLC,MAAM;QACNzC;QACAI;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/tools/file-move-to-trash.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { type CallToolResult, ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { google } from 'googleapis';\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 = google.drive({ 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","ProtocolError","ProtocolErrorCode","google","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","drive","version","auth","authContext","results","Promise","allSettled","map","files","update","fileId","requestBody","trashed","forEach","index","status","errorMessage","reason","Error","message","String","push","content","text","JSON","stringify","structuredContent","InternalError","stack","undefined","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAErC,SAA8BE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACtF,SAASC,MAAM,QAAQ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,SAASe,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,IAAI5D,cAAcC,kBAAkBmE,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"}
@@ -1,5 +1,5 @@
1
1
  import type { EnrichedExtra } from '@mcp-z/oauth-google';
2
- import { type CallToolResult } from '@modelcontextprotocol/sdk/types.js';
2
+ import { type CallToolResult } from '@mcp-z/server';
3
3
  import { z } from 'zod';
4
4
  declare const inputSchema: z.ZodObject<{
5
5
  fileIds: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
@@ -1,8 +1,9 @@
1
1
  import { schemas } from '@mcp-z/oauth-google';
2
2
  const { AuthRequiredBranchSchema } = schemas;
3
- import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
3
+ import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';
4
4
  import { google } from 'googleapis';
5
5
  import { z } from 'zod';
6
+ import { googleAuth } from '../../lib/google-auth.js';
6
7
  function isDriveApiError(error) {
7
8
  return typeof error === 'object' && error !== null && ('message' in error || 'code' in error);
8
9
  }
@@ -207,7 +208,7 @@ async function handler({ fileIds, destinationFolderId, returnOldParents = true }
207
208
  try {
208
209
  const drive = google.drive({
209
210
  version: 'v3',
210
- auth: extra.authContext.auth
211
+ auth: googleAuth(extra.authContext.auth)
211
212
  });
212
213
  let moved = [];
213
214
  let failed = [];
@@ -259,8 +260,8 @@ async function handler({ fileIds, destinationFolderId, returnOldParents = true }
259
260
  logger.error('drive.file.move error', {
260
261
  error: message
261
262
  });
262
- // Throw McpError
263
- throw new McpError(ErrorCode.InternalError, `Error moving files: ${message}`, {
263
+ // Throw ProtocolError
264
+ throw new ProtocolError(ProtocolErrorCode.InternalError, `Error moving files: ${message}`, {
264
265
  stack: error instanceof Error ? error.stack : undefined
265
266
  });
266
267
  }