gemini-upload-file
Upload files up to 2GB to the Gemini File API for AI operations, manage file listings, retrievals, or deletions. Files persist for 48 hours, enabling efficient handling in Claude Desktop workflows.
Instructions
Upload files to Gemini File API (up to 2GB) for use in subsequent operations. Files persist for 48 hours.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| display_name | No | Optional display name for the file (defaults to filename) | |
| file_name | No | File name (for get/delete operations) | |
| file_path | No | Path to the file to upload | |
| operation | Yes | Operation to perform: "upload", "list", "get", or "delete" | |
| page_size | No | Number of files to list (for list operation, max 100) |
Implementation Reference
- src/tools/index.js:87-87 (registration)Registers the FileUploadTool class instance, which provides the 'gemini-upload-file' tool, into the central tool registry.registerTool(new FileUploadTool(intelligenceSystem, geminiService));
- src/tools/file-upload.js:19-50 (schema)Tool name, description, and input schema definition passed to BaseTool super constructor.'gemini-upload-file', 'Upload files to Gemini File API (up to 2GB) for use in subsequent operations. Files persist for 48 hours.', { type: 'object', properties: { file_path: { type: 'string', description: 'Path to the file to upload', }, display_name: { type: 'string', description: 'Optional display name for the file (defaults to filename)', }, operation: { type: 'string', description: 'Operation to perform: "upload", "list", "get", or "delete"', enum: ['upload', 'list', 'get', 'delete'], }, file_name: { type: 'string', description: 'File name (for get/delete operations)', }, page_size: { type: 'number', description: 'Number of files to list (for list operation, max 100)', }, }, required: ['operation'], }, intelligenceSystem, geminiService, );
- src/tools/file-upload.js:60-80 (handler)Primary handler method that validates operation and dispatches to specific handlers (upload, list, get, delete).async execute(args) { const operation = validateString(args.operation, 'operation', ['upload', 'list', 'get', 'delete']); try { switch (operation) { case 'upload': return await this.handleUpload(args); case 'list': return await this.handleList(args); case 'get': return await this.handleGet(args); case 'delete': return await this.handleDelete(args); default: throw new Error(`Unknown operation: ${operation}`); } } catch (error) { log(`Error in file upload tool: ${error.message}`, this.name); throw error; } }
- src/tools/file-upload.js:82-181 (handler)Core upload operation handler: validates file, checks size (<2GB), uploads via FileUploadService, builds formatted response with URI.async handleUpload(args) { const filePath = validateNonEmptyString(args.file_path, 'file_path'); const displayName = args.display_name || null; // Check if file exists if (!fs.existsSync(filePath)) { throw new Error(`File not found: ${filePath}`); } // Check file size const stats = fs.statSync(filePath); const fileSizeMB = stats.size / (1024 * 1024); if (fileSizeMB > 2048) { // 2GB limit throw new Error(`File too large: ${fileSizeMB.toFixed(2)}MB. Maximum size is 2GB.`); } log(`Uploading file: ${filePath} (${fileSizeMB.toFixed(2)}MB)`, this.name); try { const fileInfo = await this.fileUploadService.uploadFile(filePath, displayName); // Build response with available fields let response = `✓ File uploaded successfully to Gemini File API:\n\n`; if (fileInfo.display_name) { response += `**Name:** ${fileInfo.display_name}\n`; } if (fileInfo.uri) { response += `**URI:** ${fileInfo.uri}\n`; } if (fileInfo.name) { response += `**File ID:** ${fileInfo.name}\n`; } if (fileInfo.size_bytes && fileInfo.size_bytes > 0) { response += `**Size:** ${(fileInfo.size_bytes / (1024 * 1024)).toFixed(2)}MB\n`; } else { response += `**Size:** ${fileSizeMB.toFixed(2)}MB (estimated)\n`; } if (fileInfo.mime_type) { response += `**MIME Type:** ${fileInfo.mime_type}\n`; } if (fileInfo.create_time) { try { response += `**Created:** ${new Date(fileInfo.create_time).toLocaleString()}\n`; } catch (e) { response += `**Created:** ${fileInfo.create_time}\n`; } } if (fileInfo.expiration_time) { try { response += `**Expires:** ${new Date(fileInfo.expiration_time).toLocaleString()}\n`; } catch (e) { response += `**Expires:** ${fileInfo.expiration_time}\n`; } } response += `\n`; if (fileInfo.uri) { response += `This file can now be used in other Gemini operations by referencing its URI.\n`; response += `The file will be automatically deleted after 48 hours.`; } else { response += `File uploaded but URI not returned. Check logs for details.`; log(`Warning: File uploaded but no URI returned. Response: ${JSON.stringify(fileInfo)}`, this.name); } // Learn from the interaction if intelligence is enabled if (this.intelligenceSystem.initialized) { try { await this.intelligenceSystem.learnFromInteraction( `Upload file ${filePath}`, `Upload file ${filePath} with display name ${displayName || path.basename(filePath)}`, `Successfully uploaded ${fileSizeMB.toFixed(2)}MB file`, 'file-upload', this.name ); } catch (err) { log(`Tool Intelligence learning failed: ${err.message}`, this.name); } } return { content: [ { type: 'text', text: response, }, ], }; } catch (error) { throw new Error(`Failed to upload file: ${error.message}`); } }
- Supporting service class that handles the actual HTTP requests to Gemini File API for upload, list, get, delete operations./** * Gemini File API Upload Service * Implements resumable upload protocol for files up to 2GB * * @author Rob (with Claude) */ const https = require('https'); const fs = require('fs'); const path = require('path'); const { URL } = require('url'); const { log } = require('../../utils/logger'); class FileUploadService { constructor(apiKey) { this.apiKey = apiKey; this.baseUrl = 'https://generativelanguage.googleapis.com'; } /** * Uploads a file to Gemini using resumable upload protocol * @param {string} filePath - Path to the file to upload * @param {string} displayName - Display name for the file * @param {Object} options - Additional options * @returns {Promise<Object>} File metadata including URI */ async uploadFile(filePath, displayName = null, options = {}) { const stats = fs.statSync(filePath); const fileSize = stats.size; const mimeType = this.getMimeType(filePath); if (!displayName) { displayName = path.basename(filePath); } log(`Starting resumable upload for file: ${filePath} (${(fileSize / (1024 * 1024)).toFixed(2)}MB)`, 'file-upload'); // Step 1: Initialize resumable upload const uploadUrl = await this.initializeResumableUpload(displayName, mimeType, fileSize); // Step 2: Upload the file data const fileInfo = await this.uploadFileData(uploadUrl, filePath, fileSize); log(`File uploaded successfully: ${fileInfo.name}, URI: ${fileInfo.uri}`, 'file-upload'); return fileInfo; } /** * Initialize resumable upload and get upload URL */ async initializeResumableUpload(displayName, mimeType, fileSize) { return new Promise((resolve, reject) => {