@mcp-z/mcp-drive 2.4.1 → 2.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/server.js +1 -1
- package/dist/cjs/constants.js.map +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/lib/create-store.js.map +1 -1
- package/dist/cjs/lib/file-streaming.js.map +1 -1
- package/dist/cjs/lib/google-auth.js.map +1 -1
- package/dist/cjs/lib/query-builder.js.map +1 -1
- package/dist/cjs/mcp/index.js.map +1 -1
- package/dist/cjs/mcp/prompts/index.js.map +1 -1
- package/dist/cjs/mcp/prompts/organize-files.js.map +1 -1
- package/dist/cjs/mcp/prompts/query-syntax.js.map +1 -1
- package/dist/cjs/mcp/resources/file.js.map +1 -1
- package/dist/cjs/mcp/resources/index.js.map +1 -1
- package/dist/cjs/mcp/tools/file-move-to-trash.js.map +1 -1
- package/dist/cjs/mcp/tools/file-move.js.map +1 -1
- package/dist/cjs/mcp/tools/file-upload.js.map +1 -1
- package/dist/cjs/mcp/tools/files-search.js.map +1 -1
- package/dist/cjs/mcp/tools/folder-contents.js.map +1 -1
- package/dist/cjs/mcp/tools/folder-create.js.map +1 -1
- package/dist/cjs/mcp/tools/folder-path.js.map +1 -1
- package/dist/cjs/mcp/tools/folder-search.js.map +1 -1
- package/dist/cjs/mcp/tools/index.js.map +1 -1
- package/dist/cjs/schemas/drive-query-schema.js.map +1 -1
- package/dist/cjs/schemas/drive-validation.js.map +1 -1
- package/dist/cjs/schemas/index.js.map +1 -1
- package/dist/cjs/setup/config.js +5 -4
- package/dist/cjs/setup/config.js.map +1 -1
- package/dist/cjs/setup/http.js.map +1 -1
- package/dist/cjs/setup/index.js.map +1 -1
- package/dist/cjs/setup/oauth-google.js.map +1 -1
- package/dist/cjs/setup/runtime.js +3 -2
- package/dist/cjs/setup/runtime.js.map +1 -1
- package/dist/cjs/setup/stdio.js.map +1 -1
- package/dist/cjs/setup/version-help.js.map +1 -1
- package/dist/esm/constants.js.map +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/lib/create-store.js.map +1 -1
- package/dist/esm/lib/file-streaming.js.map +1 -1
- package/dist/esm/lib/google-auth.js.map +1 -1
- package/dist/esm/lib/query-builder.js.map +1 -1
- package/dist/esm/mcp/index.js.map +1 -1
- package/dist/esm/mcp/prompts/index.js.map +1 -1
- package/dist/esm/mcp/prompts/organize-files.js.map +1 -1
- package/dist/esm/mcp/prompts/query-syntax.js.map +1 -1
- package/dist/esm/mcp/resources/file.js.map +1 -1
- package/dist/esm/mcp/resources/index.js.map +1 -1
- package/dist/esm/mcp/tools/file-move-to-trash.js.map +1 -1
- package/dist/esm/mcp/tools/file-move.js.map +1 -1
- package/dist/esm/mcp/tools/file-upload.js.map +1 -1
- package/dist/esm/mcp/tools/files-search.js.map +1 -1
- package/dist/esm/mcp/tools/folder-contents.js.map +1 -1
- package/dist/esm/mcp/tools/folder-create.js.map +1 -1
- package/dist/esm/mcp/tools/folder-path.js.map +1 -1
- package/dist/esm/mcp/tools/folder-search.js.map +1 -1
- package/dist/esm/mcp/tools/index.js.map +1 -1
- package/dist/esm/schemas/drive-query-schema.js.map +1 -1
- package/dist/esm/schemas/drive-validation.js.map +1 -1
- package/dist/esm/schemas/index.js.map +1 -1
- package/dist/esm/setup/config.js +4 -3
- package/dist/esm/setup/config.js.map +1 -1
- package/dist/esm/setup/http.js.map +1 -1
- package/dist/esm/setup/index.js.map +1 -1
- package/dist/esm/setup/oauth-google.js.map +1 -1
- package/dist/esm/setup/runtime.js +3 -2
- package/dist/esm/setup/runtime.js.map +1 -1
- package/dist/esm/setup/stdio.js.map +1 -1
- package/dist/esm/setup/version-help.js.map +1 -1
- package/dist/esm/types.js.map +1 -1
- package/package.json +6 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/tools/folder-contents.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { drive as driveApi } from '@googleapis/drive';\nimport { type CallToolResult, createFieldsSchema, createPaginationSchema, createShapeSchema, filterFields, ProtocolError, ProtocolErrorCode, parseFields, toColumnarFormat } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { DRIVE_FILE_COMMON_PATTERNS, DRIVE_FILE_FIELD_DESCRIPTIONS, DRIVE_FILE_FIELDS, type DriveFile, DriveFileSchema } from '../../schemas/index.ts';\n\nconst inputSchema = z.object({\n folderId: z.string().min(1).describe('Folder ID to list contents (use \"root\" for Drive root)'),\n fields: createFieldsSchema({\n availableFields: DRIVE_FILE_FIELDS,\n fieldDescriptions: DRIVE_FILE_FIELD_DESCRIPTIONS,\n commonPatterns: DRIVE_FILE_COMMON_PATTERNS,\n resourceName: 'Drive item',\n }),\n ...createPaginationSchema({\n defaultPageSize: 50,\n maxPageSize: 1000,\n provider: 'drive',\n }).shape,\n shape: createShapeSchema(),\n});\n\n// Success branch schemas for different shapes\nconst successObjectsBranchSchema = z.object({\n type: z.literal('success'),\n shape: z.literal('objects'),\n items: z.array(DriveFileSchema).describe('Files and folders in the specified folder'),\n count: z.number().describe('Number of items in this page'),\n folderId: z.string().describe('ID of the folder that was listed'),\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 items in this page'),\n folderId: z.string().describe('ID of the folder that was listed'),\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: 'List Folder Contents',\n description: 'List files and folders in a specific folder with field selection.',\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 DriveItem = {\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 DriveResponse = {\n files?: DriveItem[];\n nextPageToken?: string;\n};\n\nasync function handler({ folderId, pageSize = 50, pageToken, fields, shape = 'arrays' }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n\n const requestedFields = parseFields(fields, DRIVE_FILE_FIELDS);\n\n logger.info('drive.folder.contents called', {\n folderId,\n pageSize,\n pageToken: pageToken ? '[provided]' : undefined,\n fields: fields || 'all',\n });\n\n try {\n const drive = driveApi({ version: 'v3', auth: googleAuth(extra.authContext.auth) });\n\n const qStr = `'${folderId}' in parents and trashed = false`;\n\n const listOptions: {\n q: string;\n pageSize: number;\n fields: string;\n orderBy: string;\n pageToken?: string;\n corpora: string;\n supportsAllDrives: boolean;\n includeItemsFromAllDrives: boolean;\n } = {\n q: qStr,\n pageSize: Math.min(1000, pageSize),\n fields: 'files(id,name,mimeType,webViewLink,modifiedTime,parents,shared,starred,owners),nextPageToken',\n orderBy: 'folder,name', // Folders first, then by name\n // All three are load-bearing for shared drives: the default `user` corpus omits\n // them, and Drive rejects an `allDrives` corpus unless both flags are set too.\n corpora: 'allDrives',\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n };\n if (pageToken && pageToken.trim().length > 0) {\n listOptions.pageToken = pageToken;\n }\n\n const response = await drive.files.list(listOptions);\n\n const res = response.data as DriveResponse;\n const items = Array.isArray(res?.files) ? res.files : [];\n\n const parentIds = new Set<string>();\n for (const f of items) {\n if (f?.parents && f.parents.length > 0) {\n for (const parentId of f.parents) {\n if (parentId && parentId !== 'root') {\n parentIds.add(parentId);\n }\n }\n }\n }\n\n const parentNameMap = new Map<string, string>();\n if (parentIds.size > 0) {\n logger.info('Fetching parent names', { count: parentIds.size });\n const parentFetches = Array.from(parentIds).map(async (parentId) => {\n try {\n const parentRes = await drive.files.get({\n fileId: parentId,\n fields: 'id,name',\n supportsAllDrives: true,\n });\n const parentName = (parentRes.data.name as string | undefined) || parentId;\n parentNameMap.set(parentId, parentName);\n } catch (e) {\n logger.info('Failed to fetch parent name', { parentId, error: e });\n parentNameMap.set(parentId, parentId); // Fallback to ID\n }\n });\n await Promise.all(parentFetches);\n }\n\n const driveFiles: DriveFile[] = items.map((f: DriveItem) => {\n const id = f?.id ? String(f.id) : 'unknown';\n const name = f?.name || id;\n const result: DriveFile = { id, name };\n\n // Only include properties that have actual values\n if (f?.mimeType) result.mimeType = f.mimeType;\n if (f?.webViewLink) result.webViewLink = f.webViewLink;\n if (f?.modifiedTime) result.modifiedTime = f.modifiedTime;\n\n // 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 return result;\n });\n\n const filteredItems = driveFiles.map((item) => filterFields(item, requestedFields));\n\n logger.info('drive.folder.contents returning', {\n folderId,\n resultCount: filteredItems.length,\n fields: fields || 'all',\n });\n\n const nextPageToken = res.nextPageToken && res.nextPageToken.trim().length > 0 ? res.nextPageToken : undefined;\n\n // Build result based on shape\n const result: Output =\n shape === 'arrays'\n ? {\n type: 'success' as const,\n shape: 'arrays' as const,\n ...toColumnarFormat(filteredItems, requestedFields, DRIVE_FILE_FIELDS),\n count: filteredItems.length,\n folderId,\n ...(nextPageToken && { nextPageToken }),\n }\n : {\n type: 'success' as const,\n shape: 'objects' as const,\n items: filteredItems,\n count: filteredItems.length,\n folderId,\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.contents error', { error: message });\n\n // Throw ProtocolError\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error listing folder contents: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'folder-contents' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","folderId","string","min","describe","fields","createFieldsSchema","availableFields","DRIVE_FILE_FIELDS","fieldDescriptions","DRIVE_FILE_FIELD_DESCRIPTIONS","commonPatterns","DRIVE_FILE_COMMON_PATTERNS","resourceName","createPaginationSchema","defaultPageSize","maxPageSize","provider","shape","createShapeSchema","successObjectsBranchSchema","type","literal","items","array","DriveFileSchema","count","number","nextPageToken","optional","successArraysBranchSchema","columns","rows","unknown","outputSchema","union","config","title","description","result","handler","extra","pageSize","pageToken","logger","requestedFields","drive","qStr","listOptions","response","res","parentIds","f","parentId","parentNameMap","parentFetches","driveFiles","filteredItems","error","message","parseFields","info","undefined","driveApi","version","auth","googleAuth","authContext","q","Math","orderBy","corpora","supportsAllDrives","includeItemsFromAllDrives","trim","length","files","list","data","Array","isArray","Set","parents","add","Map","size","from","map","parentRes","parentName","e","get","fileId","name","set","Promise","all","id","String","mimeType","webViewLink","modifiedTime","shared","starred","owners","o","owner","displayName","emailAddress","kind","me","permissionId","photoLink","item","filterFields","resultCount","toColumnarFormat","content","text","JSON","stringify","structuredContent","Error","ProtocolError","ProtocolErrorCode","InternalError","stack"],"mappings":";;;;+BA+PA;;;eAAwBA;;;2BA9PA;qBAIU;sBACgJ;mBAChK;4BACS;uBACmG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAN9H,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAQR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,UAAUF,MAAC,CAACG,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IACrCC,QAAQC,IAAAA,0BAAkB,EAAC;QACzBC,iBAAiBC,0BAAiB;QAClCC,mBAAmBC,sCAA6B;QAChDC,gBAAgBC,mCAA0B;QAC1CC,cAAc;IAChB;GACGC,IAAAA,8BAAsB,EAAC;IACxBC,iBAAiB;IACjBC,aAAa;IACbC,UAAU;AACZ,GAAGC,KAAK;IACRA,OAAOC,IAAAA,yBAAiB;;AAG1B,8CAA8C;AAC9C,IAAMC,6BAA6BrB,MAAC,CAACC,MAAM,CAAC;IAC1CqB,MAAMtB,MAAC,CAACuB,OAAO,CAAC;IAChBJ,OAAOnB,MAAC,CAACuB,OAAO,CAAC;IACjBC,OAAOxB,MAAC,CAACyB,KAAK,CAACC,wBAAe,EAAErB,QAAQ,CAAC;IACzCsB,OAAO3B,MAAC,CAAC4B,MAAM,GAAGvB,QAAQ,CAAC;IAC3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F;gCACvB;;4BAEFkF,mBAAmB;gCAAElF,QAAAA;4BAAO;wBAC9B;;;oBACOmB;oBACDC,UAAUD,AAAK,YAALA,OAAiBgE,SAAQhE,MAAMC,OAAO,GAAGuC,OAAOxC;oBAChEd,OAAOc,KAAK,CAAC,+BAA+B;wBAAEA,OAAOC;oBAAQ;oBAE7D,sBAAsB;oBACtB,MAAM,IAAIgE,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,kCAAyC,OAARlE,UAAW;wBACpGmE,OAAOpE,AAAK,YAALA,OAAiBgE,SAAQhE,MAAMoE,KAAK,GAAGhE;oBAChD;;;;;;;IAEJ;;AAEe,SAASnE;IACtB,OAAO;QACLkG,MAAM;QACNzD,QAAAA;QACAI,SAAAA;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-drive/src/mcp/tools/folder-contents.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { drive as driveApi } from '@googleapis/drive';\nimport { type CallToolResult, createFieldsSchema, createPaginationSchema, createShapeSchema, filterFields, ProtocolError, ProtocolErrorCode, parseFields, toColumnarFormat } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { DRIVE_FILE_COMMON_PATTERNS, DRIVE_FILE_FIELD_DESCRIPTIONS, DRIVE_FILE_FIELDS, type DriveFile, DriveFileSchema } from '../../schemas/index.ts';\n\nconst inputSchema = z.object({\n folderId: z.string().min(1).describe('Folder ID to list contents (use \"root\" for Drive root)'),\n fields: createFieldsSchema({\n availableFields: DRIVE_FILE_FIELDS,\n fieldDescriptions: DRIVE_FILE_FIELD_DESCRIPTIONS,\n commonPatterns: DRIVE_FILE_COMMON_PATTERNS,\n resourceName: 'Drive item',\n }),\n ...createPaginationSchema({\n defaultPageSize: 50,\n maxPageSize: 1000,\n provider: 'drive',\n }).shape,\n shape: createShapeSchema(),\n});\n\n// Success branch schemas for different shapes\nconst successObjectsBranchSchema = z.object({\n type: z.literal('success'),\n shape: z.literal('objects'),\n items: z.array(DriveFileSchema).describe('Files and folders in the specified folder'),\n count: z.number().describe('Number of items in this page'),\n folderId: z.string().describe('ID of the folder that was listed'),\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 items in this page'),\n folderId: z.string().describe('ID of the folder that was listed'),\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: 'List Folder Contents',\n description: 'List files and folders in a specific folder with field selection.',\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 DriveItem = {\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 DriveResponse = {\n files?: DriveItem[];\n nextPageToken?: string;\n};\n\nasync function handler({ folderId, pageSize = 50, pageToken, fields, shape = 'arrays' }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n\n const requestedFields = parseFields(fields, DRIVE_FILE_FIELDS);\n\n logger.info('drive.folder.contents called', {\n folderId,\n pageSize,\n pageToken: pageToken ? '[provided]' : undefined,\n fields: fields || 'all',\n });\n\n try {\n const drive = driveApi({ version: 'v3', auth: googleAuth(extra.authContext.auth) });\n\n const qStr = `'${folderId}' in parents and trashed = false`;\n\n const listOptions: {\n q: string;\n pageSize: number;\n fields: string;\n orderBy: string;\n pageToken?: string;\n corpora: string;\n supportsAllDrives: boolean;\n includeItemsFromAllDrives: boolean;\n } = {\n q: qStr,\n pageSize: Math.min(1000, pageSize),\n fields: 'files(id,name,mimeType,webViewLink,modifiedTime,parents,shared,starred,owners),nextPageToken',\n orderBy: 'folder,name', // Folders first, then by name\n // All three are load-bearing for shared drives: the default `user` corpus omits\n // them, and Drive rejects an `allDrives` corpus unless both flags are set too.\n corpora: 'allDrives',\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n };\n if (pageToken && pageToken.trim().length > 0) {\n listOptions.pageToken = pageToken;\n }\n\n const response = await drive.files.list(listOptions);\n\n const res = response.data as DriveResponse;\n const items = Array.isArray(res?.files) ? res.files : [];\n\n const parentIds = new Set<string>();\n for (const f of items) {\n if (f?.parents && f.parents.length > 0) {\n for (const parentId of f.parents) {\n if (parentId && parentId !== 'root') {\n parentIds.add(parentId);\n }\n }\n }\n }\n\n const parentNameMap = new Map<string, string>();\n if (parentIds.size > 0) {\n logger.info('Fetching parent names', { count: parentIds.size });\n const parentFetches = Array.from(parentIds).map(async (parentId) => {\n try {\n const parentRes = await drive.files.get({\n fileId: parentId,\n fields: 'id,name',\n supportsAllDrives: true,\n });\n const parentName = (parentRes.data.name as string | undefined) || parentId;\n parentNameMap.set(parentId, parentName);\n } catch (e) {\n logger.info('Failed to fetch parent name', { parentId, error: e });\n parentNameMap.set(parentId, parentId); // Fallback to ID\n }\n });\n await Promise.all(parentFetches);\n }\n\n const driveFiles: DriveFile[] = items.map((f: DriveItem) => {\n const id = f?.id ? String(f.id) : 'unknown';\n const name = f?.name || id;\n const result: DriveFile = { id, name };\n\n // Only include properties that have actual values\n if (f?.mimeType) result.mimeType = f.mimeType;\n if (f?.webViewLink) result.webViewLink = f.webViewLink;\n if (f?.modifiedTime) result.modifiedTime = f.modifiedTime;\n\n // 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 return result;\n });\n\n const filteredItems = driveFiles.map((item) => filterFields(item, requestedFields));\n\n logger.info('drive.folder.contents returning', {\n folderId,\n resultCount: filteredItems.length,\n fields: fields || 'all',\n });\n\n const nextPageToken = res.nextPageToken && res.nextPageToken.trim().length > 0 ? res.nextPageToken : undefined;\n\n // Build result based on shape\n const result: Output =\n shape === 'arrays'\n ? {\n type: 'success' as const,\n shape: 'arrays' as const,\n ...toColumnarFormat(filteredItems, requestedFields, DRIVE_FILE_FIELDS),\n count: filteredItems.length,\n folderId,\n ...(nextPageToken && { nextPageToken }),\n }\n : {\n type: 'success' as const,\n shape: 'objects' as const,\n items: filteredItems,\n count: filteredItems.length,\n folderId,\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.contents error', { error: message });\n\n // Throw ProtocolError\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error listing folder contents: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'folder-contents' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","folderId","string","min","describe","fields","createFieldsSchema","availableFields","DRIVE_FILE_FIELDS","fieldDescriptions","DRIVE_FILE_FIELD_DESCRIPTIONS","commonPatterns","DRIVE_FILE_COMMON_PATTERNS","resourceName","createPaginationSchema","defaultPageSize","maxPageSize","provider","shape","createShapeSchema","successObjectsBranchSchema","type","literal","items","array","DriveFileSchema","count","number","nextPageToken","optional","successArraysBranchSchema","columns","rows","unknown","outputSchema","union","config","title","description","result","handler","extra","pageSize","pageToken","logger","requestedFields","drive","qStr","listOptions","response","res","parentIds","f","parentId","parentNameMap","parentFetches","driveFiles","filteredItems","error","message","parseFields","info","undefined","driveApi","version","auth","googleAuth","authContext","q","Math","orderBy","corpora","supportsAllDrives","includeItemsFromAllDrives","trim","length","files","list","data","Array","isArray","Set","parents","add","Map","size","from","map","parentRes","parentName","e","get","fileId","name","set","Promise","all","id","String","mimeType","webViewLink","modifiedTime","shared","starred","owners","o","owner","displayName","emailAddress","kind","me","permissionId","photoLink","item","filterFields","resultCount","toColumnarFormat","content","text","JSON","stringify","structuredContent","Error","ProtocolError","ProtocolErrorCode","InternalError","stack"],"mappings":";;;;+BA+PA;;;eAAwBA;;;2BA9PA;qBAIU;sBACgJ;mBAChK;4BACS;uBACmG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAN9H,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAQR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,UAAU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M;wBACjCtE,QAAQA,UAAU;oBACpB;oBAEMuB,gBAAgBsB,IAAItB,aAAa,IAAIsB,IAAItB,aAAa,CAAC8C,IAAI,GAAGC,MAAM,GAAG,IAAIzB,IAAItB,aAAa,GAAGkC;oBAErG,8BAA8B;oBACxBvB,SACJrB,UAAU,WACN;wBACEG,MAAM;wBACNH,OAAO;uBACJkG,IAAAA,wBAAgB,EAAC3D,eAAeZ,iBAAiBrC,0BAAiB;wBACrEkB,OAAO+B,cAAckB,MAAM;wBAC3B1E,UAAAA;wBACI2B,iBAAiB;wBAAEA,eAAAA;oBAAc,KAEvC;wBACEP,MAAM;wBACNH,OAAO;wBACPK,OAAOkC;wBACP/B,OAAO+B,cAAckB,MAAM;wBAC3B1E,UAAAA;uBACI2B,iBAAiB;wBAAEA,eAAAA;oBAAc;oBAG7C;;wBAAO;4BACLyF,OAAO;gCACL;oCACEhG,MAAM;oCACNiG,MAAMC,KAAKC,SAAS,CAACjF;gCACvB;;4BAEFkF,mBAAmB;gCAAElF,QAAAA;4BAAO;wBAC9B;;;oBACOmB;oBACDC,UAAUD,AAAK,YAALA,OAAiBgE,SAAQhE,MAAMC,OAAO,GAAGuC,OAAOxC;oBAChEd,OAAOc,KAAK,CAAC,+BAA+B;wBAAEA,OAAOC;oBAAQ;oBAE7D,sBAAsB;oBACtB,MAAM,IAAIgE,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,kCAAyC,OAARlE,UAAW;wBACpGmE,OAAOpE,AAAK,YAALA,OAAiBgE,SAAQhE,MAAMoE,KAAK,GAAGhE;oBAChD;;;;;;;IAEJ;;AAEe,SAASnE;IACtB,OAAO;QACLkG,MAAM;QACNzD,QAAAA;QACAI,SAAAA;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-drive/src/mcp/tools/folder-create.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { drive as driveApi } from '@googleapis/drive';\nimport type { CallToolResult } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\n\nconst inputSchema = z.object({\n name: z.string().trim().min(1).describe('Name for the new folder'),\n parentId: z.string().optional().describe('Parent folder ID (omit to create in My Drive root)'),\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n operationSummary: z.string().describe('Summary of the folder creation operation'),\n itemsProcessed: z.number().describe('Total items attempted (always 1 for single folder)'),\n itemsChanged: z.number().describe('Successfully created folders (always 1 on success)'),\n completedAt: z.string().describe('ISO datetime when operation completed'),\n id: z.string().describe('ID of the created folder'),\n name: z.string().describe('Name of the created folder'),\n webViewLink: z.string().describe('URL to view the folder in Drive'),\n parentId: z.string().optional().describe('ID of the parent folder'),\n parentName: z.string().optional().describe('Name of the parent folder'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n title: 'Create Folder',\n description: 'Create a new folder in Google Drive. Returns folder ID for use in other operations.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\n// Export types for strong typing in tests\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ name: folderName, parentId }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('drive.folder.create called', {\n name: folderName,\n parentId: parentId || 'root',\n });\n\n try {\n const drive = driveApi({ version: 'v3', auth: googleAuth(extra.authContext.auth) });\n\n // Folder MIME type constant (consistent with folder-search.ts)\n const folderMimeType = 'application/vnd.google-apps.folder';\n\n // Create the folder\n const response = await drive.files.create({\n requestBody: {\n name: folderName,\n mimeType: folderMimeType,\n parents: parentId ? [parentId] : null,\n },\n fields: 'id,name,webViewLink,parents',\n supportsAllDrives: true,\n });\n\n const res = response.data;\n const id = res.id ?? '';\n const name = res.name ?? folderName;\n const webViewLink = res.webViewLink ?? '';\n const parents = (res.parents as string[] | undefined) || [];\n\n // Fetch parent name if parentId was provided\n let parentName: string | undefined;\n let actualParentId: string | undefined;\n\n if (parents.length > 0) {\n actualParentId = parents[0];\n\n if (actualParentId === 'root') {\n parentName = 'My Drive';\n } else if (actualParentId) {\n try {\n const parentResponse = await drive.files.get({\n fileId: actualParentId,\n fields: 'name',\n supportsAllDrives: true,\n });\n parentName = (parentResponse.data.name as string | undefined) || actualParentId;\n } catch (e) {\n logger.info('Failed to fetch parent name', {\n parentId: actualParentId,\n error: e,\n });\n parentName = actualParentId; // Fallback to ID\n }\n }\n }\n\n const locationSummary = parentName ? ` in \"${parentName}\"` : ' in My Drive';\n\n logger.info('drive.folder.create success', {\n id,\n name,\n parentId: actualParentId,\n });\n\n // Build result object with operation metadata\n const result: Output = {\n type: 'success' as const,\n operationSummary: `Created folder \"${name}\"${locationSummary}`,\n itemsProcessed: 1,\n itemsChanged: 1,\n completedAt: new Date().toISOString(),\n id,\n name,\n webViewLink,\n ...(actualParentId && { parentId: actualParentId }),\n ...(parentName && { parentName }),\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('drive.folder.create error', { error: message });\n\n // Throw ProtocolError for proper MCP error handling\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error creating folder: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'folder-create' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","name","string","trim","min","describe","parentId","optional","successBranchSchema","type","literal","operationSummary","itemsProcessed","number","itemsChanged","completedAt","id","webViewLink","parentName","outputSchema","discriminatedUnion","config","title","description","result","handler","extra","folderName","logger","res","drive","folderMimeType","response","parents","actualParentId","parentResponse","e","locationSummary","error","message","info","driveApi","version","auth","googleAuth","authContext","files","create","requestBody","mimeType","fields","supportsAllDrives","data","length","get","fileId","Date","toISOString","content","text","JSON","stringify","structuredContent","Error","String","ProtocolError","ProtocolErrorCode","InternalError","stack","undefined"],"mappings":";;;;+BAiJA;;;eAAwBA;;;2BAhJA;qBAIU;sBAEe;mBAC/B;4BACS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAN3B,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAQR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,MAAMF,MAAC,CAACG,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IACxCC,UAAUP,MAAC,CAACG,MAAM,GAAGK,QAAQ,GAAGF,QAAQ,CAAC;AAC3C;AAEA,wBAAwB;AACxB,IAAMG,sBAAsBT,MAAC,CAACC,MAAM,CAAC;IACnCS,MAAMV,MAAC,CAACW,OAAO,CAAC;IAChBC,kBAAkBZ,MAAC,CAACG,MAAM,GAAGG,QAAQ,CAAC;IACtCO,gBAAgBb,MAAC,CAACc,MAAM,GAAGR,QAAQ,CAAC;IACpCS,cAAcf,MAAC,CAACc,MAAM,GAAGR,QAAQ,CAAC;IAClCU,aAAahB,MAAC,CAACG,MAAM,GAAGG,QAAQ,CAAC;IACjCW,IAAIjB,MAAC,CAACG,MAAM,GAAGG,QAAQ,CAAC;IACxBJ,MAAMF,MAAC,CAACG,MAAM,GAAGG,QAAQ,CAAC;IAC1BY,aAAalB,MAAC,CA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;wBAC9B;;;oBACOc;oBACDC,UAAUD,AAAK,YAALA,OAAiByB,SAAQzB,MAAMC,OAAO,GAAGyB,OAAO1B;oBAChEV,OAAOU,KAAK,CAAC,6BAA6B;wBAAEA,OAAOC;oBAAQ;oBAE3D,oDAAoD;oBACpD,MAAM,IAAI0B,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,0BAAiC,OAAR5B,UAAW;wBAC5F6B,OAAO9B,AAAK,YAALA,OAAiByB,SAAQzB,MAAM8B,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAAS1E;IACtB,OAAO;QACLM,MAAM;QACNoB,QAAAA;QACAI,SAAAA;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-drive/src/mcp/tools/folder-path.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { drive_v3 } from '@googleapis/drive';\nimport { drive as driveApi } from '@googleapis/drive';\nimport { type CallToolResult, ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport type { Logger } from '../../types.ts';\n\nconst inputSchema = z.object({\n folderId: z.string().min(1).describe('Folder ID to get path for (or \"root\")'),\n});\n\n// Success branch schema - uses items: for consistency with standard vocabulary\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n path: z.string().describe('Full path from root (e.g., /Work/Projects/2024)'),\n items: z\n .array(\n z.object({\n id: z.string().describe('Folder ID'),\n name: z.string().describe('Folder name'),\n })\n )\n .describe('Path items from root to target folder'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n title: 'Get Folder Path',\n description: 'Get full path from folder to root. Returns human-readable path and items with IDs.',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\n/**\n * Resolves the full path for a folder by walking up the parent chain.\n * Returns both the path string and structured segments with IDs and names.\n */\nasync function resolveFolderPath(drive: drive_v3.Drive, folderId: string, logger: Logger): Promise<{ path: string; segments: Array<{ id: string; name: string }> }> {\n // Handle root specially\n if (folderId === 'root') {\n return {\n path: '/',\n segments: [{ id: 'root', name: 'My Drive' }],\n };\n }\n\n const segments: Array<{ id: string; name: string }> = [];\n let currentId = folderId;\n const visited = new Set<string>();\n\n // Walk up the parent chain\n while (currentId && currentId !== 'root') {\n // Prevent infinite loops\n if (visited.has(currentId)) {\n logger.info('Circular folder reference detected', {\n folderId: currentId,\n });\n break;\n }\n visited.add(currentId);\n\n // Fetch folder metadata\n try {\n const response = await drive.files.get({\n fileId: currentId,\n fields: 'id,name,parents',\n supportsAllDrives: true,\n });\n\n const id = response.data.id as string;\n const name = (response.data.name as string) || id;\n const parents = response.data.parents as string[] | undefined;\n\n // Add to segments at beginning (we're walking from child to root)\n segments.unshift({ id, name });\n\n // Move to parent\n currentId = (parents && parents.length > 0 ? parents[0] : '') || '';\n } catch (e) {\n logger.info('Failed to resolve folder path', {\n folderId: currentId,\n error: e,\n });\n break;\n }\n }\n\n // Add root if we reached it\n if (currentId === 'root') {\n segments.unshift({ id: 'root', name: 'My Drive' });\n }\n\n // Build path string\n const pathParts = segments.slice(1).map((seg) => seg.name); // Skip root\n const path = pathParts.length > 0 ? `/${pathParts.join('/')}` : '/';\n\n return { path, segments };\n}\n\nasync function handler({ folderId }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('drive.folder.path called', { folderId });\n\n try {\n const drive = driveApi({ version: 'v3', auth: googleAuth(extra.authContext.auth) });\n\n const pathResult = await resolveFolderPath(drive, folderId, logger);\n\n logger.info('drive.folder.path returning', {\n path: pathResult.path,\n segmentCount: pathResult.segments.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n path: pathResult.path,\n items: pathResult.segments,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('drive.folder.path error', { error: message });\n\n // Throw ProtocolError\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error getting folder path: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'folder-path' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","folderId","string","min","describe","successBranchSchema","type","literal","path","items","array","id","name","outputSchema","discriminatedUnion","config","title","description","result","resolveFolderPath","drive","logger","segments","currentId","visited","response","parents","e","pathParts","Set","has","info","add","files","get","fileId","fields","supportsAllDrives","data","unshift","length","error","slice","map","seg","join","handler","extra","pathResult","message","driveApi","version","auth","googleAuth","authContext","segmentCount","content","text","JSON","stringify","structuredContent","Error","String","ProtocolError","ProtocolErrorCode","InternalError","stack","undefined"],"mappings":";;;;+BAuJA;;;eAAwBA;;;2BAtJA;qBAKU;sBACoC;mBACpD;4BACS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAN3B,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AASR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,UAAUF,MAAC,CAACG,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;AACvC;AAEA,+EAA+E;AAC/E,IAAMC,sBAAsBN,MAAC,CAACC,MAAM,CAAC;IACnCM,MAAMP,MAAC,CA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WAAWxC,IAAI;wBACrB+C,cAAcP,WAAW1B,QAAQ,CAACkB,MAAM;oBAC1C;oBAEMtB,SAAiB;wBACrBZ,MAAM;wBACNE,MAAMwC,WAAWxC,IAAI;wBACrBC,OAAOuC,WAAW1B,QAAQ;oBAC5B;oBAEA;;wBAAO;4BACLkC,OAAO;gCACL;oCACElD,MAAM;oCACNmD,MAAMC,KAAKC,SAAS,CAACzC;gCACvB;;4BAEF0C,mBAAmB;gCAAE1C,QAAAA;4BAAO;wBAC9B;;;oBACOuB;oBACDQ,UAAUR,AAAK,YAALA,OAAiBoB,SAAQpB,MAAMQ,OAAO,GAAGa,OAAOrB;oBAChEpB,OAAOoB,KAAK,CAAC,2BAA2B;wBAAEA,OAAOQ;oBAAQ;oBAEzD,sBAAsB;oBACtB,MAAM,IAAIc,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,8BAAqC,OAARhB,UAAW;wBAChGiB,OAAOzB,AAAK,YAALA,OAAiBoB,SAAQpB,MAAMyB,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAASxE;IACtB,OAAO;QACLiB,MAAM;QACNG,QAAAA;QACA+B,SAAAA;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/tools/folder-search.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { drive_v3 } from '@googleapis/drive';\nimport { drive as driveApi } from '@googleapis/drive';\nimport { type CallToolResult, createFieldsSchema, createPaginationSchema, createShapeSchema, filterFields, ProtocolError, ProtocolErrorCode, parseFields, toColumnarFormat } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { toDriveQuery } from '../../lib/query-builder.ts';\nimport { DRIVE_FILE_COMMON_PATTERNS, DRIVE_FILE_FIELD_DESCRIPTIONS, DRIVE_FILE_FIELDS, type DriveFile, DriveFileSchema, DriveQueryParameterSchema, parseDriveQueryParameter } from '../../schemas/index.ts';\nimport type { Logger } from '../../types.ts';\n\nconst inputSchema = z.object({\n query: DriveQueryParameterSchema.optional().describe('Structured Drive query object or JSON string. Use rawDriveQuery for raw Drive syntax.'),\n fields: createFieldsSchema({\n availableFields: [...DRIVE_FILE_FIELDS, 'path'] as const,\n fieldDescriptions: {\n ...DRIVE_FILE_FIELD_DESCRIPTIONS,\n path: 'Full folder path like /Work/Projects (requires resolvePaths=true)',\n },\n commonPatterns: DRIVE_FILE_COMMON_PATTERNS,\n resourceName: 'Drive folder',\n }),\n resolvePaths: z.boolean().optional().describe('Resolve full folder paths like /Work/Projects/2024 (requires additional API calls per result)'),\n ...createPaginationSchema({\n defaultPageSize: 50,\n maxPageSize: 1000,\n provider: 'drive',\n }).shape,\n shape: createShapeSchema(),\n});\n\n// Success branch schemas for different shapes\nconst successObjectsBranchSchema = z.object({\n type: z.literal('success'),\n shape: z.literal('objects'),\n items: z.array(DriveFileSchema.extend({ path: z.string().optional().describe('Full folder path (if resolvePaths=true)') })).describe('Matching Drive folders'),\n count: z.number().describe('Number of folders in this page'),\n nextPageToken: z.string().optional().describe('Token for fetching next page of results'),\n});\n\nconst successArraysBranchSchema = z.object({\n type: z.literal('success'),\n shape: z.literal('arrays'),\n columns: z.array(z.string()).describe('Column names in canonical order'),\n rows: z.array(z.array(z.unknown())).describe('Row data matching column order'),\n count: z.number().describe('Number of folders in this page'),\n nextPageToken: z.string().optional().describe('Token for fetching next page of results'),\n});\n\n// Output schema with auth_required support\n// Using z.union instead of discriminatedUnion since we have two success branches with different shapes\nconst outputSchema = z.union([successObjectsBranchSchema, successArraysBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n title: 'Search Folders',\n description: 'Search Google Drive folders with flexible field selection and optional path resolution.',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\n// Type for the raw Google Drive API response\ntype DriveFolder = {\n id?: string;\n name?: string;\n mimeType?: string;\n webViewLink?: string;\n modifiedTime?: string;\n parents?: string[];\n shared?: boolean;\n starred?: boolean;\n owners?: Array<{\n displayName?: string;\n emailAddress?: string;\n kind?: string;\n me?: boolean;\n permissionId?: string;\n photoLink?: string;\n }>;\n};\n\ntype DriveFolderResponse = {\n files?: DriveFolder[];\n nextPageToken?: string;\n};\n\n/**\n * Resolves the full path for a folder by walking up the parent chain\n * Caches folder names to reduce redundant API calls\n */\nasync function resolveFolderPath(drive: drive_v3.Drive, folderId: string, folderCache: Map<string, string>, logger: Logger): Promise<string> {\n if (folderId === 'root') return '/';\n\n const pathParts: string[] = [];\n let currentId = folderId;\n const visited = new Set<string>();\n\n while (currentId && currentId !== 'root') {\n // Prevent infinite loops\n if (visited.has(currentId)) {\n logger.info('Circular folder reference detected', {\n folderId: currentId,\n });\n break;\n }\n visited.add(currentId);\n\n // Check cache first\n if (folderCache.has(currentId)) {\n const cachedName = folderCache.get(currentId);\n if (cachedName) {\n pathParts.unshift(cachedName);\n }\n\n // Get parent of cached folder\n try {\n const response = await drive.files.get({\n fileId: currentId,\n fields: 'parents',\n supportsAllDrives: true,\n });\n const parents = response.data.parents as string[] | undefined;\n currentId = (parents && parents.length > 0 ? parents[0] : '') || '';\n } catch (_e) {\n logger.info('Failed to get parent for cached folder', {\n folderId: currentId,\n });\n break;\n }\n } else {\n // Fetch folder metadata\n try {\n const response = await drive.files.get({\n fileId: currentId,\n fields: 'name,parents',\n supportsAllDrives: true,\n });\n const folderName = response.data.name as string | undefined;\n const parents = response.data.parents as string[] | undefined;\n\n if (folderName) {\n folderCache.set(currentId, folderName);\n pathParts.unshift(folderName);\n }\n\n currentId = (parents && parents.length > 0 ? parents[0] : '') || '';\n } catch (e) {\n logger.info('Failed to resolve folder path', {\n folderId: currentId,\n error: e,\n });\n break;\n }\n }\n }\n\n return `/${pathParts.join('/')}`;\n}\n\nasync function handler({ query, resolvePaths = false, pageSize = 50, pageToken, fields, shape = 'arrays' }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n\n try {\n const parsedQuery = parseDriveQueryParameter(query);\n const requestedFields = parseFields(fields, [...DRIVE_FILE_FIELDS, 'path'] as const);\n\n // Validate and clamp pageSize to Google Drive API limits (1-1000)\n const validPageSize = Math.max(1, Math.min(1000, Math.floor(pageSize || 50)));\n\n logger.info('drive.folder.search called', {\n query: parsedQuery,\n resolvePaths,\n pageSize: validPageSize,\n pageToken: pageToken ? '[provided]' : undefined,\n fields: fields || 'all',\n });\n\n const drive = driveApi({ version: 'v3', auth: googleAuth(extra.authContext.auth) });\n\n const folderMimeType = 'application/vnd.google-apps.folder';\n let qStr: string;\n\n if (parsedQuery && 'rawDriveQuery' in parsedQuery && parsedQuery.rawDriveQuery) {\n // Object with rawDriveQuery field - use it directly\n qStr = parsedQuery.rawDriveQuery;\n } else if (parsedQuery) {\n // Structured query object - convert to Drive query string\n const { q } = toDriveQuery(parsedQuery);\n qStr = q || '';\n } else {\n qStr = '';\n }\n\n qStr = qStr ? `(${qStr}) and mimeType='${folderMimeType}'` : `mimeType='${folderMimeType}'`;\n\n const listOptions: {\n q: string;\n pageSize: number;\n fields: string;\n orderBy: string;\n pageToken?: string;\n corpora: string;\n supportsAllDrives: boolean;\n includeItemsFromAllDrives: boolean;\n } = {\n q: qStr,\n pageSize: validPageSize,\n fields: 'files(id,name,mimeType,webViewLink,modifiedTime,parents,shared,starred,owners),nextPageToken',\n orderBy: 'modifiedTime desc',\n // All three are load-bearing for shared drives: the default `user` corpus omits\n // them, and Drive rejects an `allDrives` corpus unless both flags are set too.\n corpora: 'allDrives',\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n };\n if (pageToken && pageToken.trim().length > 0) {\n listOptions.pageToken = pageToken;\n }\n\n const response = await drive.files.list(listOptions);\n\n const res = response.data as DriveFolderResponse;\n const folders = Array.isArray(res?.files) ? res.files : [];\n\n const parentIds = new Set<string>();\n for (const f of folders) {\n if (f?.parents && f.parents.length > 0) {\n for (const parentId of f.parents) {\n if (parentId && parentId !== 'root') {\n parentIds.add(parentId);\n }\n }\n }\n }\n\n const parentNameMap = new Map<string, string>();\n if (parentIds.size > 0) {\n logger.info('Fetching parent names', { count: parentIds.size });\n const parentFetches = Array.from(parentIds).map(async (parentId) => {\n try {\n const parentRes = await drive.files.get({\n fileId: parentId,\n fields: 'id,name',\n supportsAllDrives: true,\n });\n const parentName = (parentRes.data.name as string | undefined) || parentId;\n parentNameMap.set(parentId, parentName);\n } catch (e) {\n logger.info('Failed to fetch parent name', { parentId, error: e });\n parentNameMap.set(parentId, parentId); // Fallback to ID\n }\n });\n await Promise.all(parentFetches);\n }\n\n // Cache for folder names to reduce API calls during path resolution\n const folderCache = new Map<string, string>();\n\n const items: (DriveFile & { path?: string })[] = await Promise.all(\n folders.map(async (f: DriveFolder) => {\n const id = f?.id ? String(f.id) : 'unknown';\n const name = f?.name || id;\n const result: DriveFile & { path?: string } = { id, name };\n\n // Only include properties that have actual values\n if (f?.mimeType) result.mimeType = f.mimeType;\n if (f?.webViewLink) result.webViewLink = f.webViewLink;\n if (f?.modifiedTime) result.modifiedTime = f.modifiedTime;\n\n // Build parent objects with names\n if (f?.parents && f.parents.length > 0) {\n result.parents = f.parents.map((parentId) => {\n if (parentId === 'root') {\n return { id: 'root', name: 'My Drive' };\n }\n const parentName = parentNameMap.get(parentId) || parentId;\n return { id: parentId, name: parentName };\n });\n }\n\n if (f?.shared !== undefined) result.shared = f.shared;\n if (f?.starred !== undefined) result.starred = f.starred;\n\n if (f?.owners && f.owners.length > 0) {\n result.owners = f.owners.map((o) => {\n const owner: NonNullable<DriveFile['owners']>[number] = {};\n if (o?.displayName) owner.displayName = o.displayName;\n if (o?.emailAddress) owner.emailAddress = o.emailAddress;\n if (o?.kind) owner.kind = o.kind;\n if (o?.me !== undefined) owner.me = o.me;\n if (o?.permissionId) owner.permissionId = o.permissionId;\n if (o?.photoLink) owner.photoLink = o.photoLink;\n return owner;\n });\n }\n\n // Resolve path if requested\n if (resolvePaths && id !== 'unknown') {\n result.path = await resolveFolderPath(drive, id, folderCache, logger);\n }\n\n return result;\n })\n );\n\n const filteredItems = items.map((item) => filterFields(item, requestedFields));\n\n logger.info('drive.folder.search returning', {\n query: parsedQuery,\n pageSize,\n resultCount: filteredItems.length,\n resolvePaths,\n fields: fields || 'all',\n });\n\n const nextPageToken = res.nextPageToken && res.nextPageToken.trim().length > 0 ? res.nextPageToken : undefined;\n\n // Build result based on shape\n const result: Output =\n shape === 'arrays'\n ? {\n type: 'success' as const,\n shape: 'arrays' as const,\n ...toColumnarFormat(filteredItems, requestedFields, [...DRIVE_FILE_FIELDS, 'path'] as const),\n count: filteredItems.length,\n ...(nextPageToken && { nextPageToken }),\n }\n : {\n type: 'success' as const,\n shape: 'objects' as const,\n items: filteredItems,\n count: filteredItems.length,\n ...(nextPageToken && { nextPageToken }),\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('drive.folder.search error', { error: message });\n\n // Throw ProtocolError for all errors so callers can see Drive validation details\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error searching folders: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'folder-search' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","query","DriveQueryParameterSchema","optional","describe","fields","createFieldsSchema","availableFields","DRIVE_FILE_FIELDS","fieldDescriptions","DRIVE_FILE_FIELD_DESCRIPTIONS","path","commonPatterns","DRIVE_FILE_COMMON_PATTERNS","resourceName","resolvePaths","boolean","createPaginationSchema","defaultPageSize","maxPageSize","provider","shape","createShapeSchema","successObjectsBranchSchema","type","literal","items","array","DriveFileSchema","extend","string","count","number","nextPageToken","successArraysBranchSchema","columns","rows","unknown","outputSchema","union","config","title","description","result","resolveFolderPath","drive","folderId","folderCache","logger","pathParts","currentId","visited","cachedName","response","parents","_e","folderName","e","Set","has","info","add","get","unshift","files","fileId","supportsAllDrives","data","length","name","set","error","join","handler","extra","pageSize","pageToken","parsedQuery","requestedFields","validPageSize","folderMimeType","qStr","q","listOptions","res","folders","parentIds","f","parentId","parentNameMap","parentFetches","filteredItems","message","parseDriveQueryParameter","parseFields","Math","max","min","floor","undefined","driveApi","version","auth","googleAuth","authContext","rawDriveQuery","toDriveQuery","orderBy","corpora","includeItemsFromAllDrives","trim","list","Array","isArray","Map","size","from","map","parentRes","parentName","Promise","all","id","String","mimeType","webViewLink","modifiedTime","shared","starred","owners","o","owner","displayName","emailAddress","kind","me","permissionId","photoLink","item","filterFields","resultCount","toColumnarFormat","content","text","JSON","stringify","structuredContent","Error","ProtocolError","ProtocolErrorCode","InternalError","stack"],"mappings":";;;;+BA0WA;;;eAAwBA;;;2BAzWA;qBAKU;sBACgJ;mBAChK;4BACS;8BACE;uBACsJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AARnL,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAWR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,OAAOC,kCAAyB,CAACC,QAAQ,GAAGC,QAAQ,CAAC;IACrDC,QAAQC,IAAAA,0BAAkB,EAAC;QACzBC,iBAAiB,AAAC,qBAAGC,0BAAiB,SAArB;YAAuB;SAAO;QAC/CC,mBAAmB,wCACdC,sCAA6B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AAInD,aAAa,GAAGkE;oBAErG,8BAA8B;oBACxBxD,SACJtB,UAAU,WACN;wBACEG,MAAM;wBACNH,OAAO;uBACJwH,IAAAA,wBAAgB,EAAClD,eAAeb,iBAAiB,AAAC,qBAAGtE,0BAAiB;wBAAE;;wBAC3EuB,OAAO4D,cAAcvB,MAAM;wBACvBnC,iBAAiB;wBAAEA,eAAAA;oBAAc,KAEvC;wBACET,MAAM;wBACNH,OAAO;wBACPK,OAAOiE;wBACP5D,OAAO4D,cAAcvB,MAAM;uBACvBnC,iBAAiB;wBAAEA,eAAAA;oBAAc;oBAG7C;;wBAAO;4BACL6G,OAAO;gCACL;oCACEtH,MAAM;oCACNuH,MAAMC,KAAKC,SAAS,CAACtG;gCACvB;;4BAEFuG,mBAAmB;gCAAEvG,QAAAA;4BAAO;wBAC9B;;;oBACO4B;oBACDqB,UAAUrB,AAAK,YAALA,OAAiB4E,SAAQ5E,MAAMqB,OAAO,GAAG+B,OAAOpD;oBAChEvB,OAAOuB,KAAK,CAAC,6BAA6B;wBAAEA,OAAOqB;oBAAQ;oBAE3D,iFAAiF;oBACjF,MAAM,IAAIwD,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,4BAAmC,OAAR1D,UAAW;wBAC9F2D,OAAOhF,AAAK,YAALA,OAAiB4E,SAAQ5E,MAAMgF,KAAK,GAAGpD;oBAChD;;;;;;;IAEJ;;AAEe,SAASxG;IACtB,OAAO;QACL0E,MAAM;QACN7B,QAAAA;QACAiC,SAAAA;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-drive/src/mcp/tools/folder-search.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { drive_v3 } from '@googleapis/drive';\nimport { drive as driveApi } from '@googleapis/drive';\nimport { type CallToolResult, createFieldsSchema, createPaginationSchema, createShapeSchema, filterFields, ProtocolError, ProtocolErrorCode, parseFields, toColumnarFormat } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { toDriveQuery } from '../../lib/query-builder.ts';\nimport { DRIVE_FILE_COMMON_PATTERNS, DRIVE_FILE_FIELD_DESCRIPTIONS, DRIVE_FILE_FIELDS, type DriveFile, DriveFileSchema, DriveQueryParameterSchema, parseDriveQueryParameter } from '../../schemas/index.ts';\nimport type { Logger } from '../../types.ts';\n\nconst inputSchema = z.object({\n query: DriveQueryParameterSchema.optional().describe('Structured Drive query object or JSON string. Use rawDriveQuery for raw Drive syntax.'),\n fields: createFieldsSchema({\n availableFields: [...DRIVE_FILE_FIELDS, 'path'] as const,\n fieldDescriptions: {\n ...DRIVE_FILE_FIELD_DESCRIPTIONS,\n path: 'Full folder path like /Work/Projects (requires resolvePaths=true)',\n },\n commonPatterns: DRIVE_FILE_COMMON_PATTERNS,\n resourceName: 'Drive folder',\n }),\n resolvePaths: z.boolean().optional().describe('Resolve full folder paths like /Work/Projects/2024 (requires additional API calls per result)'),\n ...createPaginationSchema({\n defaultPageSize: 50,\n maxPageSize: 1000,\n provider: 'drive',\n }).shape,\n shape: createShapeSchema(),\n});\n\n// Success branch schemas for different shapes\nconst successObjectsBranchSchema = z.object({\n type: z.literal('success'),\n shape: z.literal('objects'),\n items: z.array(DriveFileSchema.extend({ path: z.string().optional().describe('Full folder path (if resolvePaths=true)') })).describe('Matching Drive folders'),\n count: z.number().describe('Number of folders in this page'),\n nextPageToken: z.string().optional().describe('Token for fetching next page of results'),\n});\n\nconst successArraysBranchSchema = z.object({\n type: z.literal('success'),\n shape: z.literal('arrays'),\n columns: z.array(z.string()).describe('Column names in canonical order'),\n rows: z.array(z.array(z.unknown())).describe('Row data matching column order'),\n count: z.number().describe('Number of folders in this page'),\n nextPageToken: z.string().optional().describe('Token for fetching next page of results'),\n});\n\n// Output schema with auth_required support\n// Using z.union instead of discriminatedUnion since we have two success branches with different shapes\nconst outputSchema = z.union([successObjectsBranchSchema, successArraysBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n title: 'Search Folders',\n description: 'Search Google Drive folders with flexible field selection and optional path resolution.',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\n// Type for the raw Google Drive API response\ntype DriveFolder = {\n id?: string;\n name?: string;\n mimeType?: string;\n webViewLink?: string;\n modifiedTime?: string;\n parents?: string[];\n shared?: boolean;\n starred?: boolean;\n owners?: Array<{\n displayName?: string;\n emailAddress?: string;\n kind?: string;\n me?: boolean;\n permissionId?: string;\n photoLink?: string;\n }>;\n};\n\ntype DriveFolderResponse = {\n files?: DriveFolder[];\n nextPageToken?: string;\n};\n\n/**\n * Resolves the full path for a folder by walking up the parent chain\n * Caches folder names to reduce redundant API calls\n */\nasync function resolveFolderPath(drive: drive_v3.Drive, folderId: string, folderCache: Map<string, string>, logger: Logger): Promise<string> {\n if (folderId === 'root') return '/';\n\n const pathParts: string[] = [];\n let currentId = folderId;\n const visited = new Set<string>();\n\n while (currentId && currentId !== 'root') {\n // Prevent infinite loops\n if (visited.has(currentId)) {\n logger.info('Circular folder reference detected', {\n folderId: currentId,\n });\n break;\n }\n visited.add(currentId);\n\n // Check cache first\n if (folderCache.has(currentId)) {\n const cachedName = folderCache.get(currentId);\n if (cachedName) {\n pathParts.unshift(cachedName);\n }\n\n // Get parent of cached folder\n try {\n const response = await drive.files.get({\n fileId: currentId,\n fields: 'parents',\n supportsAllDrives: true,\n });\n const parents = response.data.parents as string[] | undefined;\n currentId = (parents && parents.length > 0 ? parents[0] : '') || '';\n } catch (_e) {\n logger.info('Failed to get parent for cached folder', {\n folderId: currentId,\n });\n break;\n }\n } else {\n // Fetch folder metadata\n try {\n const response = await drive.files.get({\n fileId: currentId,\n fields: 'name,parents',\n supportsAllDrives: true,\n });\n const folderName = response.data.name as string | undefined;\n const parents = response.data.parents as string[] | undefined;\n\n if (folderName) {\n folderCache.set(currentId, folderName);\n pathParts.unshift(folderName);\n }\n\n currentId = (parents && parents.length > 0 ? parents[0] : '') || '';\n } catch (e) {\n logger.info('Failed to resolve folder path', {\n folderId: currentId,\n error: e,\n });\n break;\n }\n }\n }\n\n return `/${pathParts.join('/')}`;\n}\n\nasync function handler({ query, resolvePaths = false, pageSize = 50, pageToken, fields, shape = 'arrays' }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n\n try {\n const parsedQuery = parseDriveQueryParameter(query);\n const requestedFields = parseFields(fields, [...DRIVE_FILE_FIELDS, 'path'] as const);\n\n // Validate and clamp pageSize to Google Drive API limits (1-1000)\n const validPageSize = Math.max(1, Math.min(1000, Math.floor(pageSize || 50)));\n\n logger.info('drive.folder.search called', {\n query: parsedQuery,\n resolvePaths,\n pageSize: validPageSize,\n pageToken: pageToken ? '[provided]' : undefined,\n fields: fields || 'all',\n });\n\n const drive = driveApi({ version: 'v3', auth: googleAuth(extra.authContext.auth) });\n\n const folderMimeType = 'application/vnd.google-apps.folder';\n let qStr: string;\n\n if (parsedQuery && 'rawDriveQuery' in parsedQuery && parsedQuery.rawDriveQuery) {\n // Object with rawDriveQuery field - use it directly\n qStr = parsedQuery.rawDriveQuery;\n } else if (parsedQuery) {\n // Structured query object - convert to Drive query string\n const { q } = toDriveQuery(parsedQuery);\n qStr = q || '';\n } else {\n qStr = '';\n }\n\n qStr = qStr ? `(${qStr}) and mimeType='${folderMimeType}'` : `mimeType='${folderMimeType}'`;\n\n const listOptions: {\n q: string;\n pageSize: number;\n fields: string;\n orderBy: string;\n pageToken?: string;\n corpora: string;\n supportsAllDrives: boolean;\n includeItemsFromAllDrives: boolean;\n } = {\n q: qStr,\n pageSize: validPageSize,\n fields: 'files(id,name,mimeType,webViewLink,modifiedTime,parents,shared,starred,owners),nextPageToken',\n orderBy: 'modifiedTime desc',\n // All three are load-bearing for shared drives: the default `user` corpus omits\n // them, and Drive rejects an `allDrives` corpus unless both flags are set too.\n corpora: 'allDrives',\n supportsAllDrives: true,\n includeItemsFromAllDrives: true,\n };\n if (pageToken && pageToken.trim().length > 0) {\n listOptions.pageToken = pageToken;\n }\n\n const response = await drive.files.list(listOptions);\n\n const res = response.data as DriveFolderResponse;\n const folders = Array.isArray(res?.files) ? res.files : [];\n\n const parentIds = new Set<string>();\n for (const f of folders) {\n if (f?.parents && f.parents.length > 0) {\n for (const parentId of f.parents) {\n if (parentId && parentId !== 'root') {\n parentIds.add(parentId);\n }\n }\n }\n }\n\n const parentNameMap = new Map<string, string>();\n if (parentIds.size > 0) {\n logger.info('Fetching parent names', { count: parentIds.size });\n const parentFetches = Array.from(parentIds).map(async (parentId) => {\n try {\n const parentRes = await drive.files.get({\n fileId: parentId,\n fields: 'id,name',\n supportsAllDrives: true,\n });\n const parentName = (parentRes.data.name as string | undefined) || parentId;\n parentNameMap.set(parentId, parentName);\n } catch (e) {\n logger.info('Failed to fetch parent name', { parentId, error: e });\n parentNameMap.set(parentId, parentId); // Fallback to ID\n }\n });\n await Promise.all(parentFetches);\n }\n\n // Cache for folder names to reduce API calls during path resolution\n const folderCache = new Map<string, string>();\n\n const items: (DriveFile & { path?: string })[] = await Promise.all(\n folders.map(async (f: DriveFolder) => {\n const id = f?.id ? String(f.id) : 'unknown';\n const name = f?.name || id;\n const result: DriveFile & { path?: string } = { id, name };\n\n // Only include properties that have actual values\n if (f?.mimeType) result.mimeType = f.mimeType;\n if (f?.webViewLink) result.webViewLink = f.webViewLink;\n if (f?.modifiedTime) result.modifiedTime = f.modifiedTime;\n\n // Build parent objects with names\n if (f?.parents && f.parents.length > 0) {\n result.parents = f.parents.map((parentId) => {\n if (parentId === 'root') {\n return { id: 'root', name: 'My Drive' };\n }\n const parentName = parentNameMap.get(parentId) || parentId;\n return { id: parentId, name: parentName };\n });\n }\n\n if (f?.shared !== undefined) result.shared = f.shared;\n if (f?.starred !== undefined) result.starred = f.starred;\n\n if (f?.owners && f.owners.length > 0) {\n result.owners = f.owners.map((o) => {\n const owner: NonNullable<DriveFile['owners']>[number] = {};\n if (o?.displayName) owner.displayName = o.displayName;\n if (o?.emailAddress) owner.emailAddress = o.emailAddress;\n if (o?.kind) owner.kind = o.kind;\n if (o?.me !== undefined) owner.me = o.me;\n if (o?.permissionId) owner.permissionId = o.permissionId;\n if (o?.photoLink) owner.photoLink = o.photoLink;\n return owner;\n });\n }\n\n // Resolve path if requested\n if (resolvePaths && id !== 'unknown') {\n result.path = await resolveFolderPath(drive, id, folderCache, logger);\n }\n\n return result;\n })\n );\n\n const filteredItems = items.map((item) => filterFields(item, requestedFields));\n\n logger.info('drive.folder.search returning', {\n query: parsedQuery,\n pageSize,\n resultCount: filteredItems.length,\n resolvePaths,\n fields: fields || 'all',\n });\n\n const nextPageToken = res.nextPageToken && res.nextPageToken.trim().length > 0 ? res.nextPageToken : undefined;\n\n // Build result based on shape\n const result: Output =\n shape === 'arrays'\n ? {\n type: 'success' as const,\n shape: 'arrays' as const,\n ...toColumnarFormat(filteredItems, requestedFields, [...DRIVE_FILE_FIELDS, 'path'] as const),\n count: filteredItems.length,\n ...(nextPageToken && { nextPageToken }),\n }\n : {\n type: 'success' as const,\n shape: 'objects' as const,\n items: filteredItems,\n count: filteredItems.length,\n ...(nextPageToken && { nextPageToken }),\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('drive.folder.search error', { error: message });\n\n // Throw ProtocolError for all errors so callers can see Drive validation details\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error searching folders: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'folder-search' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","query","DriveQueryParameterSchema","optional","describe","fields","createFieldsSchema","availableFields","DRIVE_FILE_FIELDS","fieldDescriptions","DRIVE_FILE_FIELD_DESCRIPTIONS","path","commonPatterns","DRIVE_FILE_COMMON_PATTERNS","resourceName","resolvePaths","boolean","createPaginationSchema","defaultPageSize","maxPageSize","provider","shape","createShapeSchema","successObjectsBranchSchema","type","literal","items","array","DriveFileSchema","extend","string","count","number","nextPageToken","successArraysBranchSchema","columns","rows","unknown","outputSchema","union","config","title","description","result","resolveFolderPath","drive","folderId","folderCache","logger","pathParts","currentId","visited","cachedName","response","parents","_e","folderName","e","Set","has","info","add","get","unshift","files","fileId","supportsAllDrives","data","length","name","set","error","join","handler","extra","pageSize","pageToken","parsedQuery","requestedFields","validPageSize","folderMimeType","qStr","q","listOptions","res","folders","parentIds","f","parentId","parentNameMap","parentFetches","filteredItems","message","parseDriveQueryParameter","parseFields","Math","max","min","floor","undefined","driveApi","version","auth","googleAuth","authContext","rawDriveQuery","toDriveQuery","orderBy","corpora","includeItemsFromAllDrives","trim","list","Array","isArray","Map","size","from","map","parentRes","parentName","Promise","all","id","String","mimeType","webViewLink","modifiedTime","shared","starred","owners","o","owner","displayName","emailAddress","kind","me","permissionId","photoLink","item","filterFields","resultCount","toColumnarFormat","content","text","JSON","stringify","structuredContent","Error","ProtocolError","ProtocolErrorCode","InternalError","stack"],"mappings":";;;;+BA0WA;;;eAAwBA;;;2BAzWA;qBAKU;sBACgJ;mBAChK;4BACS;8BACE;uBACsJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AARnL,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAWR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;I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open-source/ai/mcp-z/mcp-drive/src/mcp/tools/index.ts"],"sourcesContent":["export { default as fileMove } from './file-move.ts';\nexport { default as fileMoveToTrash } from './file-move-to-trash.ts';\nexport { default as fileUpload } from './file-upload.ts';\nexport { default as filesSearch } from './files-search.ts';\nexport { default as folderContents } from './folder-contents.ts';\nexport { default as folderCreate } from './folder-create.ts';\nexport { default as folderPath } from './folder-path.ts';\nexport { default as folderSearch } from './folder-search.ts';\n"],"names":["fileMove","fileMoveToTrash","fileUpload","filesSearch","folderContents","folderCreate","folderPath","folderSearch"],"mappings":";;;;;;;;;;;QAAoBA;eAAAA,mBAAQ;;QACRC;eAAAA,0BAAe;;QACfC;eAAAA,qBAAU;;QACVC;eAAAA,sBAAW;;QACXC;eAAAA,yBAAc;;QACdC;eAAAA,uBAAY;;QACZC;eAAAA,qBAAU;;QACVC;eAAAA,uBAAY;;;iEAPI;wEACO;mEACL;oEACC;uEACG;qEACF;mEACF;qEACE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-drive/src/schemas/drive-query-schema.ts"],"sourcesContent":["import { z } from 'zod';\n\n/**\n * Field operator schema for Drive query fields that support multiple values\n * Supports OR ($any), AND ($all), and NOT ($none) operations\n */\nexport const FieldOperatorSchema = z\n .object({\n $any: z.array(z.string()).optional().describe('OR within field - matches if ANY value matches'),\n $all: z.array(z.string()).optional().describe('AND within field - matches if ALL values match'),\n $none: z.array(z.string()).optional().describe('NOT within field - matches if NONE match'),\n })\n .strict();\n\nexport type FieldOperator = z.infer<typeof FieldOperatorSchema>;\n\n/**\n * Drive query object schema with recursive operators and Drive features.\n *\n * Includes Drive-specific features:\n * - name: Search by file/folder name (supports string or field operators)\n * - mimeType: Filter by MIME type (e.g., \"application/pdf\", \"application/vnd.google-apps.folder\")\n * - fullText: Search file content and metadata\n * - parentId: Search within specific folder (supports string or field operators)\n * - starred: Filter by starred status\n * - shared: Filter by shared status\n * - modifiedTime: Date range filtering with $gte and $lt\n * - owner: Filter by owner email (supports string or field operators)\n * - rawDriveQuery: Escape hatch for advanced Drive query syntax\n *\n * Logical operators:\n * - $and: Array of conditions that must ALL match (recursive)\n * - $or: Array of conditions where ANY must match (recursive)\n * - $not: Nested condition that must NOT match (recursive)\n *\n * Note: Cast through unknown to work around Zod's lazy schema type inference issue\n * with exactOptionalPropertyTypes. The runtime schema is correct; this cast ensures\n * TypeScript sees the strict DriveQueryObject type everywhere the schema is used.\n */\nexport const DriveQuerySchema = z.lazy(() =>\n z\n .object({\n // Logical operators for combining conditions (recursive)\n $and: z.array(DriveQuerySchema).optional().describe('Array of conditions that must ALL match'),\n $or: z.array(DriveQuerySchema).optional().describe('Array of conditions where ANY must match'),\n $not: DriveQuerySchema.optional().describe('Nested condition that must NOT match'),\n\n // File/folder name search\n name: z\n .union([z.string().min(1), FieldOperatorSchema])\n .optional()\n .describe('Search by file or folder name (partial match, case-insensitive)'),\n\n // MIME type filtering\n mimeType: z\n .union([z.string().min(1), FieldOperatorSchema])\n .optional()\n .describe('Filter by MIME type (e.g., \"application/pdf\", \"application/vnd.google-apps.folder\", \"image/jpeg\")'),\n\n // Full-text search across content and metadata\n fullText: z\n .union([z.string().min(1), FieldOperatorSchema])\n .optional()\n .describe('Search file content and metadata (full-text search)'),\n\n // Parent folder filtering\n parentId: z\n .union([z.string().min(1), FieldOperatorSchema])\n .optional()\n .describe('Search within specific folder by folder ID (use \"root\" for My Drive root)'),\n\n // Boolean flags\n starred: z.boolean().optional().describe('Filter by starred status (true = starred, false = not starred)'),\n sharedWithMe: z.boolean().optional().describe('Filter by \"shared with me\" collection (true = in shared collection, false = not shared)'),\n trashed: z.boolean().optional().describe('Filter by trash status (true = in trash, false = not in trash).'),\n\n // Date range filtering\n modifiedTime: z\n .object({\n $gte: z\n .string()\n .regex(/^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}:\\d{2}(\\.\\d{3})?Z)?$/)\n .optional()\n .describe('Files modified on or after this date (ISO 8601: YYYY-MM-DD or YYYY-MM-DDTHH:mm:ss.sssZ)'),\n $lt: z\n .string()\n .regex(/^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}:\\d{2}(\\.\\d{3})?Z)?$/)\n .optional()\n .describe('Files modified before this date (ISO 8601: YYYY-MM-DD or YYYY-MM-DDTHH:mm:ss.sssZ)'),\n })\n .optional()\n .describe('Filter by modification date range'),\n\n // Owner filtering\n owner: z\n .union([z.string().min(1), FieldOperatorSchema])\n .optional()\n .describe('Filter by owner email address (partial match)'),\n\n // Raw Drive query string - escape hatch for advanced syntax\n rawDriveQuery: z.string().min(1).optional().describe(\"Raw Google Drive query syntax for advanced use cases. Bypasses schema validation - use sparingly. Example: \\\"name contains 'budget' and mimeType = 'application/pdf'\\\"\"),\n })\n .strict()\n) as unknown as z.ZodType<DriveQueryObject>;\n\nexport type DriveQueryObject = {\n $and?: DriveQueryObject[];\n $or?: DriveQueryObject[];\n $not?: DriveQueryObject;\n name?: string | FieldOperator;\n mimeType?: string | FieldOperator;\n fullText?: string | FieldOperator;\n parentId?: string | FieldOperator;\n starred?: boolean;\n sharedWithMe?: boolean;\n trashed?: boolean;\n modifiedTime?: {\n $gte?: string;\n $lt?: string;\n };\n owner?: string | FieldOperator;\n rawDriveQuery?: string;\n};\n\nexport type DriveQuery = DriveQueryObject;\n\n/**\n * Drive query parameter schema that accepts either:\n * - A structured DriveQuery object with typed fields\n * - A JSON string representing that object\n *\n * This provides type safety for common queries while allowing\n * JSON string input from MCP clients when needed.\n */\nexport const DriveQueryParameterSchema = z.union([DriveQuerySchema, z.string().min(1)]) as z.ZodType<DriveQuery | string>;\nexport type DriveQueryParameter = z.infer<typeof DriveQueryParameterSchema>;\n\nexport function parseDriveQueryParameter(input: DriveQuery | string | undefined): DriveQuery | undefined {\n if (input === undefined) return undefined;\n const raw = typeof input === 'string' ? safeJsonParse(input, 'rawDriveQuery') : input;\n const validated = DriveQuerySchema.safeParse(raw);\n if (!validated.success) {\n throw new Error(`Invalid query JSON: ${validated.error.message}. Use {\"rawDriveQuery\":\"<query>\"} for Drive syntax.`);\n }\n return validated.data;\n}\n\nfunction safeJsonParse(value: string, rawField: 'rawDriveQuery'): unknown {\n try {\n return JSON.parse(value);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Invalid JSON';\n throw new Error(`Query must be valid JSON. ${message}. Wrap Drive syntax in {\"${rawField}\":\"<query>\"} if needed.`);\n }\n}\n"],"names":["DriveQueryParameterSchema","DriveQuerySchema","FieldOperatorSchema","parseDriveQueryParameter","z","object","$any","array","string","optional","describe","$all","$none","strict","lazy","$and","$or","$not","name","union","min","mimeType","fullText","parentId","starred","boolean","sharedWithMe","trashed","modifiedTime","$gte","regex","$lt","owner","rawDriveQuery","input","undefined","raw","safeJsonParse","validated","safeParse","success","Error","error","message","data","value","rawField","JSON","parse"],"mappings":";;;;;;;;;;;QAsIaA;eAAAA;;QA/FAC;eAAAA;;QAjCAC;eAAAA;;QAmIGC;eAAAA;;;mBAzIE;;;;;;;AAMX,IAAMD,sBAAsBE,MAAC,CACjCC,MAAM,CAAC;IACNC,MAAMF,MAAC,CAACG,KAAK,CAACH,MAAC,CAACI,MAAM,IAAIC,QAAQ,GAAGC,QAAQ,CAAC;IAC9CC,MAAMP,MAAC,CAACG,KAAK,CAACH,MAAC,CAACI,MAAM,IAAIC,QAAQ,GAAGC,QAAQ,CAAC;IAC9CE,OAAOR,MAAC,CAACG,KAAK,CAACH,MAAC,CAACI,MAAM,IAAIC,QAAQ,GAAGC,QAAQ,CAAC;AACjD,GACCG,MAAM;AA2BF,IAAMZ,mBAAmBG,MAAC,CAACU,IAAI,CAAC;WACrCV,MAAC,CACEC,MAAM,CAAC;QACN,yDAAyD;QACzDU,MAAMX,MAAC,CAACG,KAAK,CAACN,kBAAkBQ,QAAQ,GAAGC,QAAQ,CAAC;QACpDM,KAAKZ,MAAC,CAACG,KAAK,CAACN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ACLe,KAAK,CAAC;YAACf,MAAC,CAACI,MAAM,GAAGY,GAAG,CAAC;YAAIlB;SAAoB,EAC9CO,QAAQ,GACRC,QAAQ,CAAC;QAEZ,4DAA4D;QAC5DuB,eAAe7B,MAAC,CAACI,MAAM,GAAGY,GAAG,CAAC,GAAGX,QAAQ,GAAGC,QAAQ,CAAC;IACvD,GACCG,MAAM;;AAgCJ,IAAMb,4BAA4BI,MAAC,CAACe,KAAK,CAAC;IAAClB;IAAkBG,MAAC,CAACI,MAAM,GAAGY,GAAG,CAAC;CAAG;AAG/E,SAASjB,yBAAyB+B,KAAsC;IAC7E,IAAIA,UAAUC,WAAW,OAAOA;IAChC,IAAMC,MAAM,OAAOF,UAAU,WAAWG,cAAcH,OAAO,mBAAmBA;IAChF,IAAMI,YAAYrC,iBAAiBsC,SAAS,CAACH;IAC7C,IAAI,CAACE,UAAUE,OAAO,EAAE;QACtB,MAAM,IAAIC,MAAM,AAAC,uBAA8C,OAAxBH,UAAUI,KAAK,CAACC,OAAO,EAAC;IACjE;IACA,OAAOL,UAAUM,IAAI;AACvB;AAEA,SAASP,cAAcQ,KAAa,EAAEC,QAAyB;IAC7D,IAAI;QACF,OAAOC,KAAKC,KAAK,CAACH;IACpB,EAAE,OAAOH,OAAO;QACd,IAAMC,UAAUD,AAAK,YAALA,OAAiBD,SAAQC,MAAMC,OAAO,GAAG;QACzD,MAAM,IAAIF,MAAM,AAAC,6BAA+DK,OAAnCH,SAAQ,6BAAoC,OAATG,UAAS;IAC3F;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-drive/src/schemas/drive-validation.ts"],"sourcesContent":["import { z } from 'zod';\n\n// Drive file schema\nexport const DriveFileSchema = z.object({\n id: z.string().optional(),\n name: z.string().optional(),\n mimeType: z.string().optional().describe('MIME type of the file (e.g., application/pdf, image/png)'),\n webViewLink: z.string().optional().describe('URL to view the file in Google Drive'),\n webContentLink: z.string().optional().describe('Direct download link for the file'),\n modifiedTime: z.string().optional().describe('ISO datetime when file was last modified'),\n createdTime: z.string().optional().describe('ISO datetime when file was created'),\n size: z.string().optional().describe('File size in bytes as string'),\n version: z.string().optional().describe('Version number of the file'),\n shared: z.boolean().optional().describe('Whether the file is shared with others'),\n starred: z.boolean().optional().describe('Whether the file is starred by the user'),\n trashed: z.boolean().optional().describe('Whether the file is in trash'),\n parents: z\n .array(\n z.object({\n id: z.string().describe('Parent folder ID'),\n name: z.string().describe('Parent folder name'),\n })\n )\n .optional()\n .describe('Parent folders with ID and name'),\n owners: z\n .array(\n z.object({\n displayName: z.string().optional(),\n emailAddress: z.string().optional(),\n kind: z.string().optional().describe('Resource type identifier (e.g., \"drive#user\")'),\n me: z.boolean().optional().describe('Whether this owner is the current user'),\n permissionId: z.string().optional().describe('Permission ID for this user'),\n photoLink: z.string().optional().describe('URL to user profile photo'),\n })\n )\n .optional(),\n permissions: z\n .object({\n canEdit: z.boolean().optional(),\n canComment: z.boolean().optional(),\n canShare: z.boolean().optional(),\n })\n .optional()\n .describe(\"Current user's permissions on this file\"),\n});\n\nexport type DriveFile = z.infer<typeof DriveFileSchema>;\n\n// Drive file field definitions for field selection\nexport const DRIVE_FILE_FIELDS = ['id', 'name', 'mimeType', 'webViewLink', 'modifiedTime', 'parents', 'shared', 'starred', 'owners'] as const;\n\nexport const DRIVE_FILE_FIELD_DESCRIPTIONS: Record<(typeof DRIVE_FILE_FIELDS)[number], string> = {\n id: 'Unique file/folder identifier',\n name: 'File or folder name',\n mimeType: 'MIME type (e.g., application/pdf, application/vnd.google-apps.folder)',\n webViewLink: 'URL to view the file in Google Drive',\n modifiedTime: 'Last modification timestamp',\n parents: 'Parent folder IDs',\n shared: 'Whether the file is shared',\n starred: 'Whether the file is starred',\n owners: 'File owner information (displayName, emailAddress, etc.)',\n};\n\nexport const DRIVE_FILE_COMMON_PATTERNS = [\n {\n name: 'Bulk operations (delete/move)',\n fields: 'id,name',\n tokens: '~20 tokens/file',\n },\n {\n name: 'Browsing/filtering',\n fields: 'id,name,mimeType,modifiedTime',\n tokens: '~40 tokens/file',\n },\n {\n name: 'Full metadata',\n fields: 'id,name,mimeType,webViewLink,modifiedTime,owners',\n tokens: '~80 tokens/file',\n },\n] as const;\n"],"names":["DRIVE_FILE_COMMON_PATTERNS","DRIVE_FILE_FIELDS","DRIVE_FILE_FIELD_DESCRIPTIONS","DriveFileSchema","z","object","id","string","optional","name","mimeType","describe","webViewLink","webContentLink","modifiedTime","createdTime","size","version","shared","boolean","starred","trashed","parents","array","owners","displayName","emailAddress","kind","me","permissionId","photoLink","permissions","canEdit","canComment","canShare","fields","tokens"],"mappings":";;;;;;;;;;;QAgEaA;eAAAA;;QAdAC;eAAAA;;QAEAC;eAAAA;;QAjDAC;eAAAA;;;mBAHK;AAGX,IAAMA,kBAAkBC,MAAC,CAACC,MAAM,CAAC;IACtCC,IAAIF,MAAC,CAACG,MAAM,GAAGC,QAAQ;IACvBC,MAAML,MAAC,CAACG,MAAM,GAAGC,QAAQ;IACzBE,UAAUN,MAAC,CAACG,MAAM,GAAGC,QAAQ,GAAGG,QAAQ,CAAC;IACzCC,aAAaR,MAAC,CAACG,MAAM,GAAGC,QAAQ,GAAGG,QAAQ,CAAC;IAC5CE,gBAAgBT,MAAC,CAACG,MAAM,GAAGC,QAAQ,GAAGG,QAAQ,CAAC;IAC/CG,cAAcV,MAAC,CAACG,MAAM,GAAGC,QAAQ,GAAGG,QAAQ,CAAC;IAC7CI,aAAaX,MAAC,CAACG,MAAM,GAAGC,QAAQ,GAAGG,QAAQ,CAAC;IAC5CK,MAAMZ,MAAC,CAACG,MAAM,GAAGC,QAAQ,GAAGG,QAAQ,CAAC;IACrCM,SAASb,MAAC,CAACG,MAAM,GAAGC,QAAQ,GAAGG,QAAQ,CAAC;IACxCO,QAAQd,MAAC,CAACe,OAAO,GAAGX,QAAQ,GAAGG,QAAQ,CAAC;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IACRE,SAAS;IACTI,QAAQ;AACV;AAEO,IAAMxB,6BAA6B;IACxC;QACES,MAAM;QACN0B,QAAQ;QACRC,QAAQ;IACV;IACA;QACE3B,MAAM;QACN0B,QAAQ;QACRC,QAAQ;IACV;IACA;QACE3B,MAAM;QACN0B,QAAQ;QACRC,QAAQ;IACV;CACD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-drive/src/schemas/index.ts"],"sourcesContent":["export * from './drive-query-schema.ts';\nexport * from './drive-validation.ts';\n"],"names":[],"mappings":";;;;qBAAc;qBACA"}
|
package/dist/cjs/setup/config.js
CHANGED
|
@@ -16,6 +16,7 @@ _export(exports, {
|
|
|
16
16
|
return parseConfig;
|
|
17
17
|
}
|
|
18
18
|
});
|
|
19
|
+
var _nodeurl = require("node:url");
|
|
19
20
|
var _module = require("module");
|
|
20
21
|
var _os = require("os");
|
|
21
22
|
var _path = /*#__PURE__*/ _interop_require_wildcard(require("path"));
|
|
@@ -180,12 +181,12 @@ function normalizeResourceStoreUri(resourceStoreUri) {
|
|
|
180
181
|
var filePrefix = 'file://';
|
|
181
182
|
if (resourceStoreUri.startsWith(filePrefix)) {
|
|
182
183
|
var rawPath = resourceStoreUri.slice(filePrefix.length);
|
|
183
|
-
var
|
|
184
|
-
return
|
|
184
|
+
var filePath = rawPath.startsWith('~') ? rawPath.replace(/^~/, (0, _os.homedir)()) : rawPath.startsWith('/') ? (0, _nodeurl.fileURLToPath)(resourceStoreUri) : rawPath;
|
|
185
|
+
return (0, _nodeurl.pathToFileURL)(_path.resolve(filePath)).href;
|
|
185
186
|
}
|
|
186
187
|
if (resourceStoreUri.includes('://')) return resourceStoreUri;
|
|
187
|
-
var
|
|
188
|
-
return
|
|
188
|
+
var expandedPath = resourceStoreUri.startsWith('~') ? resourceStoreUri.replace(/^~/, (0, _os.homedir)()) : resourceStoreUri;
|
|
189
|
+
return (0, _nodeurl.pathToFileURL)(_path.resolve(expandedPath)).href;
|
|
189
190
|
}
|
|
190
191
|
function createConfig() {
|
|
191
192
|
return parseConfig(process.argv, process.env);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/setup/config.ts"],"sourcesContent":["import type * as OAuthGoogle from '@mcp-z/oauth-google';\nimport type * as McpServer from '@mcp-z/server';\nimport { Module } from 'module';\nimport { homedir } from 'os';\nimport * as path from 'path';\nimport { parseArgs } from 'util';\nimport { GOOGLE_SCOPE } from '../constants.ts';\nimport type { ServerConfig } from '../types.ts';\nimport { readPkg } from './version-help.ts';\n\nconst pkg = readPkg();\n\n// @mcp-z/oauth-google and @mcp-z/server are requireable at the >=20 floor; deferred so\n// --version/--help (handled via version-help.ts, never this file) load neither package.\nconst _require = typeof require === 'undefined' ? Module.createRequire(import.meta.url) : require;\n\n/**\n * Parse Drive server configuration from CLI arguments and environment.\n *\n * CLI Arguments (all optional):\n * - --auth=<mode> Authentication mode (default: loopback-oauth)\n * Modes: loopback-oauth, service-account, dcr\n * - --headless Disable browser auto-open, return auth URL instead\n * - --redirect-uri=<uri> OAuth redirect URI (default: ephemeral loopback)\n * - --dcr-mode=<mode> DCR mode (self-hosted or external, default: self-hosted)\n * - --dcr-verify-url=<url> External verification endpoint (required for external mode)\n * - --dcr-store-uri=<uri> DCR client storage URI (required for self-hosted mode)\n * - --port=<port> Enable HTTP transport on specified port\n * - --stdio Enable stdio transport (default if no port)\n * - --log-level=<level> Logging level (default: info)\n * - --resource-store-uri=<uri> Resource store URI for CSV file storage (default: file://~/.mcp-z/mcp-drive/files)\n * - --base-url=<url> Base URL for HTTP file serving (optional)\n *\n * Environment Variables:\n * - GOOGLE_CLIENT_ID OAuth client ID (REQUIRED)\n * - GOOGLE_CLIENT_SECRET OAuth client secret (optional)\n * - AUTH_MODE Default authentication mode (optional)\n * - HEADLESS Disable browser auto-open (optional)\n * - DCR_MODE DCR mode (optional, same format as --dcr-mode)\n * - DCR_VERIFY_URL External verification URL (optional, same as --dcr-verify-url)\n * - DCR_STORE_URI DCR storage URI (optional, same as --dcr-store-uri)\n * - TOKEN_STORE_URI Token storage URI (optional)\n * - PORT Default HTTP port (optional)\n * - LOG_LEVEL Default logging level (optional)\n * - RESOURCE_STORE_URI Resource store URI (optional, file://)\n * - BASE_URL Base URL for HTTP file serving (optional)\n *\n * OAuth Scopes (from constants.ts):\n * openid https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/drive\n */\nexport function parseConfig(args: string[], env: Record<string, string | undefined>): ServerConfig {\n const oauthGoogle = _require('@mcp-z/oauth-google') as typeof OAuthGoogle;\n const mcpServer = _require('@mcp-z/server') as typeof McpServer;\n\n const transportConfig = mcpServer.parseConfig(args, env);\n const oauthConfig = oauthGoogle.parseConfig(args, env);\n\n // Parse DCR configuration if DCR mode is enabled\n const dcrConfig = oauthConfig.auth === 'dcr' ? oauthGoogle.parseDcrConfig(args, env, GOOGLE_SCOPE) : undefined;\n\n // Parse application-level config (LOG_LEVEL, RESOURCE_STORE_URI, BASE_URL)\n const { values } = parseArgs({\n args,\n options: {\n 'log-level': { type: 'string' },\n 'base-url': { type: 'string' },\n 'resource-store-uri': { type: 'string' },\n },\n strict: false, // Allow other arguments\n allowPositionals: true,\n });\n\n const name = pkg.name.replace(/^@[^/]+\\//, '');\n // Parse repository URL from package.json, stripping git+ prefix and .git suffix\n const rawRepoUrl = typeof pkg.repository === 'object' ? pkg.repository.url : pkg.repository;\n const repositoryUrl = rawRepoUrl?.replace(/^git\\+/, '').replace(/\\.git$/, '') ?? `https://github.com/mcp-z/${name}`;\n let rootDir = homedir();\n try {\n const configPath = mcpServer.findConfigPath({ config: '.mcp.json', cwd: process.cwd(), stopDir: homedir() });\n rootDir = path.dirname(configPath);\n } catch {\n rootDir = homedir();\n }\n const baseDir = path.join(rootDir, '.mcp-z');\n const cliLogLevel = typeof values['log-level'] === 'string' ? values['log-level'] : undefined;\n const envLogLevel = env.LOG_LEVEL;\n const logLevel = cliLogLevel ?? envLogLevel ?? 'info';\n\n // Parse storage configuration\n const cliResourceStoreUri = typeof values['resource-store-uri'] === 'string' ? values['resource-store-uri'] : undefined;\n const envResourceStoreUri = env.RESOURCE_STORE_URI;\n const defaultResourceStorePath = path.join(baseDir, name, 'files');\n const resourceStoreUri = normalizeResourceStoreUri(cliResourceStoreUri ?? envResourceStoreUri ?? defaultResourceStorePath);\n\n const cliBaseUrl = typeof values['base-url'] === 'string' ? values['base-url'] : undefined;\n const envBaseUrl = env.BASE_URL;\n const baseUrl = cliBaseUrl ?? envBaseUrl;\n\n // Combine configs\n return {\n ...oauthConfig, // Includes clientId, auth, headless, redirectUri\n transport: transportConfig.transport,\n logLevel,\n baseDir,\n name,\n version: pkg.version,\n repositoryUrl,\n resourceStoreUri,\n ...(baseUrl && { baseUrl }),\n ...(dcrConfig && { dcrConfig }),\n };\n}\n\nfunction normalizeResourceStoreUri(resourceStoreUri: string): string {\n const filePrefix = 'file://';\n if (resourceStoreUri.startsWith(filePrefix)) {\n const rawPath = resourceStoreUri.slice(filePrefix.length);\n const expandedPath = rawPath.startsWith('~') ? rawPath.replace(/^~/, homedir()) : rawPath;\n return `${filePrefix}${path.resolve(expandedPath)}`;\n }\n\n if (resourceStoreUri.includes('://')) return resourceStoreUri;\n\n const expandedPath = resourceStoreUri.startsWith('~') ? resourceStoreUri.replace(/^~/, homedir()) : resourceStoreUri;\n return `${filePrefix}${path.resolve(expandedPath)}`;\n}\n\n/**\n * Build production configuration from process globals.\n * Entry point for production server.\n */\nexport function createConfig(): ServerConfig {\n return parseConfig(process.argv, process.env);\n}\n"],"names":["createConfig","parseConfig","pkg","readPkg","_require","require","Module","createRequire","args","env","cliLogLevel","cliResourceStoreUri","oauthGoogle","mcpServer","transportConfig","oauthConfig","dcrConfig","auth","parseDcrConfig","GOOGLE_SCOPE","undefined","values","parseArgs","options","type","strict","allowPositionals","name","replace","rawRepoUrl","repository","url","repositoryUrl","rootDir","homedir","configPath","findConfigPath","config","cwd","process","stopDir","path","dirname","baseDir","join","envLogLevel","LOG_LEVEL","logLevel","envResourceStoreUri","RESOURCE_STORE_URI","defaultResourceStorePath","resourceStoreUri","normalizeResourceStoreUri","cliBaseUrl","envBaseUrl","BASE_URL","baseUrl","transport","version","filePrefix","startsWith","rawPath","slice","length","expandedPath","resolve","includes","argv"],"mappings":";;;;;;;;;;;QAmIgBA;eAAAA;;QAjFAC;eAAAA;;;sBAhDO;kBACC;4DACF;oBACI;2BACG;6BAEL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAExB,IAAMC,MAAMC,IAAAA,sBAAO;AAEnB,uFAAuF;AACvF,wFAAwF;AACxF,IAAMC,WAAW,OAAOC,YAAY,cAAcC,cAAM,CAACC,aAAa,CAAC,uDAAmBF;AAoCnF,SAASJ,YAAYO,IAAc,EAAEC,GAAuC;cAoChEC,OAMkCC;IAzCnD,IAAMC,cAAcR,SAAS;IAC7B,IAAMS,YAAYT,SAAS;IAE3B,IAAMU,kBAAkBD,UAAUZ,WAAW,CAACO,MAAMC;IACpD,IAAMM,cAAcH,YAAYX,WAAW,CAACO,MAAMC;IAElD,iDAAiD;IACjD,IAAMO,YAAYD,YAAYE,IAAI,KAAK,QAAQL,YAAYM,cAAc,CAACV,MAAMC,KAAKU,yBAAY,IAAIC;IAErG,2EAA2E;IAC3E,IAAM,AAAEC,SAAWC,IAAAA,eAAS,EAAC;QAC3Bd,MAAAA;QACAe,SAAS;YACP,aAAa;gBAAEC,MAAM;YAAS;YAC9B,YAAY;gBAAEA,MAAM;YAAS;YAC7B,sBAAsB;gBAAEA,MAAM;YAAS;QACzC;QACAC,QAAQ;QACRC,kBAAkB;IACpB,GATQL;IAWR,IAAMM,OAAOzB,IAAIyB,IAAI,CAACC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,kBAAkB;IAClB,OAAO,uDACFvC;QACH0C,WAAW3C,gBAAgB2C,SAAS;QACpCV,UAAAA;QACAJ,SAAAA;QACAhB,MAAAA;QACA+B,SAASxD,IAAIwD,OAAO;QACpB1B,eAAAA;QACAmB,kBAAAA;QACIK,WAAW;QAAEA,SAAAA;IAAQ,GACrBxC,aAAa;QAAEA,WAAAA;IAAU;AAEjC;AAEA,SAASoC,0BAA0BD,gBAAwB;IACzD,IAAMQ,aAAa;IACnB,IAAIR,iBAAiBS,UAAU,CAACD,aAAa;QAC3C,IAAME,UAAUV,iBAAiBW,KAAK,CAACH,WAAWI,MAAM;QACxD,IAAMC,eAAeH,QAAQD,UAAU,CAAC,OAAOC,QAAQjC,OAAO,CAAC,MAAMM,IAAAA,WAAO,OAAM2B;QAClF,OAAO,AAAC,GAAepB,OAAbkB,YAAwC,OAA3BlB,MAAKwB,OAAO,CAACD;IACtC;IAEA,IAAIb,iBAAiBe,QAAQ,CAAC,QAAQ,OAAOf;IAE7C,IAAMa,gBAAeb,iBAAiBS,UAAU,CAAC,OAAOT,iBAAiBvB,OAAO,CAAC,MAAMM,IAAAA,WAAO,OAAMiB;IACpG,OAAO,AAAC,GAAeV,OAAbkB,YAAwC,OAA3BlB,MAAKwB,OAAO,CAACD;AACtC;AAMO,SAAShE;IACd,OAAOC,YAAYsC,QAAQ4B,IAAI,EAAE5B,QAAQ9B,GAAG;AAC9C"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-drive/src/setup/config.ts"],"sourcesContent":["import { fileURLToPath, pathToFileURL } from 'node:url';\nimport type * as OAuthGoogle from '@mcp-z/oauth-google';\nimport type * as McpServer from '@mcp-z/server';\nimport { Module } from 'module';\nimport { homedir } from 'os';\nimport * as path from 'path';\nimport { parseArgs } from 'util';\nimport { GOOGLE_SCOPE } from '../constants.ts';\nimport type { ServerConfig } from '../types.ts';\nimport { readPkg } from './version-help.ts';\n\nconst pkg = readPkg();\n\n// @mcp-z/oauth-google and @mcp-z/server are requireable at the >=20 floor; deferred so\n// --version/--help (handled via version-help.ts, never this file) load neither package.\nconst _require = typeof require === 'undefined' ? Module.createRequire(import.meta.url) : require;\n\n/**\n * Parse Drive server configuration from CLI arguments and environment.\n *\n * CLI Arguments (all optional):\n * - --auth=<mode> Authentication mode (default: loopback-oauth)\n * Modes: loopback-oauth, service-account, dcr\n * - --headless Disable browser auto-open, return auth URL instead\n * - --redirect-uri=<uri> OAuth redirect URI (default: ephemeral loopback)\n * - --dcr-mode=<mode> DCR mode (self-hosted or external, default: self-hosted)\n * - --dcr-verify-url=<url> External verification endpoint (required for external mode)\n * - --dcr-store-uri=<uri> DCR client storage URI (required for self-hosted mode)\n * - --port=<port> Enable HTTP transport on specified port\n * - --stdio Enable stdio transport (default if no port)\n * - --log-level=<level> Logging level (default: info)\n * - --resource-store-uri=<uri> Resource store URI for CSV file storage (default: file://~/.mcp-z/mcp-drive/files)\n * - --base-url=<url> Base URL for HTTP file serving (optional)\n *\n * Environment Variables:\n * - GOOGLE_CLIENT_ID OAuth client ID (REQUIRED)\n * - GOOGLE_CLIENT_SECRET OAuth client secret (optional)\n * - AUTH_MODE Default authentication mode (optional)\n * - HEADLESS Disable browser auto-open (optional)\n * - DCR_MODE DCR mode (optional, same format as --dcr-mode)\n * - DCR_VERIFY_URL External verification URL (optional, same as --dcr-verify-url)\n * - DCR_STORE_URI DCR storage URI (optional, same as --dcr-store-uri)\n * - TOKEN_STORE_URI Token storage URI (optional)\n * - PORT Default HTTP port (optional)\n * - LOG_LEVEL Default logging level (optional)\n * - RESOURCE_STORE_URI Resource store URI (optional, file://)\n * - BASE_URL Base URL for HTTP file serving (optional)\n *\n * OAuth Scopes (from constants.ts):\n * openid https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/drive\n */\nexport function parseConfig(args: string[], env: Record<string, string | undefined>): ServerConfig {\n const oauthGoogle = _require('@mcp-z/oauth-google') as typeof OAuthGoogle;\n const mcpServer = _require('@mcp-z/server') as typeof McpServer;\n\n const transportConfig = mcpServer.parseConfig(args, env);\n const oauthConfig = oauthGoogle.parseConfig(args, env);\n\n // Parse DCR configuration if DCR mode is enabled\n const dcrConfig = oauthConfig.auth === 'dcr' ? oauthGoogle.parseDcrConfig(args, env, GOOGLE_SCOPE) : undefined;\n\n // Parse application-level config (LOG_LEVEL, RESOURCE_STORE_URI, BASE_URL)\n const { values } = parseArgs({\n args,\n options: {\n 'log-level': { type: 'string' },\n 'base-url': { type: 'string' },\n 'resource-store-uri': { type: 'string' },\n },\n strict: false, // Allow other arguments\n allowPositionals: true,\n });\n\n const name = pkg.name.replace(/^@[^/]+\\//, '');\n // Parse repository URL from package.json, stripping git+ prefix and .git suffix\n const rawRepoUrl = typeof pkg.repository === 'object' ? pkg.repository.url : pkg.repository;\n const repositoryUrl = rawRepoUrl?.replace(/^git\\+/, '').replace(/\\.git$/, '') ?? `https://github.com/mcp-z/${name}`;\n let rootDir = homedir();\n try {\n const configPath = mcpServer.findConfigPath({ config: '.mcp.json', cwd: process.cwd(), stopDir: homedir() });\n rootDir = path.dirname(configPath);\n } catch {\n rootDir = homedir();\n }\n const baseDir = path.join(rootDir, '.mcp-z');\n const cliLogLevel = typeof values['log-level'] === 'string' ? values['log-level'] : undefined;\n const envLogLevel = env.LOG_LEVEL;\n const logLevel = cliLogLevel ?? envLogLevel ?? 'info';\n\n // Parse storage configuration\n const cliResourceStoreUri = typeof values['resource-store-uri'] === 'string' ? values['resource-store-uri'] : undefined;\n const envResourceStoreUri = env.RESOURCE_STORE_URI;\n const defaultResourceStorePath = path.join(baseDir, name, 'files');\n const resourceStoreUri = normalizeResourceStoreUri(cliResourceStoreUri ?? envResourceStoreUri ?? defaultResourceStorePath);\n\n const cliBaseUrl = typeof values['base-url'] === 'string' ? values['base-url'] : undefined;\n const envBaseUrl = env.BASE_URL;\n const baseUrl = cliBaseUrl ?? envBaseUrl;\n\n // Combine configs\n return {\n ...oauthConfig, // Includes clientId, auth, headless, redirectUri\n transport: transportConfig.transport,\n logLevel,\n baseDir,\n name,\n version: pkg.version,\n repositoryUrl,\n resourceStoreUri,\n ...(baseUrl && { baseUrl }),\n ...(dcrConfig && { dcrConfig }),\n };\n}\n\nfunction normalizeResourceStoreUri(resourceStoreUri: string): string {\n const filePrefix = 'file://';\n if (resourceStoreUri.startsWith(filePrefix)) {\n const rawPath = resourceStoreUri.slice(filePrefix.length);\n const filePath = rawPath.startsWith('~') ? rawPath.replace(/^~/, homedir()) : rawPath.startsWith('/') ? fileURLToPath(resourceStoreUri) : rawPath;\n return pathToFileURL(path.resolve(filePath)).href;\n }\n\n if (resourceStoreUri.includes('://')) return resourceStoreUri;\n\n const expandedPath = resourceStoreUri.startsWith('~') ? resourceStoreUri.replace(/^~/, homedir()) : resourceStoreUri;\n return pathToFileURL(path.resolve(expandedPath)).href;\n}\n\n/**\n * Build production configuration from process globals.\n * Entry point for production server.\n */\nexport function createConfig(): ServerConfig {\n return parseConfig(process.argv, process.env);\n}\n"],"names":["createConfig","parseConfig","pkg","readPkg","_require","require","Module","createRequire","args","env","cliLogLevel","cliResourceStoreUri","oauthGoogle","mcpServer","transportConfig","oauthConfig","dcrConfig","auth","parseDcrConfig","GOOGLE_SCOPE","undefined","values","parseArgs","options","type","strict","allowPositionals","name","replace","rawRepoUrl","repository","url","repositoryUrl","rootDir","homedir","configPath","findConfigPath","config","cwd","process","stopDir","path","dirname","baseDir","join","envLogLevel","LOG_LEVEL","logLevel","envResourceStoreUri","RESOURCE_STORE_URI","defaultResourceStorePath","resourceStoreUri","normalizeResourceStoreUri","cliBaseUrl","envBaseUrl","BASE_URL","baseUrl","transport","version","filePrefix","startsWith","rawPath","slice","length","filePath","fileURLToPath","pathToFileURL","resolve","href","includes","expandedPath","argv"],"mappings":";;;;;;;;;;;QAoIgBA;eAAAA;;QAjFAC;eAAAA;;;uBAnD6B;sBAGtB;kBACC;4DACF;oBACI;2BACG;6BAEL;;;;;;;;;;;;;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AWH,QAAQD,UAAU,CAAC,OAAOC,QAAQjC,OAAO,CAAC,MAAMM,IAAAA,WAAO,OAAM2B,QAAQD,UAAU,CAAC,OAAOK,IAAAA,sBAAa,EAACd,oBAAoBU;QAC1I,OAAOK,IAAAA,sBAAa,EAACzB,MAAK0B,OAAO,CAACH,WAAWI,IAAI;IACnD;IAEA,IAAIjB,iBAAiBkB,QAAQ,CAAC,QAAQ,OAAOlB;IAE7C,IAAMmB,eAAenB,iBAAiBS,UAAU,CAAC,OAAOT,iBAAiBvB,OAAO,CAAC,MAAMM,IAAAA,WAAO,OAAMiB;IACpG,OAAOe,IAAAA,sBAAa,EAACzB,MAAK0B,OAAO,CAACG,eAAeF,IAAI;AACvD;AAMO,SAASpE;IACd,OAAOC,YAAYsC,QAAQgC,IAAI,EAAEhC,QAAQ9B,GAAG;AAC9C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-drive/src/setup/http.ts"],"sourcesContent":["import { composeMiddleware, connectHttp, defaultCacheHints, McpServer, registerPrompts, registerResources, registerTools } from '@mcp-z/server';\nimport cors from 'cors';\nimport express from 'express';\nimport type { RuntimeOverrides, ServerConfig } from '../types.ts';\nimport { createDefaultRuntime } from './runtime.ts';\n\nexport async function createHTTPServer(config: ServerConfig, overrides?: RuntimeOverrides) {\n const runtime = await createDefaultRuntime(config, overrides);\n const modules = runtime.createDomainModules();\n const layers = runtime.middlewareFactories.map((factory) => factory(runtime.deps));\n const composed = composeMiddleware(modules, layers);\n const logger = runtime.deps.logger;\n const port = config.transport.port;\n if (!port) throw new Error('Port is required for HTTP transport');\n\n const tools = [...composed.tools, ...runtime.deps.oauthAdapters.accountTools];\n const prompts = [...composed.prompts, ...runtime.deps.oauthAdapters.accountPrompts];\n\n // Built per request (HTTP) and per connection (stdio), not shared. The SDK caches the\n // negotiated protocol revision on the McpServer instance - its own docs say a negotiated\n // session never re-routes a method onto the other era - so one shared instance pins itself\n // to whichever revision reaches it first and answers the other with -32601.\n const buildServer = () => {\n const mcpServer = new McpServer({ name: config.name, version: config.version }, { cacheHints: defaultCacheHints });\n registerTools(mcpServer, tools);\n registerResources(mcpServer, composed.resources);\n registerPrompts(mcpServer, prompts);\n return mcpServer;\n };\n\n const app = express();\n app.use(express.json({ limit: '10mb' }));\n\n // Must mount '/mcp' before any permissive app-level cors(), or that layer answers its\n // preflight first; pass baseUrl's origin/host below or a public deployment 403s itself.\n const publicUrl = config.baseUrl ? new URL(config.baseUrl) : undefined;\n logger.info(`Starting ${config.name} MCP server (http)`);\n const { close, httpServer } = await connectHttp(buildServer, {\n logger,\n app,\n port,\n allowedOrigins: publicUrl ? [publicUrl.origin] : undefined,\n allowedHosts: publicUrl ? [publicUrl.host] : undefined,\n });\n\n // The loopback OAuth callback and the DCR discovery/registration endpoints are\n // meant to be reached from a browser on another origin. Keep cors() for them,\n // scoped to their own routes - never in front of '/mcp'.\n if (runtime.deps.oauthAdapters.loopbackRouter) {\n app.use('/', cors(), runtime.deps.oauthAdapters.loopbackRouter);\n logger.info('Mounted loopback OAuth callback router');\n }\n\n if (runtime.deps.oauthAdapters.dcrRouter) {\n app.use('/', cors(), runtime.deps.oauthAdapters.dcrRouter);\n logger.info('Mounted DCR router with OAuth endpoints');\n }\n\n logger.info('http transport ready');\n\n return {\n httpServer,\n logger,\n close: async () => {\n await close();\n await runtime.close();\n },\n };\n}\n"],"names":["createHTTPServer","config","overrides","runtime","modules","layers","composed","logger","port","tools","prompts","buildServer","app","publicUrl","close","httpServer","createDefaultRuntime","createDomainModules","middlewareFactories","map","factory","deps","composeMiddleware","transport","Error","oauthAdapters","accountTools","accountPrompts","mcpServer","McpServer","name","version","cacheHints","defaultCacheHints","registerTools","registerResources","resources","registerPrompts","express","use","json","limit","baseUrl","URL","undefined","info","connectHttp","allowedOrigins","origin","allowedHosts","host","loopbackRouter","cors","dcrRouter"],"mappings":";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oDAAMX,QAAQW,KAAK;;;gDAAnB;;;;;;gCACF;;wBACF;;;;IACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-drive/src/setup/index.ts"],"sourcesContent":["export { createConfig, parseConfig } from './config.ts';\nexport { createHTTPServer } from './http.ts';\nexport type { AuthMiddleware, OAuthAdapters, OAuthRuntimeDeps } from './oauth-google.ts';\nexport { createOAuthAdapters } from './oauth-google.ts';\nexport * from './runtime.ts';\nexport { createStdioServer } from './stdio.ts';\n"],"names":["createConfig","createHTTPServer","createOAuthAdapters","createStdioServer","parseConfig"],"mappings":";;;;;;;;;;;QAASA;eAAAA,sBAAY;;QACZC;eAAAA,wBAAgB;;QAEhBC;eAAAA,kCAAmB;;QAEnBC;eAAAA,0BAAiB;;QALHC;eAAAA,qBAAW;;;wBAAQ;sBACT;6BAEG;qBACtB;uBACoB"}
|