copy_file
Copy files or directories between locations with options to overwrite existing files and copy recursively.
Instructions
Copy a file or directory
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| source | Yes | Source path | |
| destination | Yes | Destination path | |
| overwrite | No | Overwrite if exists | |
| recursive | No | Copy directories recursively |
Implementation Reference
- src/tools/write.ts:192-308 (handler)The implementation of the `copy_file` logic, including path validation, directory/file handling, and error reporting.
async function copyFileImpl(input: CopyFileInput): Promise<ToolResult> { try { const srcPath = path.resolve(input.source); const destPath = path.resolve(input.destination); // Check if source exists const srcStats = await fs.stat(srcPath); // Check if destination exists let destExists = false; try { await fs.access(destPath); destExists = true; } catch { // Destination doesn't exist } if (destExists && !input.overwrite) { return { isError: true, content: [ { type: 'text', text: JSON.stringify({ code: 'ALREADY_EXISTS', message: `Destination already exists and overwrite is false: ${input.destination}`, }), }, ], }; } if (srcStats.isDirectory()) { if (!input.recursive) { return { isError: true, content: [ { type: 'text', text: JSON.stringify({ code: 'INVALID_PATH', message: 'Source is a directory but recursive is false', }), }, ], }; } // Copy directory recursively await copyDirRecursive(srcPath, destPath); } else { // Ensure parent directory exists await fs.mkdir(path.dirname(destPath), { recursive: true }); // Copy file await fs.copyFile(srcPath, destPath); } return { content: [ { type: 'text', text: JSON.stringify({ success: true, source: srcPath, destination: destPath, }), }, ], }; } catch (error) { const err = error as NodeJS.ErrnoException; if (err.code === 'ENOENT') { return { isError: true, content: [ { type: 'text', text: JSON.stringify({ code: 'FILE_NOT_FOUND', message: `Source not found: ${input.source}`, }), }, ], }; } if (err.code === 'EACCES') { return { isError: true, content: [ { type: 'text', text: JSON.stringify({ code: 'PERMISSION_DENIED', message: `Permission denied`, }), }, ], }; } return { isError: true, content: [ { type: 'text', text: JSON.stringify({ code: 'UNKNOWN_ERROR', message: `Error copying: ${err.message}`, }), }, ], }; } } - src/tools/write.ts:576-590 (registration)Registration of the 'copy_file' tool with the MCP server.
// copy_file tool server.tool( 'copy_file', 'Copy a file or directory', { source: z.string().describe('Source path'), destination: z.string().describe('Destination path'), overwrite: z.boolean().optional().describe('Overwrite if exists'), recursive: z.boolean().optional().describe('Copy directories recursively'), }, async (args) => { const input = CopyFileInputSchema.parse(args); return await copyFileImpl(input); } );