Skip to main content
Glama
zhongweili
by zhongweili

Upload file to Gemini Files API

upload_file

Upload local files to the Gemini Files API to handle large images (over 20MB) or reuse files across multiple prompts, returning the file URI and metadata for integration.

Instructions

Upload a local file through the Gemini Files API and return its URI & metadata. Useful when the image is larger than 20MB or reused across prompts.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesServer-accessible file path to upload to Gemini Files API.
display_nameNoOptional display name for the uploaded file.

Implementation Reference

  • Core handler function for the 'upload_file' tool. Handles input parameters, performs file upload using file_service, manages errors, and returns a ToolResult with file metadata or error details.
    def upload_file(
        path: Annotated[
            str,
            Field(
                description="Server-accessible file path to upload to Gemini Files API.",
                min_length=1,
                max_length=512,
            ),
        ],
        display_name: Annotated[
            Optional[str],
            Field(description="Optional display name for the uploaded file.", max_length=256),
        ] = None,
        ctx: Context = None,
    ) -> ToolResult:
        """
        Upload a local file through the Gemini Files API and return its URI & metadata.
        Useful when the image is larger than 20MB or reused across prompts.
        """
        logger = logging.getLogger(__name__)
    
        try:
            logger.info(f"Upload file request: path='{path}', display_name='{display_name}'")
    
            # Get service (would be injected in real implementation)
            file_service = _get_file_service()
    
            # Upload file
            metadata = file_service.upload_file(path, display_name)
    
            # Create response
            summary = f"Successfully uploaded file: {metadata['name']}"
    
            # Return as structured content (not image blocks)
            logger.info(f"Successfully uploaded file: {metadata['name']}")
    
            return ToolResult(
                content=[summary], structured_content={"success": True, "file": metadata}
            )
    
        except ValidationError as e:
            logger.error(f"Validation error in upload_file: {e}")
            return ToolResult(
                content=[f"Validation error: {e}"],
                structured_content={"error": "validation_error", "message": str(e)},
            )
        except FileOperationError as e:
            logger.error(f"File operation error in upload_file: {e}")
            return ToolResult(
                content=[f"File upload failed: {e}"],
                structured_content={"error": "file_operation_error", "message": str(e)},
            )
        except Exception as e:
            logger.error(f"Unexpected error in upload_file: {e}")
            raise
  • Input schema for the upload_file tool defined using Annotated and Pydantic Field for path (required str, 1-512 chars) and optional display_name (str, max 256 chars).
    def upload_file(
        path: Annotated[
            str,
            Field(
                description="Server-accessible file path to upload to Gemini Files API.",
                min_length=1,
                max_length=512,
            ),
        ],
        display_name: Annotated[
            Optional[str],
            Field(description="Optional display name for the uploaded file.", max_length=256),
        ] = None,
        ctx: Context = None,
    ) -> ToolResult:
  • Registration function that decorates the upload_file handler with @server.tool, providing tool metadata like title.
    def register_upload_file_tool(server: FastMCP):
        """Register the upload_file tool with the FastMCP server."""
    
        @server.tool(
            annotations={
                "title": "Upload file to Gemini Files API",
                "readOnlyHint": False,
                "openWorldHint": True,
            }
        )
  • Top-level registration: imports register_upload_file_tool and calls it in _register_tools method to add the tool to the MCP server.
    from ..tools.upload_file import register_upload_file_tool
    from ..tools.output_stats import register_output_stats_tool
    from ..tools.maintenance import register_maintenance_tool
    
    register_generate_image_tool(self.server)
    register_upload_file_tool(self.server)
  • Helper function to retrieve the file_service instance used for uploading files.
    def _get_file_service():
        """Get the file service instance."""
        from ..services import get_file_service
        return get_file_service()
Behavior4/5

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

The description adds valuable behavioral context beyond annotations: it explains the tool uploads to an external API (Gemini Files API) and returns specific outputs (URI & metadata). Annotations provide readOnlyHint=false (mutation) and openWorldHint=true (external system), but the description clarifies the upload destination and return format, which is helpful for agent understanding.

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 extremely concise with only two sentences, both of which add clear value. The first sentence states the core purpose and output, while the second provides usage guidelines. There's no wasted text or redundancy.

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

Completeness4/5

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

For a mutation tool with no output schema, the description does well by specifying the return values (URI & metadata) and usage context. However, it could be more complete by mentioning authentication requirements or error handling, given the openWorldHint=true annotation indicating external system interaction.

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?

With 100% schema description coverage, the input schema already fully documents both parameters. The description doesn't add any parameter-specific information beyond what's in the schema, so it meets the baseline of 3 without compensating for gaps.

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

Purpose5/5

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

The description clearly states the specific action ('Upload a local file'), target resource ('through the Gemini Files API'), and output ('return its URI & metadata'). It distinguishes itself from sibling tools like 'generate_image' by focusing on file upload rather than image generation or other operations.

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

Usage Guidelines5/5

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

The description explicitly states when to use this tool: 'Useful when the image is larger than 20MB or reused across prompts.' This provides clear context for when this tool is appropriate versus alternatives, though it doesn't name specific sibling alternatives.

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/zhongweili/nanobanana-mcp-server'

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