Skip to main content
Glama

memory_upload_image

Upload image files to cloud storage for use in memory metadata, organizing them by memory ID with optional captions and indexing.

Instructions

Upload an image file directly to R2 storage.

Uploads a local image file to R2 and returns the r2:// reference URL that can be used in memory metadata.

Args: file_path: Absolute path to the image file to upload memory_id: Memory ID this image belongs to (used for organizing in R2) image_index: Index of image within the memory (default: 0) caption: Optional caption for the image

Returns: Dictionary with r2_url (the r2:// reference) and image object ready for metadata

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYes
memory_idYes
image_indexNo
captionNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Implementation of the memory_upload_image tool, which handles image file validation, R2 storage upload, and returning the image reference.
    async def memory_upload_image(
        file_path: str,
        memory_id: int,
        image_index: int = 0,
        caption: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Upload an image file directly to R2 storage.
    
        Uploads a local image file to R2 and returns the r2:// reference URL
        that can be used in memory metadata.
    
        Args:
            file_path: Absolute path to the image file to upload
            memory_id: Memory ID this image belongs to (used for organizing in R2)
            image_index: Index of image within the memory (default: 0)
            caption: Optional caption for the image
    
        Returns:
            Dictionary with r2_url (the r2:// reference) and image object ready for metadata
        """
        from pathlib import Path as _Path
    
        from PIL import Image as _PILImage
    
        from .image_storage import get_image_storage_instance
    
        image_storage = get_image_storage_instance()
        if not image_storage:
            return {
                "error": "r2_not_configured",
                "message": "R2 storage is not configured. Set MEMORA_STORAGE_URI to s3:// and configure AWS credentials.",
            }
    
        # --- Path validation (defense in depth) ---
        raw_path = _Path(file_path)
    
        # 1. Reject symlinks anywhere in the path chain
        for part in [raw_path] + list(raw_path.parents):
            if part.is_symlink():
                return {"error": "invalid_path", "message": "Symlinks are not supported"}
    
        try:
            resolved = raw_path.resolve(strict=True)
        except (OSError, ValueError):
            return {"error": "file_not_found", "message": "File not found"}
    
        # 2. Validate extension — aligned with image_storage.py ext_map
        _UPLOAD_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".webp"}
        if resolved.suffix.lower() not in _UPLOAD_EXTENSIONS:
            return {"error": "invalid_type", "message": "File must be an image (jpg, jpeg, png, gif, webp)"}
    
        # 3. Block known sensitive directories
        _BLOCKED_PATTERNS = [".ssh", ".gnupg", ".aws", ".config/gcloud", "id_rsa", "id_ed25519", ".env"]
        path_str = str(resolved).lower()
        for pattern in _BLOCKED_PATTERNS:
            if pattern in path_str:
                return {"error": "blocked_path", "message": "Cannot upload files from sensitive directories"}
    
        # 4. Verify file is actually an image and derive MIME from content
        _PILLOW_TO_MIME = {"JPEG": "image/jpeg", "PNG": "image/png", "GIF": "image/gif", "WEBP": "image/webp"}
        try:
            with _PILImage.open(str(resolved)) as img:
                img.verify()
                pillow_format = img.format
        except Exception:
            return {"error": "invalid_image", "message": "File is not a valid image"}
    
        content_type = _PILLOW_TO_MIME.get(pillow_format)
        if not content_type:
            return {"error": "unsupported_format", "message": f"Unsupported image format: {pillow_format}"}
    
        try:
            # Read file and upload
            with open(str(resolved), "rb") as f:
                image_data = f.read()
    
            r2_url = image_storage.upload_image(
                image_data=image_data,
                content_type=content_type,
                memory_id=memory_id,
                image_index=image_index,
            )
    
            # Build image object for metadata
            image_obj = {"src": r2_url}
            if caption:
                image_obj["caption"] = caption
    
            # Don't echo local file_path in response (path disclosure fix)
            return {
                "r2_url": r2_url,
                "image": image_obj,
                "content_type": content_type,
                "size_bytes": len(image_data),
            }
    
        except Exception as e:
            logger.error("Failed to upload image for memory %s: %s", memory_id, e)
            return {"error": "upload_failed", "message": "Image upload failed. Check server logs for details."}
Behavior4/5

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

With no annotations provided, the description carries the full burden and successfully discloses the external system interaction ('R2 storage'), the side effect (uploading file), and the return structure ('Dictionary with r2_url'). It does not cover idempotency or failure modes, but covers the primary behavioral traits adequately.

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

Conciseness4/5

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

The docstring format is well-structured with the main purpose front-loaded, followed by Args and Returns sections. It is appropriately sized given the zero schema coverage, though the Returns section repeats information available in the output schema.

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

Completeness5/5

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

For a 4-parameter tool with an output schema, the description is complete. It covers all inputs semantically, explains the output structure, and contextualizes the tool within the memory system ('memory metadata'). No critical gaps remain for invocation.

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

Parameters5/5

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

Schema description coverage is 0%, but the Args section compensates completely by providing semantic meaning for all four parameters: file_path is 'Absolute path,' memory_id explains 'organizing in R2,' image_index clarifies 'Index of image within the memory,' and caption notes it is 'Optional.'

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 opens with a specific action ('Upload') and target ('image file directly to R2 storage'), clearly distinguishing it from sibling tools like memory_migrate_images or memory_create. It precisely identifies the operation and destination resource.

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

Usage Guidelines4/5

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

The description provides clear context for when to use the tool by stating the return value 'can be used in memory metadata,' which clarifies its role in the memory workflow. However, it lacks explicit exclusions or named alternatives (e.g., when to use memory_migrate_images instead).

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/agentic-box/memora'

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