@mcp-z/mcp-drive 2.0.0 → 2.1.1
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/dist/cjs/lib/google-auth.d.cts +9 -0
- package/dist/cjs/lib/google-auth.d.ts +9 -0
- package/dist/cjs/lib/google-auth.js +16 -0
- package/dist/cjs/lib/google-auth.js.map +1 -0
- package/dist/cjs/mcp/resources/file.js +4 -3
- package/dist/cjs/mcp/resources/file.js.map +1 -1
- package/dist/cjs/mcp/tools/file-move-to-trash.js +4 -3
- package/dist/cjs/mcp/tools/file-move-to-trash.js.map +1 -1
- package/dist/cjs/mcp/tools/file-move.js +4 -3
- package/dist/cjs/mcp/tools/file-move.js.map +1 -1
- package/dist/cjs/mcp/tools/file-upload.js +4 -3
- package/dist/cjs/mcp/tools/file-upload.js.map +1 -1
- package/dist/cjs/mcp/tools/files-search.js +4 -3
- package/dist/cjs/mcp/tools/files-search.js.map +1 -1
- package/dist/cjs/mcp/tools/folder-contents.js +4 -3
- package/dist/cjs/mcp/tools/folder-contents.js.map +1 -1
- package/dist/cjs/mcp/tools/folder-create.js +4 -3
- package/dist/cjs/mcp/tools/folder-create.js.map +1 -1
- package/dist/cjs/mcp/tools/folder-path.js +4 -3
- package/dist/cjs/mcp/tools/folder-path.js.map +1 -1
- package/dist/cjs/mcp/tools/folder-search.js +4 -3
- package/dist/cjs/mcp/tools/folder-search.js.map +1 -1
- package/dist/esm/lib/google-auth.d.ts +9 -0
- package/dist/esm/lib/google-auth.js +11 -0
- package/dist/esm/lib/google-auth.js.map +1 -0
- package/dist/esm/mcp/resources/file.js +4 -3
- package/dist/esm/mcp/resources/file.js.map +1 -1
- package/dist/esm/mcp/tools/file-move-to-trash.js +4 -3
- package/dist/esm/mcp/tools/file-move-to-trash.js.map +1 -1
- package/dist/esm/mcp/tools/file-move.js +4 -3
- package/dist/esm/mcp/tools/file-move.js.map +1 -1
- package/dist/esm/mcp/tools/file-upload.js +4 -3
- package/dist/esm/mcp/tools/file-upload.js.map +1 -1
- package/dist/esm/mcp/tools/files-search.js +4 -3
- package/dist/esm/mcp/tools/files-search.js.map +1 -1
- package/dist/esm/mcp/tools/folder-contents.js +4 -3
- package/dist/esm/mcp/tools/folder-contents.js.map +1 -1
- package/dist/esm/mcp/tools/folder-create.js +4 -3
- package/dist/esm/mcp/tools/folder-create.js.map +1 -1
- package/dist/esm/mcp/tools/folder-path.js +4 -3
- package/dist/esm/mcp/tools/folder-path.js.map +1 -1
- package/dist/esm/mcp/tools/folder-search.js +4 -3
- package/dist/esm/mcp/tools/folder-search.js.map +1 -1
- package/package.json +4 -4
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type GoogleAuthProvider } from '@mcp-z/oauth-google';
|
|
2
|
+
/**
|
|
3
|
+
* A Google API client bound to this request's token provider.
|
|
4
|
+
*
|
|
5
|
+
* `@mcp-z/oauth-google` mints tokens and depends on no Google SDK, so the client
|
|
6
|
+
* is built here, from this package's own SDK. That keeps one copy of
|
|
7
|
+
* `google-auth-library` in the tree by construction rather than by matching pins.
|
|
8
|
+
*/
|
|
9
|
+
export declare function googleAuth(auth: GoogleAuthProvider): import("google-auth-library").OAuth2Client;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type GoogleAuthProvider } from '@mcp-z/oauth-google';
|
|
2
|
+
/**
|
|
3
|
+
* A Google API client bound to this request's token provider.
|
|
4
|
+
*
|
|
5
|
+
* `@mcp-z/oauth-google` mints tokens and depends on no Google SDK, so the client
|
|
6
|
+
* is built here, from this package's own SDK. That keeps one copy of
|
|
7
|
+
* `google-auth-library` in the tree by construction rather than by matching pins.
|
|
8
|
+
*/
|
|
9
|
+
export declare function googleAuth(auth: GoogleAuthProvider): import("google-auth-library").OAuth2Client;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
Object.defineProperty(exports, "googleAuth", {
|
|
6
|
+
enumerable: true,
|
|
7
|
+
get: function() {
|
|
8
|
+
return googleAuth;
|
|
9
|
+
}
|
|
10
|
+
});
|
|
11
|
+
var _drive = require("@googleapis/drive");
|
|
12
|
+
var _oauthgoogle = require("@mcp-z/oauth-google");
|
|
13
|
+
function googleAuth(auth) {
|
|
14
|
+
return (0, _oauthgoogle.attachTokenProvider)(new _drive.auth.OAuth2(), auth);
|
|
15
|
+
}
|
|
16
|
+
/* CJS INTEROP */ if (exports.__esModule && exports.default) { try { Object.defineProperty(exports.default, '__esModule', { value: true }); for (var key in exports) { exports.default[key] = exports[key]; } } catch (_) {}; module.exports = exports.default; }
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/lib/google-auth.ts"],"sourcesContent":["import { auth as googleAuthPlus } from '@googleapis/drive';\nimport { attachTokenProvider, type GoogleAuthProvider } from '@mcp-z/oauth-google';\n\n/**\n * A Google API client bound to this request's token provider.\n *\n * `@mcp-z/oauth-google` mints tokens and depends on no Google SDK, so the client\n * is built here, from this package's own SDK. That keeps one copy of\n * `google-auth-library` in the tree by construction rather than by matching pins.\n */\nexport function googleAuth(auth: GoogleAuthProvider) {\n return attachTokenProvider(new googleAuthPlus.OAuth2(), auth);\n}\n"],"names":["googleAuth","auth","attachTokenProvider","googleAuthPlus","OAuth2"],"mappings":";;;;+BAUgBA;;;eAAAA;;;qBAVuB;2BACsB;AAStD,SAASA,WAAWC,IAAwB;IACjD,OAAOC,IAAAA,gCAAmB,EAAC,IAAIC,WAAc,CAACC,MAAM,IAAIH;AAC1D"}
|
|
@@ -8,8 +8,9 @@ Object.defineProperty(exports, "default", {
|
|
|
8
8
|
return createResource;
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
|
+
var _drive = require("@googleapis/drive");
|
|
11
12
|
var _server = require("@mcp-z/server");
|
|
12
|
-
var
|
|
13
|
+
var _googleauthts = require("../../lib/google-auth.js");
|
|
13
14
|
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
14
15
|
try {
|
|
15
16
|
var info = gen[key](arg);
|
|
@@ -178,9 +179,9 @@ function createResource() {
|
|
|
178
179
|
}
|
|
179
180
|
// Safe type guard to access middleware-enriched extra
|
|
180
181
|
logger = extra.logger, authContext = extra.authContext;
|
|
181
|
-
drive =
|
|
182
|
+
drive = (0, _drive.drive)({
|
|
182
183
|
version: 'v3',
|
|
183
|
-
auth: authContext.auth
|
|
184
|
+
auth: (0, _googleauthts.googleAuth)(authContext.auth)
|
|
184
185
|
});
|
|
185
186
|
return [
|
|
186
187
|
4,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/resources/file.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport type { ReadResourceResult, ResourceConfig, ResourceModule, ServerContext } from '@mcp-z/server';\nimport { ResourceTemplate } from '@mcp-z/server';\nimport {
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/resources/file.ts"],"sourcesContent":["import { drive as driveApi } from '@googleapis/drive';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport type { ReadResourceResult, ResourceConfig, ResourceModule, ServerContext } from '@mcp-z/server';\nimport { ResourceTemplate } from '@mcp-z/server';\nimport { googleAuth } from '../../lib/google-auth.ts';\n\nexport default function createResource(): ResourceModule {\n const template = new ResourceTemplate('drive://files/{fileId}', {\n list: undefined,\n });\n const config: ResourceConfig = {\n description: 'Drive file resource',\n mimeType: 'application/json',\n };\n\n const handler = async (uri: URL, variables: Record<string, string | string[]>, extra: ServerContext): Promise<ReadResourceResult> => {\n // Extract fileId and handle both string and string[] cases\n const fileId = Array.isArray(variables.fileId) ? variables.fileId[0] : variables.fileId;\n\n try {\n // Validate fileId exists and is a string\n if (!fileId || typeof fileId !== 'string') {\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify({\n error: 'Missing or invalid fileId in resource URI',\n }),\n },\n ],\n };\n }\n\n // Safe type guard to access middleware-enriched extra\n const { logger, authContext } = extra as unknown as EnrichedExtra;\n const drive = driveApi({ version: 'v3', auth: googleAuth(authContext.auth) });\n const resp = await drive.files.get({\n fileId,\n fields: 'id,name,mimeType,size,modifiedTime,owners,webViewLink',\n });\n const data = resp.data;\n logger.debug?.({ fileId, fileName: data?.name }, 'drive-file resource fetch success');\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify(data || {}),\n },\n ],\n };\n } catch (error) {\n const { logger } = extra as unknown as EnrichedExtra;\n logger.debug?.(error as Record<string, unknown>, 'drive resource fetch failed');\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify({ error: (error as Error).message }),\n },\n ],\n };\n }\n };\n\n return {\n name: 'file',\n template,\n config,\n handler,\n } satisfies ResourceModule;\n}\n"],"names":["createResource","template","ResourceTemplate","list","undefined","config","description","mimeType","handler","uri","variables","extra","fileId","logger","authContext","drive","resp","data","error","Array","isArray","contents","href","text","JSON","stringify","driveApi","version","auth","googleAuth","files","get","fields","debug","fileName","name","message"],"mappings":";;;;+BAMA;;;eAAwBA;;;qBANU;sBAGD;4BACN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEZ,SAASA;IACtB,IAAMC,WAAW,IAAIC,wBAAgB,CAAC,0BAA0B;QAC9DC,MAAMC;IACR;IACA,IAAMC,SAAyB;QAC7BC,aAAa;QACbC,UAAU;IACZ;IAEA,IAAMC,UAAU,iBAAOC,KAAUC,WAA8CC;;gBAEvEC,QA0BJC,eAPQA,QAAQC,aACVC,OACAC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;oCACzD;;4BAEJ;;;;;;;;QAEJ;;IAEA,OAAO;QACLD,MAAM;QACNlC,UAAAA;QACAI,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
@@ -9,9 +9,10 @@ Object.defineProperty(exports, "default", {
|
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
11
|
var _oauthgoogle = require("@mcp-z/oauth-google");
|
|
12
|
+
var _drive = require("@googleapis/drive");
|
|
12
13
|
var _server = require("@mcp-z/server");
|
|
13
|
-
var _googleapis = require("googleapis");
|
|
14
14
|
var _zod = require("zod");
|
|
15
|
+
var _googleauthts = require("../../lib/google-auth.js");
|
|
15
16
|
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
16
17
|
try {
|
|
17
18
|
var info = gen[key](arg);
|
|
@@ -220,9 +221,9 @@ function handler(_0, _1) {
|
|
|
220
221
|
,
|
|
221
222
|
4
|
|
222
223
|
]);
|
|
223
|
-
drive =
|
|
224
|
+
drive = (0, _drive.drive)({
|
|
224
225
|
version: 'v3',
|
|
225
|
-
auth: extra.authContext.auth
|
|
226
|
+
auth: (0, _googleauthts.googleAuth)(extra.authContext.auth)
|
|
226
227
|
});
|
|
227
228
|
return [
|
|
228
229
|
4,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/tools/file-move-to-trash.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { type CallToolResult, ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport {
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/tools/file-move-to-trash.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { drive as driveApi } from '@googleapis/drive';\nimport { type CallToolResult, ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\n\nconst MAX_BATCH_SIZE = 1000;\n\nconst inputSchema = z.object({\n ids: z.array(z.string().min(1)).min(1).max(MAX_BATCH_SIZE).describe('File IDs to soft delete (move to trash)'),\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n operationSummary: z.string().describe('Human-readable summary of the operation'),\n totalCount: z.number().describe('Total number of files requested to trash'),\n successCount: z.number().describe('Number of files successfully moved to trash'),\n failureCount: z.number().describe('Number of files that failed to move'),\n recoverable: z.boolean().describe('Whether trashed files can be restored'),\n recoverableDays: z.number().describe('Days until permanent deletion'),\n failures: z\n .array(\n z.object({\n id: z.string().describe('ID of the file that failed'),\n error: z.string().describe('Error message explaining the failure'),\n })\n )\n .optional()\n .describe('Details of any files that failed to trash'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n title: 'Move Files to Trash',\n description: 'Move files to trash (recoverable for 30 days).',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ ids }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('drive.file.moveToTrash called', { count: ids.length });\n\n try {\n const drive = driveApi({ version: 'v3', auth: googleAuth(extra.authContext.auth) });\n\n const results = await Promise.allSettled(\n ids.map(async (id) => {\n await drive.files.update({\n fileId: id,\n requestBody: { trashed: true },\n });\n return id;\n })\n );\n\n // Separate successes and failures\n const failures: Array<{ id: string; error: string }> = [];\n\n results.forEach((result, index) => {\n const id = ids[index];\n if (!id) return;\n\n if (result.status === 'rejected') {\n const errorMessage = result.reason instanceof Error ? result.reason.message : String(result.reason);\n failures.push({ id, error: errorMessage });\n }\n });\n\n const successCount = ids.length - failures.length;\n const failureCount = failures.length;\n const totalCount = ids.length;\n\n logger.info('drive.file.moveToTrash completed', {\n totalCount,\n successCount,\n failureCount,\n });\n\n const operationSummary = failureCount === 0 ? `Moved ${successCount} file${successCount === 1 ? '' : 's'} to trash (recoverable for 30 days)` : `Moved ${successCount} of ${totalCount} file${totalCount === 1 ? '' : 's'} to trash (${failureCount} failed, recoverable for 30 days)`;\n\n const result: Output = {\n type: 'success' as const,\n operationSummary,\n totalCount,\n successCount,\n failureCount,\n recoverable: true,\n recoverableDays: 30,\n ...(failures.length > 0 && { failures }),\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('drive.file.moveToTrash error', { error: message });\n\n // Throw ProtocolError\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error moving files to trash: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'file-move-to-trash' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","MAX_BATCH_SIZE","inputSchema","z","object","ids","array","string","min","max","describe","successBranchSchema","type","literal","operationSummary","totalCount","number","successCount","failureCount","recoverable","boolean","recoverableDays","failures","id","error","optional","outputSchema","discriminatedUnion","config","title","description","result","handler","extra","logger","drive","results","message","info","count","length","driveApi","version","auth","googleAuth","authContext","Promise","allSettled","map","files","update","fileId","requestBody","trashed","forEach","index","status","errorMessage","reason","Error","String","push","content","text","JSON","stringify","structuredContent","ProtocolError","ProtocolErrorCode","InternalError","stack","undefined","name"],"mappings":";;;;+BA4HA;;;eAAwBA;;;2BA3HA;qBAIU;sBACoC;mBACpD;4BACS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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oBAEMJ,mBAAmBI,iBAAiB,IAAI,AAAC,SAA4BD,OAApBA,cAAa,SAAqC,OAA9BA,iBAAiB,IAAI,KAAK,KAAI,yCAAuC,AAAC,SAA2BF,OAAnBE,cAAa,QAAwBF,OAAlBA,YAAW,SAAgDG,OAAzCH,eAAe,IAAI,KAAK,KAAI,eAA0B,OAAbG,cAAa;oBAE9Oa,SAAiB;wBACrBnB,MAAM;wBACNE,kBAAAA;wBACAC,YAAAA;wBACAE,cAAAA;wBACAC,cAAAA;wBACAC,aAAa;wBACbE,iBAAiB;uBACbC,SAASkB,MAAM,GAAG,KAAK;wBAAElB,UAAAA;oBAAS;oBAGxC;;wBAAO;4BACLwC,OAAO;gCACL;oCACElD,MAAM;oCACNmD,MAAMC,KAAKC,SAAS,CAAClC;gCACvB;;4BAEFmC,mBAAmB;gCAAEnC,QAAAA;4BAAO;wBAC9B;;;oBACOP;oBACDa,UAAUb,AAAK,YAALA,OAAiBmC,SAAQnC,MAAMa,OAAO,GAAGuB,OAAOpC;oBAChEU,OAAOV,KAAK,CAAC,gCAAgC;wBAAEA,OAAOa;oBAAQ;oBAE9D,sBAAsB;oBACtB,MAAM,IAAI8B,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,gCAAuC,OAARhC,UAAW;wBAClGiC,OAAO9C,AAAK,YAALA,OAAiBmC,SAAQnC,MAAM8C,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAASzE;IACtB,OAAO;QACL0E,MAAM;QACN5C,QAAAA;QACAI,SAAAA;IACF;AACF"}
|
|
@@ -9,9 +9,10 @@ Object.defineProperty(exports, "default", {
|
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
11
|
var _oauthgoogle = require("@mcp-z/oauth-google");
|
|
12
|
+
var _drive = require("@googleapis/drive");
|
|
12
13
|
var _server = require("@mcp-z/server");
|
|
13
|
-
var _googleapis = require("googleapis");
|
|
14
14
|
var _zod = require("zod");
|
|
15
|
+
var _googleauthts = require("../../lib/google-auth.js");
|
|
15
16
|
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
16
17
|
try {
|
|
17
18
|
var info = gen[key](arg);
|
|
@@ -507,9 +508,9 @@ function handler(_0, _1) {
|
|
|
507
508
|
,
|
|
508
509
|
7
|
|
509
510
|
]);
|
|
510
|
-
drive =
|
|
511
|
+
drive = (0, _drive.drive)({
|
|
511
512
|
version: 'v3',
|
|
512
|
-
auth: extra.authContext.auth
|
|
513
|
+
auth: (0, _googleauthts.googleAuth)(extra.authContext.auth)
|
|
513
514
|
});
|
|
514
515
|
moved = [];
|
|
515
516
|
failed = [];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/tools/file-move.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { type CallToolResult, ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport type { drive_v3 } from 'googleapis';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport type { Logger } from '../../types.ts';\n\n// Type guard for Google Drive API errors\ninterface DriveApiError {\n message?: string;\n code?: number | string;\n}\n\nfunction isDriveApiError(error: unknown): error is DriveApiError {\n return typeof error === 'object' && error !== null && ('message' in error || 'code' in error);\n}\n\n// Types for results\ninterface MoveResult {\n fileId: string;\n fileName: string;\n oldParents: string[];\n newParent: string;\n webViewLink?: string;\n}\n\ninterface FailedMove {\n fileId: string;\n error: string;\n code?: string;\n}\n\nconst inputSchema = z.object({\n fileIds: z.union([z.string().min(1), z.array(z.string().min(1)).min(1).max(100)]).describe('File or folder ID(s) to move. Single ID or array (max 100 for batch)'),\n destinationFolderId: z.string().min(1).describe('Destination folder ID (use \"root\" for My Drive root)'),\n returnOldParents: z.boolean().optional().describe('Include old parent IDs in response for manual undo (recommended: true)'),\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n moved: z\n .array(\n z.object({\n fileId: z.string().describe('ID of the moved file'),\n fileName: z.string().describe('Name of the moved file'),\n oldParents: z.array(z.string()).describe('Previous parent folder IDs (for undo)'),\n newParent: z.string().describe('New parent folder ID'),\n webViewLink: z.string().optional().describe('URL to view the file'),\n })\n )\n .describe('Successfully moved files'),\n failed: z\n .array(\n z.object({\n fileId: z.string().describe('ID of the file that failed to move'),\n error: z.string().describe('Error message explaining the failure'),\n code: z.string().optional().describe('API error code if available'),\n })\n )\n .optional()\n .describe('Files that failed to move'),\n totalRequested: z.number().describe('Total number of files requested to move'),\n totalMoved: z.number().describe('Number of files successfully moved'),\n totalFailed: z.number().describe('Number of files that failed to move'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n title: 'Move Files',\n description: 'Move files/folders to destination folder. Returns oldParents for undo. Use \"root\" for My Drive root.',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\n/**\n * Move a single file to a new parent folder\n */\nasync function moveSingleFile(\n drive: drive_v3.Drive,\n fileId: string,\n destinationFolderId: string,\n returnOldParents: boolean,\n logger: Logger\n): Promise<{\n success: boolean;\n result?: MoveResult;\n error?: FailedMove;\n}> {\n try {\n // Get current file metadata to get old parents\n const fileMetadata = await drive.files.get({\n fileId: fileId,\n fields: 'id,name,parents,webViewLink',\n });\n\n const oldParents = (fileMetadata.data.parents as string[] | undefined) || [];\n const fileName = (fileMetadata.data.name as string | undefined) || fileId;\n const webViewLink = fileMetadata.data.webViewLink as string | undefined;\n\n // Move file using addParents and removeParents\n await drive.files.update({\n fileId: fileId,\n addParents: destinationFolderId,\n removeParents: oldParents.join(','),\n fields: 'id,name,parents,webViewLink',\n });\n\n const result: MoveResult = {\n fileId: fileId,\n fileName: fileName,\n oldParents: returnOldParents ? oldParents : [],\n newParent: destinationFolderId,\n ...(webViewLink && { webViewLink }),\n };\n\n return { success: true, result };\n } catch (e: unknown) {\n const errorMessage = isDriveApiError(e) && e.message ? e.message : 'Unknown error';\n const errorCode = isDriveApiError(e) && e.code ? String(e.code) : undefined;\n logger.info('Failed to move file', { fileId, error: errorMessage });\n return {\n success: false,\n error: {\n fileId: fileId,\n error: errorMessage,\n ...(errorCode && { code: errorCode }),\n },\n };\n }\n}\n\n/**\n * Move multiple files using batch requests\n */\nasync function moveBatchFiles(\n drive: drive_v3.Drive,\n fileIds: string[],\n destinationFolderId: string,\n returnOldParents: boolean,\n _logger: Logger\n): Promise<{\n moved: MoveResult[];\n failed: FailedMove[];\n}> {\n const moved: MoveResult[] = [];\n const failed: FailedMove[] = [];\n\n // First, fetch metadata for all files in batch\n const metadataResults = await Promise.allSettled(\n fileIds.map(async (fileId) => {\n try {\n const response = await drive.files.get({\n fileId: fileId,\n fields: 'id,name,parents,webViewLink',\n });\n const webViewLink = response.data.webViewLink as string | undefined;\n return {\n fileId: fileId,\n name: (response.data.name as string | undefined) || fileId,\n parents: (response.data.parents as string[] | undefined) || [],\n ...(webViewLink && { webViewLink }),\n };\n } catch (e: unknown) {\n const message = isDriveApiError(e) && e.message ? e.message : String(e);\n throw new Error(`Failed to fetch metadata: ${message}`);\n }\n })\n );\n\n // Process metadata results\n const filesToMove: Array<{\n fileId: string;\n name: string;\n parents: string[];\n webViewLink?: string;\n }> = [];\n for (let i = 0; i < metadataResults.length; i++) {\n const result = metadataResults[i];\n if (result && result.status === 'fulfilled') {\n filesToMove.push(result.value);\n } else if (result && result.status === 'rejected') {\n const fileId = fileIds[i];\n if (fileId) {\n const errorCode = result.reason?.code ? String(result.reason.code) : undefined;\n failed.push({\n fileId: fileId,\n error: result.reason?.message || 'Failed to fetch file metadata',\n ...(errorCode && { code: errorCode }),\n });\n }\n }\n }\n\n // Now move files in batch\n const moveResults = await Promise.allSettled(\n filesToMove.map(async (file) => {\n try {\n await drive.files.update({\n fileId: file.fileId,\n addParents: destinationFolderId,\n removeParents: file.parents.join(','),\n fields: 'id',\n });\n return {\n fileId: file.fileId,\n fileName: file.name,\n oldParents: returnOldParents ? file.parents : [],\n newParent: destinationFolderId,\n ...(file.webViewLink && { webViewLink: file.webViewLink }),\n };\n } catch (e: unknown) {\n const message = isDriveApiError(e) && e.message ? e.message : String(e);\n throw new Error(`Failed to move: ${message}`);\n }\n })\n );\n\n // Process move results\n for (let i = 0; i < moveResults.length; i++) {\n const result = moveResults[i];\n if (result && result.status === 'fulfilled') {\n moved.push(result.value);\n } else if (result && result.status === 'rejected') {\n const file = filesToMove[i];\n if (file) {\n const errorCode = result.reason?.code ? String(result.reason.code) : undefined;\n failed.push({\n fileId: file.fileId,\n error: result.reason?.message || 'Failed to move file',\n ...(errorCode && { code: errorCode }),\n });\n }\n }\n }\n\n return { moved, failed };\n}\n\nasync function handler({ fileIds, destinationFolderId, returnOldParents = true }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n const isBatch = Array.isArray(fileIds);\n const fileIdArray = Array.isArray(fileIds) ? fileIds : [fileIds];\n\n logger.info('drive.file.move called', {\n fileCount: fileIdArray.length,\n isBatch,\n destinationFolderId,\n returnOldParents,\n });\n\n try {\n const drive = google.drive({ version: 'v3', auth: extra.authContext.auth });\n\n let moved: MoveResult[] = [];\n let failed: FailedMove[] = [];\n\n if (isBatch && fileIdArray.length > 1) {\n // Use batch API for multiple files\n const batchResult = await moveBatchFiles(drive, fileIdArray, destinationFolderId, returnOldParents, logger);\n moved = batchResult.moved;\n failed = batchResult.failed;\n } else {\n // Single file operation\n const fileId = fileIdArray[0];\n if (fileId) {\n const singleResult = await moveSingleFile(drive, fileId, destinationFolderId, returnOldParents, logger);\n if (singleResult.success && singleResult.result) {\n moved.push(singleResult.result);\n } else if (singleResult.error) {\n failed.push(singleResult.error);\n }\n }\n }\n\n logger.info('drive.file.move returning', {\n totalRequested: fileIdArray.length,\n totalMoved: moved.length,\n totalFailed: failed.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n moved,\n ...(failed.length > 0 && { failed }),\n totalRequested: fileIdArray.length,\n totalMoved: moved.length,\n totalFailed: failed.length,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('drive.file.move error', { error: message });\n\n // Throw ProtocolError\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error moving files: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'file-move' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","isDriveApiError","error","inputSchema","z","object","fileIds","union","string","min","array","max","describe","destinationFolderId","returnOldParents","boolean","optional","successBranchSchema","type","literal","moved","fileId","fileName","oldParents","newParent","webViewLink","failed","code","totalRequested","number","totalMoved","totalFailed","outputSchema","discriminatedUnion","config","title","description","result","moveSingleFile","drive","logger","fileMetadata","e","errorMessage","errorCode","files","get","fields","data","parents","name","update","addParents","removeParents","join","success","message","String","undefined","info","moveBatchFiles","_logger","metadataResults","filesToMove","i","moveResults","file","Promise","allSettled","map","response","Error","length","status","push","value","reason","handler","extra","isBatch","fileIdArray","batchResult","singleResult","Array","isArray","fileCount","google","version","auth","authContext","content","text","JSON","stringify","structuredContent","ProtocolError","ProtocolErrorCode","InternalError","stack"],"mappings":";;;;+BAiUA;;;eAAwBA;;;2BAhUA;sBAI8C;0BAE/C;mBACL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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OAAO8C,MAAM;;oBAG5B;;wBAAO;4BACLkB,OAAO;gCACL;oCACExE,MAAM;oCACNyE,MAAMC,KAAKC,SAAS,CAACxD;gCACvB;;4BAEFyD,mBAAmB;gCAAEzD,QAAAA;4BAAO;wBAC9B;;;oBACOnC;oBACDsD,UAAUtD,AAAK,YAALA,OAAiBqE,SAAQrE,MAAMsD,OAAO,GAAGC,OAAOvD;oBAChEsC,OAAOtC,KAAK,CAAC,yBAAyB;wBAAEA,OAAOsD;oBAAQ;oBAEvD,sBAAsB;oBACtB,MAAM,IAAIuC,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,uBAA8B,OAARzC,UAAW;wBACzF0C,OAAOhG,AAAK,YAALA,OAAiBqE,SAAQrE,MAAMgG,KAAK,GAAGxC;oBAChD;;;;;;;IAEJ;;AAEe,SAAS5D;IACtB,OAAO;QACLoD,MAAM;QACNhB,QAAAA;QACA2C,SAAAA;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/tools/file-move.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { drive_v3 } from '@googleapis/drive';\nimport { drive as driveApi } from '@googleapis/drive';\nimport { type CallToolResult, ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport type { Logger } from '../../types.ts';\n\n// Type guard for Google Drive API errors\ninterface DriveApiError {\n message?: string;\n code?: number | string;\n}\n\nfunction isDriveApiError(error: unknown): error is DriveApiError {\n return typeof error === 'object' && error !== null && ('message' in error || 'code' in error);\n}\n\n// Types for results\ninterface MoveResult {\n fileId: string;\n fileName: string;\n oldParents: string[];\n newParent: string;\n webViewLink?: string;\n}\n\ninterface FailedMove {\n fileId: string;\n error: string;\n code?: string;\n}\n\nconst inputSchema = z.object({\n fileIds: z.union([z.string().min(1), z.array(z.string().min(1)).min(1).max(100)]).describe('File or folder ID(s) to move. Single ID or array (max 100 for batch)'),\n destinationFolderId: z.string().min(1).describe('Destination folder ID (use \"root\" for My Drive root)'),\n returnOldParents: z.boolean().optional().describe('Include old parent IDs in response for manual undo (recommended: true)'),\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n moved: z\n .array(\n z.object({\n fileId: z.string().describe('ID of the moved file'),\n fileName: z.string().describe('Name of the moved file'),\n oldParents: z.array(z.string()).describe('Previous parent folder IDs (for undo)'),\n newParent: z.string().describe('New parent folder ID'),\n webViewLink: z.string().optional().describe('URL to view the file'),\n })\n )\n .describe('Successfully moved files'),\n failed: z\n .array(\n z.object({\n fileId: z.string().describe('ID of the file that failed to move'),\n error: z.string().describe('Error message explaining the failure'),\n code: z.string().optional().describe('API error code if available'),\n })\n )\n .optional()\n .describe('Files that failed to move'),\n totalRequested: z.number().describe('Total number of files requested to move'),\n totalMoved: z.number().describe('Number of files successfully moved'),\n totalFailed: z.number().describe('Number of files that failed to move'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n title: 'Move Files',\n description: 'Move files/folders to destination folder. Returns oldParents for undo. Use \"root\" for My Drive root.',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\n/**\n * Move a single file to a new parent folder\n */\nasync function moveSingleFile(\n drive: drive_v3.Drive,\n fileId: string,\n destinationFolderId: string,\n returnOldParents: boolean,\n logger: Logger\n): Promise<{\n success: boolean;\n result?: MoveResult;\n error?: FailedMove;\n}> {\n try {\n // Get current file metadata to get old parents\n const fileMetadata = await drive.files.get({\n fileId: fileId,\n fields: 'id,name,parents,webViewLink',\n });\n\n const oldParents = (fileMetadata.data.parents as string[] | undefined) || [];\n const fileName = (fileMetadata.data.name as string | undefined) || fileId;\n const webViewLink = fileMetadata.data.webViewLink as string | undefined;\n\n // Move file using addParents and removeParents\n await drive.files.update({\n fileId: fileId,\n addParents: destinationFolderId,\n removeParents: oldParents.join(','),\n fields: 'id,name,parents,webViewLink',\n });\n\n const result: MoveResult = {\n fileId: fileId,\n fileName: fileName,\n oldParents: returnOldParents ? oldParents : [],\n newParent: destinationFolderId,\n ...(webViewLink && { webViewLink }),\n };\n\n return { success: true, result };\n } catch (e: unknown) {\n const errorMessage = isDriveApiError(e) && e.message ? e.message : 'Unknown error';\n const errorCode = isDriveApiError(e) && e.code ? String(e.code) : undefined;\n logger.info('Failed to move file', { fileId, error: errorMessage });\n return {\n success: false,\n error: {\n fileId: fileId,\n error: errorMessage,\n ...(errorCode && { code: errorCode }),\n },\n };\n }\n}\n\n/**\n * Move multiple files using batch requests\n */\nasync function moveBatchFiles(\n drive: drive_v3.Drive,\n fileIds: string[],\n destinationFolderId: string,\n returnOldParents: boolean,\n _logger: Logger\n): Promise<{\n moved: MoveResult[];\n failed: FailedMove[];\n}> {\n const moved: MoveResult[] = [];\n const failed: FailedMove[] = [];\n\n // First, fetch metadata for all files in batch\n const metadataResults = await Promise.allSettled(\n fileIds.map(async (fileId) => {\n try {\n const response = await drive.files.get({\n fileId: fileId,\n fields: 'id,name,parents,webViewLink',\n });\n const webViewLink = response.data.webViewLink as string | undefined;\n return {\n fileId: fileId,\n name: (response.data.name as string | undefined) || fileId,\n parents: (response.data.parents as string[] | undefined) || [],\n ...(webViewLink && { webViewLink }),\n };\n } catch (e: unknown) {\n const message = isDriveApiError(e) && e.message ? e.message : String(e);\n throw new Error(`Failed to fetch metadata: ${message}`);\n }\n })\n );\n\n // Process metadata results\n const filesToMove: Array<{\n fileId: string;\n name: string;\n parents: string[];\n webViewLink?: string;\n }> = [];\n for (let i = 0; i < metadataResults.length; i++) {\n const result = metadataResults[i];\n if (result && result.status === 'fulfilled') {\n filesToMove.push(result.value);\n } else if (result && result.status === 'rejected') {\n const fileId = fileIds[i];\n if (fileId) {\n const errorCode = result.reason?.code ? String(result.reason.code) : undefined;\n failed.push({\n fileId: fileId,\n error: result.reason?.message || 'Failed to fetch file metadata',\n ...(errorCode && { code: errorCode }),\n });\n }\n }\n }\n\n // Now move files in batch\n const moveResults = await Promise.allSettled(\n filesToMove.map(async (file) => {\n try {\n await drive.files.update({\n fileId: file.fileId,\n addParents: destinationFolderId,\n removeParents: file.parents.join(','),\n fields: 'id',\n });\n return {\n fileId: file.fileId,\n fileName: file.name,\n oldParents: returnOldParents ? file.parents : [],\n newParent: destinationFolderId,\n ...(file.webViewLink && { webViewLink: file.webViewLink }),\n };\n } catch (e: unknown) {\n const message = isDriveApiError(e) && e.message ? e.message : String(e);\n throw new Error(`Failed to move: ${message}`);\n }\n })\n );\n\n // Process move results\n for (let i = 0; i < moveResults.length; i++) {\n const result = moveResults[i];\n if (result && result.status === 'fulfilled') {\n moved.push(result.value);\n } else if (result && result.status === 'rejected') {\n const file = filesToMove[i];\n if (file) {\n const errorCode = result.reason?.code ? String(result.reason.code) : undefined;\n failed.push({\n fileId: file.fileId,\n error: result.reason?.message || 'Failed to move file',\n ...(errorCode && { code: errorCode }),\n });\n }\n }\n }\n\n return { moved, failed };\n}\n\nasync function handler({ fileIds, destinationFolderId, returnOldParents = true }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n const isBatch = Array.isArray(fileIds);\n const fileIdArray = Array.isArray(fileIds) ? fileIds : [fileIds];\n\n logger.info('drive.file.move called', {\n fileCount: fileIdArray.length,\n isBatch,\n destinationFolderId,\n returnOldParents,\n });\n\n try {\n const drive = driveApi({ version: 'v3', auth: googleAuth(extra.authContext.auth) });\n\n let moved: MoveResult[] = [];\n let failed: FailedMove[] = [];\n\n if (isBatch && fileIdArray.length > 1) {\n // Use batch API for multiple files\n const batchResult = await moveBatchFiles(drive, fileIdArray, destinationFolderId, returnOldParents, logger);\n moved = batchResult.moved;\n failed = batchResult.failed;\n } else {\n // Single file operation\n const fileId = fileIdArray[0];\n if (fileId) {\n const singleResult = await moveSingleFile(drive, fileId, destinationFolderId, returnOldParents, logger);\n if (singleResult.success && singleResult.result) {\n moved.push(singleResult.result);\n } else if (singleResult.error) {\n failed.push(singleResult.error);\n }\n }\n }\n\n logger.info('drive.file.move returning', {\n totalRequested: fileIdArray.length,\n totalMoved: moved.length,\n totalFailed: failed.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n moved,\n ...(failed.length > 0 && { failed }),\n totalRequested: fileIdArray.length,\n totalMoved: moved.length,\n totalFailed: failed.length,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('drive.file.move error', { error: message });\n\n // Throw ProtocolError\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error moving files: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'file-move' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","isDriveApiError","error","inputSchema","z","object","fileIds","union","string","min","array","max","describe","destinationFolderId","returnOldParents","boolean","optional","successBranchSchema","type","literal","moved","fileId","fileName","oldParents","newParent","webViewLink","failed","code","totalRequested","number","totalMoved","totalFailed","outputSchema","discriminatedUnion","config","title","description","result","moveSingleFile","drive","logger","fileMetadata","e","errorMessage","errorCode","files","get","fields","data","parents","name","update","addParents","removeParents","join","success","message","String","undefined","info","moveBatchFiles","_logger","metadataResults","filesToMove","i","moveResults","file","Promise","allSettled","map","response","Error","length","status","push","value","reason","handler","extra","isBatch","fileIdArray","batchResult","singleResult","Array","isArray","fileCount","driveApi","version","auth","googleAuth","authContext","content","text","JSON","stringify","structuredContent","ProtocolError","ProtocolErrorCode","InternalError","stack"],"mappings":";;;;+BAkUA;;;eAAwBA;;;2BAjUA;qBA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AM;wBAClC1C,YAAYV,MAAMoD,MAAM;wBACxBzC,aAAaL,OAAO8C,MAAM;oBAC5B;oBAEMnC,SAAiB;wBACrBnB,MAAM;wBACNE,OAAAA;uBACIM,OAAO8C,MAAM,GAAG,KAAK;wBAAE9C,QAAAA;oBAAO;wBAClCE,gBAAgBoD,YAAYR,MAAM;wBAClC1C,YAAYV,MAAMoD,MAAM;wBACxBzC,aAAaL,OAAO8C,MAAM;;oBAG5B;;wBAAO;4BACLmB,OAAO;gCACL;oCACEzE,MAAM;oCACN0E,MAAMC,KAAKC,SAAS,CAACzD;gCACvB;;4BAEF0D,mBAAmB;gCAAE1D,QAAAA;4BAAO;wBAC9B;;;oBACOnC;oBACDsD,UAAUtD,AAAK,YAALA,OAAiBqE,SAAQrE,MAAMsD,OAAO,GAAGC,OAAOvD;oBAChEsC,OAAOtC,KAAK,CAAC,yBAAyB;wBAAEA,OAAOsD;oBAAQ;oBAEvD,sBAAsB;oBACtB,MAAM,IAAIwC,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,uBAA8B,OAAR1C,UAAW;wBACzF2C,OAAOjG,AAAK,YAALA,OAAiBqE,SAAQrE,MAAMiG,KAAK,GAAGzC;oBAChD;;;;;;;IAEJ;;AAEe,SAAS5D;IACtB,OAAO;QACLoD,MAAM;QACNhB,QAAAA;QACA2C,SAAAA;IACF;AACF"}
|
|
@@ -9,10 +9,11 @@ Object.defineProperty(exports, "default", {
|
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
11
|
var _oauthgoogle = require("@mcp-z/oauth-google");
|
|
12
|
+
var _drive = require("@googleapis/drive");
|
|
12
13
|
var _server = require("@mcp-z/server");
|
|
13
|
-
var _googleapis = require("googleapis");
|
|
14
14
|
var _zod = require("zod");
|
|
15
15
|
var _filestreamingts = require("../../lib/file-streaming.js");
|
|
16
|
+
var _googleauthts = require("../../lib/google-auth.js");
|
|
16
17
|
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
17
18
|
try {
|
|
18
19
|
var info = gen[key](arg);
|
|
@@ -227,9 +228,9 @@ function handler(_0, _1) {
|
|
|
227
228
|
,
|
|
228
229
|
10
|
|
229
230
|
]);
|
|
230
|
-
drive =
|
|
231
|
+
drive = (0, _drive.drive)({
|
|
231
232
|
version: 'v3',
|
|
232
|
-
auth: extra.authContext.auth
|
|
233
|
+
auth: (0, _googleauthts.googleAuth)(extra.authContext.auth)
|
|
233
234
|
});
|
|
234
235
|
return [
|
|
235
236
|
4,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/tools/file-upload.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { getFileReadStream, guessMimeType } from '../../lib/file-streaming.ts';\n\nconst inputSchema = z.object({\n sourceUri: z.string().trim().min(1).describe('File URI to upload (file://, http://, https://)'),\n name: z.string().trim().min(1).optional().describe('File name in Drive, including extension (defaults to the source file name)'),\n mimeType: z.string().trim().min(1).optional().describe('MIME type, e.g. application/pdf (defaults to the Content-Type header or detection from the file extension)'),\n parentId: z.string().optional().describe('Parent folder ID (omit to upload to My Drive root)'),\n description: z.string().optional().describe('Description to store in the file metadata'),\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n operationSummary: z.string().describe('Summary of the file upload operation'),\n itemsProcessed: z.number().describe('Total items attempted (always 1 for single file)'),\n itemsChanged: z.number().describe('Successfully uploaded files (always 1 on success)'),\n completedAt: z.string().describe('ISO datetime when operation completed'),\n id: z.string().describe('ID of the uploaded file'),\n name: z.string().describe('Name of the uploaded file'),\n mimeType: z.string().describe('MIME type of the uploaded file'),\n size: z.string().describe('Size of the uploaded file in bytes'),\n webViewLink: z.string().describe('URL to view the file in Drive'),\n parentId: z.string().optional().describe('ID of the parent folder'),\n parentName: z.string().optional().describe('Name of the parent folder'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n title: 'Upload File',\n description: 'Upload a file to Google Drive from a file:// or http(s):// URI. Content is streamed from the source (no temp files) in a single multipart request. Returns file ID for use in other operations.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\n// Export types for strong typing in tests\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ sourceUri, name, mimeType, parentId, description }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('drive.file.upload called', {\n sourceUri,\n name: name || 'auto',\n parentId: parentId || 'root',\n });\n\n try {\n const drive = google.drive({ version: 'v3', auth: extra.authContext.auth });\n\n // Stream source content directly from URI (no temp files)\n const source = await getFileReadStream(sourceUri);\n const finalName = name || source.fileName;\n const finalMimeType = mimeType || source.contentType || guessMimeType(finalName);\n\n // Create the file with streamed content (multipart upload; the client pipes the\n // stream body through without buffering it into memory)\n const response = await drive.files.create({\n requestBody: {\n name: finalName,\n mimeType: finalMimeType,\n parents: parentId ? [parentId] : null,\n ...(description && { description }),\n },\n media: { mimeType: finalMimeType, body: source.stream },\n supportsAllDrives: true,\n fields: 'id,name,mimeType,size,webViewLink,parents',\n });\n\n const res = response.data;\n const id = res.id ?? '';\n const resultName = res.name ?? finalName;\n const resultMimeType = res.mimeType ?? finalMimeType;\n const size = res.size ?? String(source.size ?? 0);\n const webViewLink = res.webViewLink ?? '';\n const parents = (res.parents as string[] | undefined) || [];\n\n // Fetch parent name if parentId was provided\n let parentName: string | undefined;\n let actualParentId: string | undefined;\n\n if (parents.length > 0) {\n actualParentId = parents[0];\n\n if (actualParentId === 'root') {\n parentName = 'My Drive';\n } else if (actualParentId) {\n try {\n const parentResponse = await drive.files.get({\n fileId: actualParentId,\n fields: 'name',\n });\n parentName = (parentResponse.data.name as string | undefined) || actualParentId;\n } catch (e) {\n logger.info('Failed to fetch parent name', {\n parentId: actualParentId,\n error: e,\n });\n parentName = actualParentId; // Fallback to ID\n }\n }\n }\n\n const locationSummary = parentName ? ` in \"${parentName}\"` : ' in My Drive';\n\n logger.info('drive.file.upload success', {\n id,\n name: resultName,\n size,\n parentId: actualParentId,\n });\n\n // Build result object with operation metadata\n const result: Output = {\n type: 'success' as const,\n operationSummary: `Uploaded \"${resultName}\"${locationSummary}`,\n itemsProcessed: 1,\n itemsChanged: 1,\n completedAt: new Date().toISOString(),\n id,\n name: resultName,\n mimeType: resultMimeType,\n size,\n webViewLink,\n ...(actualParentId && { parentId: actualParentId }),\n ...(parentName && { parentName }),\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('drive.file.upload error', { error: message });\n\n // Throw ProtocolError for proper MCP error handling\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error uploading file: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'file-upload' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","sourceUri","string","trim","min","describe","name","optional","mimeType","parentId","description","successBranchSchema","type","literal","operationSummary","itemsProcessed","number","itemsChanged","completedAt","id","size","webViewLink","parentName","outputSchema","discriminatedUnion","config","title","result","handler","extra","logger","res","source","drive","finalName","finalMimeType","response","resultName","resultMimeType","parents","actualParentId","parentResponse","e","locationSummary","error","message","info","google","version","auth","authContext","getFileReadStream","fileName","contentType","guessMimeType","files","create","requestBody","media","body","stream","supportsAllDrives","fields","data","String","length","get","fileId","Date","toISOString","content","text","JSON","stringify","structuredContent","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mcp-z/mcp-drive/src/mcp/tools/file-upload.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { drive as driveApi } from '@googleapis/drive';\nimport type { CallToolResult } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { getFileReadStream, guessMimeType } from '../../lib/file-streaming.ts';\nimport { googleAuth } from '../../lib/google-auth.ts';\n\nconst inputSchema = z.object({\n sourceUri: z.string().trim().min(1).describe('File URI to upload (file://, http://, https://)'),\n name: z.string().trim().min(1).optional().describe('File name in Drive, including extension (defaults to the source file name)'),\n mimeType: z.string().trim().min(1).optional().describe('MIME type, e.g. application/pdf (defaults to the Content-Type header or detection from the file extension)'),\n parentId: z.string().optional().describe('Parent folder ID (omit to upload to My Drive root)'),\n description: z.string().optional().describe('Description to store in the file metadata'),\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n operationSummary: z.string().describe('Summary of the file upload operation'),\n itemsProcessed: z.number().describe('Total items attempted (always 1 for single file)'),\n itemsChanged: z.number().describe('Successfully uploaded files (always 1 on success)'),\n completedAt: z.string().describe('ISO datetime when operation completed'),\n id: z.string().describe('ID of the uploaded file'),\n name: z.string().describe('Name of the uploaded file'),\n mimeType: z.string().describe('MIME type of the uploaded file'),\n size: z.string().describe('Size of the uploaded file in bytes'),\n webViewLink: z.string().describe('URL to view the file in Drive'),\n parentId: z.string().optional().describe('ID of the parent folder'),\n parentName: z.string().optional().describe('Name of the parent folder'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n title: 'Upload File',\n description: 'Upload a file to Google Drive from a file:// or http(s):// URI. Content is streamed from the source (no temp files) in a single multipart request. Returns file ID for use in other operations.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\n// Export types for strong typing in tests\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ sourceUri, name, mimeType, parentId, description }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('drive.file.upload called', {\n sourceUri,\n name: name || 'auto',\n parentId: parentId || 'root',\n });\n\n try {\n const drive = driveApi({ version: 'v3', auth: googleAuth(extra.authContext.auth) });\n\n // Stream source content directly from URI (no temp files)\n const source = await getFileReadStream(sourceUri);\n const finalName = name || source.fileName;\n const finalMimeType = mimeType || source.contentType || guessMimeType(finalName);\n\n // Create the file with streamed content (multipart upload; the client pipes the\n // stream body through without buffering it into memory)\n const response = await drive.files.create({\n requestBody: {\n name: finalName,\n mimeType: finalMimeType,\n parents: parentId ? [parentId] : null,\n ...(description && { description }),\n },\n media: { mimeType: finalMimeType, body: source.stream },\n supportsAllDrives: true,\n fields: 'id,name,mimeType,size,webViewLink,parents',\n });\n\n const res = response.data;\n const id = res.id ?? '';\n const resultName = res.name ?? finalName;\n const resultMimeType = res.mimeType ?? finalMimeType;\n const size = res.size ?? String(source.size ?? 0);\n const webViewLink = res.webViewLink ?? '';\n const parents = (res.parents as string[] | undefined) || [];\n\n // Fetch parent name if parentId was provided\n let parentName: string | undefined;\n let actualParentId: string | undefined;\n\n if (parents.length > 0) {\n actualParentId = parents[0];\n\n if (actualParentId === 'root') {\n parentName = 'My Drive';\n } else if (actualParentId) {\n try {\n const parentResponse = await drive.files.get({\n fileId: actualParentId,\n fields: 'name',\n });\n parentName = (parentResponse.data.name as string | undefined) || actualParentId;\n } catch (e) {\n logger.info('Failed to fetch parent name', {\n parentId: actualParentId,\n error: e,\n });\n parentName = actualParentId; // Fallback to ID\n }\n }\n }\n\n const locationSummary = parentName ? ` in \"${parentName}\"` : ' in My Drive';\n\n logger.info('drive.file.upload success', {\n id,\n name: resultName,\n size,\n parentId: actualParentId,\n });\n\n // Build result object with operation metadata\n const result: Output = {\n type: 'success' as const,\n operationSummary: `Uploaded \"${resultName}\"${locationSummary}`,\n itemsProcessed: 1,\n itemsChanged: 1,\n completedAt: new Date().toISOString(),\n id,\n name: resultName,\n mimeType: resultMimeType,\n size,\n webViewLink,\n ...(actualParentId && { parentId: actualParentId }),\n ...(parentName && { parentName }),\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('drive.file.upload error', { error: message });\n\n // Throw ProtocolError for proper MCP error handling\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error uploading file: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'file-upload' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","sourceUri","string","trim","min","describe","name","optional","mimeType","parentId","description","successBranchSchema","type","literal","operationSummary","itemsProcessed","number","itemsChanged","completedAt","id","size","webViewLink","parentName","outputSchema","discriminatedUnion","config","title","result","handler","extra","logger","res","source","drive","finalName","finalMimeType","response","resultName","resultMimeType","parents","actualParentId","parentResponse","e","locationSummary","error","message","info","driveApi","version","auth","googleAuth","authContext","getFileReadStream","fileName","contentType","guessMimeType","files","create","requestBody","media","body","stream","supportsAllDrives","fields","data","String","length","get","fileId","Date","toISOString","content","text","JSON","stringify","structuredContent","Error","ProtocolError","ProtocolErrorCode","InternalError","stack","undefined"],"mappings":";;;;+BAiKA;;;eAAwBA;;;2BAhKA;qBAIU;sBAEe;mBAC/B;+BAC+B;4BACtB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAP3B,IAAM,AAAEC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SAAiB;wBACrBf,MAAM;wBACNE,kBAAkB,AAAC,aAA0B6B,OAAdN,YAAW,KAAmB,OAAhBM;wBAC7C5B,gBAAgB;wBAChBE,cAAc;wBACdC,aAAa,IAAImD,OAAOC,WAAW;wBACnCnD,IAAAA;wBACAb,MAAM+B;wBACN7B,UAAU8B;wBACVlB,MAAAA;wBACAC,aAAAA;uBACImB,kBAAkB;wBAAE/B,UAAU+B;oBAAe,GAC7ClB,cAAc;wBAAEA,YAAAA;oBAAW;oBAGjC;;wBAAO;4BACLiD,OAAO;gCACL;oCACE3D,MAAM;oCACN4D,MAAMC,KAAKC,SAAS,CAAC/C;gCACvB;;4BAEFgD,mBAAmB;gCAAEhD,QAAAA;4BAAO;wBAC9B;;;oBACOiB;oBACDC,UAAUD,AAAK,YAALA,OAAiBgC,SAAQhC,MAAMC,OAAO,GAAGoB,OAAOrB;oBAChEd,OAAOc,KAAK,CAAC,2BAA2B;wBAAEA,OAAOC;oBAAQ;oBAEzD,oDAAoD;oBACpD,MAAM,IAAIgC,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,yBAAgC,OAARlC,UAAW;wBAC3FmC,OAAOpC,AAAK,YAALA,OAAiBgC,SAAQhC,MAAMoC,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAAStF;IACtB,OAAO;QACLW,MAAM;QACNmB,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
@@ -9,9 +9,10 @@ Object.defineProperty(exports, "default", {
|
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
11
|
var _oauthgoogle = require("@mcp-z/oauth-google");
|
|
12
|
+
var _drive = require("@googleapis/drive");
|
|
12
13
|
var _server = require("@mcp-z/server");
|
|
13
|
-
var _googleapis = require("googleapis");
|
|
14
14
|
var _zod = require("zod");
|
|
15
|
+
var _googleauthts = require("../../lib/google-auth.js");
|
|
15
16
|
var _querybuilderts = require("../../lib/query-builder.js");
|
|
16
17
|
var _indexts = require("../../schemas/index.js");
|
|
17
18
|
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
@@ -267,9 +268,9 @@ function handler(_0, _1) {
|
|
|
267
268
|
pageToken: pageToken ? '[provided]' : undefined,
|
|
268
269
|
fields: fields || 'all'
|
|
269
270
|
});
|
|
270
|
-
drive =
|
|
271
|
+
drive = (0, _drive.drive)({
|
|
271
272
|
version: 'v3',
|
|
272
|
-
auth: extra.authContext.auth
|
|
273
|
+
auth: (0, _googleauthts.googleAuth)(extra.authContext.auth)
|
|
273
274
|
});
|
|
274
275
|
if (parsedQuery && 'rawDriveQuery' in parsedQuery && parsedQuery.rawDriveQuery) {
|
|
275
276
|
// Object with rawDriveQuery field - use it directly
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-drive/src/mcp/tools/files-search.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { type CallToolResult, createFieldsSchema, createPaginationSchema, createShapeSchema, filterFields, ProtocolError, ProtocolErrorCode, parseFields, toColumnarFormat } from '@mcp-z/server';\nimport { type drive_v3, google } from 'googleapis';\nimport { z } from 'zod';\nimport { toDriveQuery } from '../../lib/query-builder.ts';\nimport { DRIVE_FILE_COMMON_PATTERNS, DRIVE_FILE_FIELD_DESCRIPTIONS, DRIVE_FILE_FIELDS, type DriveFile, DriveFileSchema, DriveQueryParameterSchema, parseDriveQueryParameter } from '../../schemas/index.ts';\n\nconst inputSchema = z.object({\n query: DriveQueryParameterSchema.describe('Structured Drive query object or JSON string. Use rawDriveQuery for raw Drive syntax.'),\n fields: createFieldsSchema({\n availableFields: DRIVE_FILE_FIELDS,\n fieldDescriptions: DRIVE_FILE_FIELD_DESCRIPTIONS,\n commonPatterns: DRIVE_FILE_COMMON_PATTERNS,\n resourceName: 'Drive file',\n }),\n ...createPaginationSchema({\n defaultPageSize: 50,\n maxPageSize: 1000,\n provider: 'drive',\n }).shape,\n shape: createShapeSchema(),\n});\n\n// Success branch schemas for different shapes\nconst successObjectsBranchSchema = z.object({\n type: z.literal('success'),\n shape: z.literal('objects'),\n items: z.array(DriveFileSchema).describe('Matching Drive files'),\n count: z.number().describe('Number of files in this page'),\n nextPageToken: z.string().optional().describe('Token for fetching next page of results'),\n});\n\nconst successArraysBranchSchema = z.object({\n type: z.literal('success'),\n shape: z.literal('arrays'),\n columns: z.array(z.string()).describe('Column names in canonical order'),\n rows: z.array(z.array(z.unknown())).describe('Row data matching column order'),\n count: z.number().describe('Number of files in this page'),\n nextPageToken: z.string().optional().describe('Token for fetching next page of results'),\n});\n\n// Output schema with auth_required support\n// Using z.union instead of discriminatedUnion since we have two success branches with different shapes\nconst outputSchema = z.union([successObjectsBranchSchema, successArraysBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n title: 'Search Drive Files',\n description: 'Search Google Drive files with flexible field selection for optimal performance.',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\n// Type for the raw Google Drive API response\ntype driveFile = drive_v3.Schema$File;\n\ntype driveResponse = drive_v3.Schema$FileList;\n\nasync function handler({ query, pageSize = 50, pageToken, fields, shape = 'arrays' }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n\n try {\n const parsedQuery = parseDriveQueryParameter(query);\n const requestedFields = parseFields(fields, DRIVE_FILE_FIELDS);\n\n // Validate and clamp pageSize to Google Drive API limits (1-1000)\n const validPageSize = Math.max(1, Math.min(1000, Math.floor(pageSize || 50)));\n\n logger.info('drive.files-search called', {\n query: parsedQuery,\n pageSize: validPageSize,\n pageToken: pageToken ? '[provided]' : undefined,\n fields: fields || 'all',\n });\n\n const drive = google.drive({ version: 'v3', auth: extra.authContext.auth });\n\n // Handle query parameter\n let qStr: string;\n if (parsedQuery && 'rawDriveQuery' in parsedQuery && parsedQuery.rawDriveQuery) {\n // Object with rawDriveQuery field - use it directly\n qStr = parsedQuery.rawDriveQuery;\n } else if (parsedQuery) {\n // Structured query object - convert to Drive query string\n const { q } = toDriveQuery(parsedQuery);\n qStr = q || '';\n } else {\n qStr = '';\n }\n\n const listOptions: {\n q?: string;\n pageSize: number;\n fields: string;\n orderBy: string;\n pageToken?: string;\n } = {\n pageSize: validPageSize,\n fields: 'files(id,name,mimeType,webViewLink,modifiedTime,parents,shared,starred,owners),nextPageToken',\n orderBy: 'modifiedTime desc',\n };\n if (qStr.trim().length > 0) {\n listOptions.q = qStr;\n }\n if (pageToken && pageToken.trim().length > 0) {\n listOptions.pageToken = pageToken;\n }\n\n const response = await drive.files.list(listOptions);\n const res = response.data as driveResponse;\n const files = Array.isArray(res?.files) ? res.files : [];\n\n const parentIds = new Set<string>();\n for (const f of files) {\n if (f?.parents && f.parents.length > 0) {\n for (const parentId of f.parents) {\n if (parentId && parentId !== 'root') {\n parentIds.add(parentId);\n }\n }\n }\n }\n\n const parentNameMap = new Map<string, string>();\n if (parentIds.size > 0) {\n logger.info('Fetching parent names', { count: parentIds.size });\n const parentFetches = Array.from(parentIds).map(async (parentId) => {\n try {\n const parentRes = await drive.files.get({\n fileId: parentId,\n fields: 'id,name',\n });\n const parentName = (parentRes.data.name as string | undefined) || parentId;\n parentNameMap.set(parentId, parentName);\n } catch (e) {\n logger.info('Failed to fetch parent name', { parentId, error: e });\n parentNameMap.set(parentId, parentId); // Fallback to ID\n }\n });\n await Promise.all(parentFetches);\n }\n\n const items: DriveFile[] = files.map((f: driveFile) => {\n const id = f?.id ? String(f.id) : 'unknown';\n const name = f?.name || id;\n const result: DriveFile = { id, name };\n\n // Only include properties that have actual values\n if (f?.mimeType) result.mimeType = f.mimeType;\n if (f?.webViewLink) result.webViewLink = f.webViewLink;\n if (f?.modifiedTime) result.modifiedTime = f.modifiedTime;\n\n if (f?.parents && f.parents.length > 0) {\n result.parents = f.parents.map((parentId) => {\n if (parentId === 'root') {\n return { id: 'root', name: 'My Drive' };\n }\n const parentName = parentNameMap.get(parentId) || parentId;\n return { id: parentId, name: parentName };\n });\n }\n\n if (f?.shared != null) result.shared = f.shared;\n if (f?.starred != null) result.starred = f.starred;\n\n if (f?.owners && f.owners.length > 0) {\n result.owners = f.owners.map((o) => {\n const owner: NonNullable<DriveFile['owners']>[number] = {};\n if (o?.displayName) owner.displayName = o.displayName;\n if (o?.emailAddress) owner.emailAddress = o.emailAddress;\n if (o?.kind) owner.kind = o.kind;\n if (o?.me != null) owner.me = o.me;\n if (o?.permissionId) owner.permissionId = o.permissionId;\n if (o?.photoLink) owner.photoLink = o.photoLink;\n return owner;\n });\n }\n\n return result;\n });\n\n const filteredItems = items.map((item) => filterFields(item, requestedFields));\n\n logger.info('drive.files-search returning', {\n query: parsedQuery,\n pageSize,\n resultCount: filteredItems.length,\n fields: fields || 'all',\n });\n\n const nextPageToken = res.nextPageToken && res.nextPageToken.trim().length > 0 ? res.nextPageToken : undefined;\n\n // Build result based on shape\n const result: Output =\n shape === 'arrays'\n ? {\n type: 'success' as const,\n shape: 'arrays' as const,\n ...toColumnarFormat(filteredItems, requestedFields, DRIVE_FILE_FIELDS),\n count: filteredItems.length,\n ...(nextPageToken && { nextPageToken }),\n }\n : {\n type: 'success' as const,\n shape: 'objects' as const,\n items: filteredItems,\n count: filteredItems.length,\n ...(nextPageToken && { nextPageToken }),\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('drive.files-search error', { error: message });\n\n // Throw ProtocolError for all errors so callers can see Drive validation details\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error searching files: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'files-search' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","query","DriveQueryParameterSchema","describe","fields","createFieldsSchema","availableFields","DRIVE_FILE_FIELDS","fieldDescriptions","DRIVE_FILE_FIELD_DESCRIPTIONS","commonPatterns","DRIVE_FILE_COMMON_PATTERNS","resourceName","createPaginationSchema","defaultPageSize","maxPageSize","provider","shape","createShapeSchema","successObjectsBranchSchema","type","literal","items","array","DriveFileSchema","count","number","nextPageToken","string","optional","successArraysBranchSchema","columns","rows","unknown","outputSchema","union","config","title","description","result","handler","extra","pageSize","pageToken","logger","parsedQuery","requestedFields","validPageSize","drive","qStr","q","listOptions","response","res","files","parentIds","f","parentId","parentNameMap","parentFetches","filteredItems","error","message","parseDriveQueryParameter","parseFields","Math","max","min","floor","info","undefined","google","version","auth","authContext","rawDriveQuery","toDriveQuery","orderBy","trim","length","list","data","Array","isArray","Set","parents","add","Map","size","from","map","parentRes","parentName","e","get","fileId","name","set","Promise","all","id","String","mimeType","webViewLink","modifiedTime","shared","starred","owners","o","owner","displayName","emailAddress","kind","me","permissionId","photoLink","item","filterFields","resultCount","toColumnarFormat","content","text","JSON","stringify","structuredContent","Error","ProtocolError","ProtocolErrorCode","InternalError","stack"],"mappings":";;;;+BA8OA;;;eAAwBA;;;2BA7OA;sBAI0J;0BAC5I;mBACpB;8BACW;uBACsJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AANnL,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAQR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,OAAOC,kCAAyB,CAACC,QAAQ,CAAC;IAC1CC,QAAQC,IAAAA,0BAAkB,EAAC;QACzBC,iBAAiBC,0BAAiB;QA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type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { type drive_v3, drive as driveApi } from '@googleapis/drive';\nimport { type CallToolResult, createFieldsSchema, createPaginationSchema, createShapeSchema, filterFields, ProtocolError, ProtocolErrorCode, parseFields, toColumnarFormat } from '@mcp-z/server';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { toDriveQuery } from '../../lib/query-builder.ts';\nimport { DRIVE_FILE_COMMON_PATTERNS, DRIVE_FILE_FIELD_DESCRIPTIONS, DRIVE_FILE_FIELDS, type DriveFile, DriveFileSchema, DriveQueryParameterSchema, parseDriveQueryParameter } from '../../schemas/index.ts';\n\nconst inputSchema = z.object({\n query: DriveQueryParameterSchema.describe('Structured Drive query object or JSON string. Use rawDriveQuery for raw Drive syntax.'),\n fields: createFieldsSchema({\n availableFields: DRIVE_FILE_FIELDS,\n fieldDescriptions: DRIVE_FILE_FIELD_DESCRIPTIONS,\n commonPatterns: DRIVE_FILE_COMMON_PATTERNS,\n resourceName: 'Drive file',\n }),\n ...createPaginationSchema({\n defaultPageSize: 50,\n maxPageSize: 1000,\n provider: 'drive',\n }).shape,\n shape: createShapeSchema(),\n});\n\n// Success branch schemas for different shapes\nconst successObjectsBranchSchema = z.object({\n type: z.literal('success'),\n shape: z.literal('objects'),\n items: z.array(DriveFileSchema).describe('Matching Drive files'),\n count: z.number().describe('Number of files in this page'),\n nextPageToken: z.string().optional().describe('Token for fetching next page of results'),\n});\n\nconst successArraysBranchSchema = z.object({\n type: z.literal('success'),\n shape: z.literal('arrays'),\n columns: z.array(z.string()).describe('Column names in canonical order'),\n rows: z.array(z.array(z.unknown())).describe('Row data matching column order'),\n count: z.number().describe('Number of files in this page'),\n nextPageToken: z.string().optional().describe('Token for fetching next page of results'),\n});\n\n// Output schema with auth_required support\n// Using z.union instead of discriminatedUnion since we have two success branches with different shapes\nconst outputSchema = z.union([successObjectsBranchSchema, successArraysBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n title: 'Search Drive Files',\n description: 'Search Google Drive files with flexible field selection for optimal performance.',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\n// Type for the raw Google Drive API response\ntype driveFile = drive_v3.Schema$File;\n\ntype driveResponse = drive_v3.Schema$FileList;\n\nasync function handler({ query, pageSize = 50, pageToken, fields, shape = 'arrays' }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n\n try {\n const parsedQuery = parseDriveQueryParameter(query);\n const requestedFields = parseFields(fields, DRIVE_FILE_FIELDS);\n\n // Validate and clamp pageSize to Google Drive API limits (1-1000)\n const validPageSize = Math.max(1, Math.min(1000, Math.floor(pageSize || 50)));\n\n logger.info('drive.files-search called', {\n query: parsedQuery,\n pageSize: validPageSize,\n pageToken: pageToken ? '[provided]' : undefined,\n fields: fields || 'all',\n });\n\n const drive = driveApi({ version: 'v3', auth: googleAuth(extra.authContext.auth) });\n\n // Handle query parameter\n let qStr: string;\n if (parsedQuery && 'rawDriveQuery' in parsedQuery && parsedQuery.rawDriveQuery) {\n // Object with rawDriveQuery field - use it directly\n qStr = parsedQuery.rawDriveQuery;\n } else if (parsedQuery) {\n // Structured query object - convert to Drive query string\n const { q } = toDriveQuery(parsedQuery);\n qStr = q || '';\n } else {\n qStr = '';\n }\n\n const listOptions: {\n q?: string;\n pageSize: number;\n fields: string;\n orderBy: string;\n pageToken?: string;\n } = {\n pageSize: validPageSize,\n fields: 'files(id,name,mimeType,webViewLink,modifiedTime,parents,shared,starred,owners),nextPageToken',\n orderBy: 'modifiedTime desc',\n };\n if (qStr.trim().length > 0) {\n listOptions.q = qStr;\n }\n if (pageToken && pageToken.trim().length > 0) {\n listOptions.pageToken = pageToken;\n }\n\n const response = await drive.files.list(listOptions);\n const res = response.data as driveResponse;\n const files = Array.isArray(res?.files) ? res.files : [];\n\n const parentIds = new Set<string>();\n for (const f of files) {\n if (f?.parents && f.parents.length > 0) {\n for (const parentId of f.parents) {\n if (parentId && parentId !== 'root') {\n parentIds.add(parentId);\n }\n }\n }\n }\n\n const parentNameMap = new Map<string, string>();\n if (parentIds.size > 0) {\n logger.info('Fetching parent names', { count: parentIds.size });\n const parentFetches = Array.from(parentIds).map(async (parentId) => {\n try {\n const parentRes = await drive.files.get({\n fileId: parentId,\n fields: 'id,name',\n });\n const parentName = (parentRes.data.name as string | undefined) || parentId;\n parentNameMap.set(parentId, parentName);\n } catch (e) {\n logger.info('Failed to fetch parent name', { parentId, error: e });\n parentNameMap.set(parentId, parentId); // Fallback to ID\n }\n });\n await Promise.all(parentFetches);\n }\n\n const items: DriveFile[] = files.map((f: driveFile) => {\n const id = f?.id ? String(f.id) : 'unknown';\n const name = f?.name || id;\n const result: DriveFile = { id, name };\n\n // Only include properties that have actual values\n if (f?.mimeType) result.mimeType = f.mimeType;\n if (f?.webViewLink) result.webViewLink = f.webViewLink;\n if (f?.modifiedTime) result.modifiedTime = f.modifiedTime;\n\n if (f?.parents && f.parents.length > 0) {\n result.parents = f.parents.map((parentId) => {\n if (parentId === 'root') {\n return { id: 'root', name: 'My Drive' };\n }\n const parentName = parentNameMap.get(parentId) || parentId;\n return { id: parentId, name: parentName };\n });\n }\n\n if (f?.shared != null) result.shared = f.shared;\n if (f?.starred != null) result.starred = f.starred;\n\n if (f?.owners && f.owners.length > 0) {\n result.owners = f.owners.map((o) => {\n const owner: NonNullable<DriveFile['owners']>[number] = {};\n if (o?.displayName) owner.displayName = o.displayName;\n if (o?.emailAddress) owner.emailAddress = o.emailAddress;\n if (o?.kind) owner.kind = o.kind;\n if (o?.me != null) owner.me = o.me;\n if (o?.permissionId) owner.permissionId = o.permissionId;\n if (o?.photoLink) owner.photoLink = o.photoLink;\n return owner;\n });\n }\n\n return result;\n });\n\n const filteredItems = items.map((item) => filterFields(item, requestedFields));\n\n logger.info('drive.files-search returning', {\n query: parsedQuery,\n pageSize,\n resultCount: filteredItems.length,\n fields: fields || 'all',\n });\n\n const nextPageToken = res.nextPageToken && res.nextPageToken.trim().length > 0 ? res.nextPageToken : undefined;\n\n // Build result based on shape\n const result: Output =\n shape === 'arrays'\n ? {\n type: 'success' as const,\n shape: 'arrays' as const,\n ...toColumnarFormat(filteredItems, requestedFields, DRIVE_FILE_FIELDS),\n count: filteredItems.length,\n ...(nextPageToken && { nextPageToken }),\n }\n : {\n type: 'success' as const,\n shape: 'objects' as const,\n items: filteredItems,\n count: filteredItems.length,\n ...(nextPageToken && { nextPageToken }),\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('drive.files-search error', { error: message });\n\n // Throw ProtocolError for all errors so callers can see Drive validation details\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error searching files: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'files-search' as const,\n config,\n handler,\n };\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","query","DriveQueryParameterSchema","describe","fields","createFieldsSchema","availableFields","DRIVE_FILE_FIELDS","fieldDescriptions","DRIVE_FILE_FIELD_DESCRIPTIONS","commonPatterns","DRIVE_FILE_COMMON_PATTERNS","resourceName","createPaginationSchema","defaultPageSize","maxPageSize","provider","shape","createShapeSchema","successObjectsBranchSchema","type","literal","items","array","DriveFileSchema","count","number","nextPageToken","string","optional","successArraysBranchSchema","columns","rows","unknown","outputSchema","union","config","title","description","result","handler","extra","pageSize","pageToken","logger","parsedQuery","requestedFields","validPageSize","drive","qStr","q","listOptions","response","res","files","parentIds","f","parentId","parentNameMap","parentFetches","filteredItems","error","message","parseDriveQueryParameter","parseFields","Math","max","min","floor","info","undefined","driveApi","version","auth","googleAuth","authContext","rawDriveQuery","toDriveQuery","orderBy","trim","length","list","data","Array","isArray","Set","parents","add","Map","size","from","map","parentRes","parentName","e","get","fileId","name","set","Promise","all","id","String","mimeType","webViewLink","modifiedTime","shared","starred","owners","o","owner","displayName","emailAddress","kind","me","permissionId","photoLink","item","filterFields","resultCount","toColumnarFormat","content","text","JSON","stringify","structuredContent","Error","ProtocolError","ProtocolErrorCode","InternalError","stack"],"mappings":";;;;+BA+OA;;;eAAwBA;;;2BA9OA;qBAIyB;sBACiI;mBAChK;4BACS;8BACE;uBACsJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAPnL,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AASR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,OAAOC,kCAAyB,CAACC,QAAQ,CAAC;IAC1CC,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,6BAA6BpB,MAAC,CAACC,MAAM,CAAC;IAC1CoB,MAAMrB,MAAC,CAACsB,OAAO,CAAC;IAChBJ,OAAOlB,MAAC,CAACsB,OAAO,CAAC;IACjBC,OAAOvB,MAAC,CAACwB,KAAK,CAACC,wBAAe,EAAErB,QAAQ,CAAC;IACzCsB,OAAO1B,MAAC,CAAC2B,MAAM,GAAGvB,QAAQ,CAAC;IAC3BwB,eAAe5B,MAAC,CAA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AOsC;wBACPnC,OAAOmC,cAAcoB,MAAM;uBACvBrD,iBAAiB;wBAAEA,eAAAA;oBAAc;oBAG7C;;wBAAO;4BACL8F,OAAO;gCACL;oCACErG,MAAM;oCACNsG,MAAMC,KAAKC,SAAS,CAACrF;gCACvB;;4BAEFsF,mBAAmB;gCAAEtF,QAAAA;4BAAO;wBAC9B;;;oBACOsB;oBACDC,UAAUD,AAAK,YAALA,OAAiBiE,SAAQjE,MAAMC,OAAO,GAAGwC,OAAOzC;oBAChEjB,OAAOiB,KAAK,CAAC,4BAA4B;wBAAEA,OAAOC;oBAAQ;oBAE1D,iFAAiF;oBACjF,MAAM,IAAIiE,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,0BAAiC,OAARnE,UAAW;wBAC5FoE,OAAOrE,AAAK,YAALA,OAAiBiE,SAAQjE,MAAMqE,KAAK,GAAG5D;oBAChD;;;;;;;IAEJ;;AAEe,SAAS3E;IACtB,OAAO;QACLsG,MAAM;QACN7D,QAAAA;QACAI,SAAAA;IACF;AACF"}
|
|
@@ -9,9 +9,10 @@ Object.defineProperty(exports, "default", {
|
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
11
|
var _oauthgoogle = require("@mcp-z/oauth-google");
|
|
12
|
+
var _drive = require("@googleapis/drive");
|
|
12
13
|
var _server = require("@mcp-z/server");
|
|
13
|
-
var _googleapis = require("googleapis");
|
|
14
14
|
var _zod = require("zod");
|
|
15
|
+
var _googleauthts = require("../../lib/google-auth.js");
|
|
15
16
|
var _indexts = require("../../schemas/index.js");
|
|
16
17
|
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
17
18
|
try {
|
|
@@ -265,9 +266,9 @@ function handler(_0, _1) {
|
|
|
265
266
|
,
|
|
266
267
|
6
|
|
267
268
|
]);
|
|
268
|
-
drive =
|
|
269
|
+
drive = (0, _drive.drive)({
|
|
269
270
|
version: 'v3',
|
|
270
|
-
auth: extra.authContext.auth
|
|
271
|
+
auth: (0, _googleauthts.googleAuth)(extra.authContext.auth)
|
|
271
272
|
});
|
|
272
273
|
qStr = "'".concat(folderId, "' in parents and trashed = false");
|
|
273
274
|
listOptions = {
|