File size: 2,492 Bytes
7dc28be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import type { FastMCP } from 'fastmcp';
import { UserError } from 'fastmcp';
import { z } from 'zod';
import { getDriveClient } from '../../clients.js';

export function register(server: FastMCP) {
  server.addTool({
    name: 'moveFile',
    description:
      'Moves a file or folder to a different Drive folder. By default adds the new parent while keeping existing parents; set removeFromAllParents=true for a true move.',
    parameters: z.strictObject({
      fileId: z
        .string()
        .describe('The file or folder ID from a Google Drive URL or a previous tool result.'),
      newParentId: z.string().describe('ID of the destination folder. Use "root" for Drive root.'),
      removeFromAllParents: z
        .boolean()
        .optional()
        .default(false)
        .describe(
          'If true, removes from all current parents. If false, adds to new parent while keeping existing parents.'
        ),
    }),
    execute: async (args, { log }) => {
      const drive = await getDriveClient();
      log.info(`Moving file ${args.fileId} to folder ${args.newParentId}`);

      try {
        // First get the current parents
        const fileInfo = await drive.files.get({
          fileId: args.fileId,
          fields: 'name,parents',
          supportsAllDrives: true,
        });

        const fileName = fileInfo.data.name;
        const currentParents = fileInfo.data.parents || [];

        let updateParams: any = {
          fileId: args.fileId,
          addParents: args.newParentId,
          fields: 'id,name,parents',
          supportsAllDrives: true,
        };

        if (args.removeFromAllParents && currentParents.length > 0) {
          updateParams.removeParents = currentParents.join(',');
        }

        const response = await drive.files.update(updateParams);

        const action = args.removeFromAllParents ? 'moved' : 'copied';
        return `Successfully ${action} "${fileName}" to new location.\nFile ID: ${response.data.id}`;
      } catch (error: any) {
        log.error(`Error moving file: ${error.message || error}`);
        if (error.code === 404)
          throw new UserError('File or destination folder not found. Check the IDs.');
        if (error.code === 403)
          throw new UserError(
            'Permission denied. Make sure you have write access to both source and destination.'
          );
        throw new UserError(`Failed to move file: ${error.message || 'Unknown error'}`);
      }
    },
  });
}