Skip to main content
Glama
Garblesnarff

Gemini MCP Server for Claude Desktop

gemini-upload-file

Upload files to Google's Gemini AI for processing, enabling Claude Desktop to analyze and generate content from documents, images, and media files up to 2GB.

Instructions

Upload files to Gemini File API (up to 2GB) for use in subsequent operations. Files persist for 48 hours.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathNoPath to the file to upload
display_nameNoOptional display name for the file (defaults to filename)
operationYesOperation to perform: "upload", "list", "get", or "delete"
file_nameNoFile name (for get/delete operations)
page_sizeNoNumber of files to list (for list operation, max 100)

Implementation Reference

  • Main handler function that validates the operation and dispatches to specific file management methods (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;
      }
    }
  • Core upload handler: validates file path and size, performs upload using FileUploadService, builds detailed success response with file metadata.
    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}`);
      }
    }
  • JSON schema defining the input parameters for the gemini-upload-file tool, including operations and file details.
    {
      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'],
  • Registers the FileUploadTool instance (named 'gemini-upload-file') with the tool dispatcher/registry.
    registerTool(new FileUploadTool(intelligenceSystem, geminiService));
  • Helper service method that implements the resumable file upload protocol to Gemini File API, called by the tool handler.
    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;
    }
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden. It discloses key behavioral traits: file size limit (2GB) and persistence (48 hours), which are valuable beyond the schema. However, it lacks details on error handling, rate limits, authentication requirements, or what 'subsequent operations' entail, leaving gaps for a mutation tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two concise sentences with zero waste: the first states the core function and constraints, the second adds persistence info. It's front-loaded with the main purpose, and every sentence adds essential context without redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no annotations and no output schema, the description is moderately complete for a 5-parameter mutation tool. It covers purpose and key constraints but lacks details on permissions, error cases, return values, or how parameters interact. For a tool that handles file operations with multiple 'operation' types, more context on behavioral outcomes would improve completeness.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema fully documents all 5 parameters. The description adds no specific parameter semantics beyond implying that uploaded files are used in later steps. It doesn't clarify parameter interactions (e.g., how 'operation' affects other params) or provide examples, so it meets the baseline for high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool uploads files to the Gemini File API with a size limit (up to 2GB) and mentions persistence duration (48 hours). It distinguishes from siblings by focusing on file upload rather than analysis, chat, or image generation. However, it doesn't explicitly differentiate from potential file management siblings beyond the upload focus.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage for preparing files for subsequent operations, providing some context. However, it doesn't specify when to use this tool versus alternatives (e.g., direct API calls or other upload methods), nor does it mention prerequisites like authentication or file format restrictions. The guidance is limited to the tool's role in a workflow.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Garblesnarff/gemini-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server