Skip to main content
Glama
ECNU3D

Universal Image Generator MCP Server

by ECNU3D

transform_image_from_encoded

Modify an existing image using a text prompt to describe changes, generating a new version based on the input image and instructions.

Instructions

Transform an existing image based on the given text prompt using the configured image provider.

    Args:
        encoded_image: Base64 encoded image data with header. Must be in format:
                    "data:image/[format];base64,[data]"
                    Where [format] can be: png, jpeg, jpg, gif, webp, etc.
        prompt: Text prompt describing the desired transformation or modifications
        
    Returns:
        Path to the transformed image file saved on the server
    

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
encoded_imageYes
promptYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The core handler function for the 'transform_image_from_encoded' MCP tool. It is registered via the @mcp.tool() decorator. Loads base64-encoded image, translates and enhances the prompt, invokes the image provider's transformation method, saves the result, and returns the file path (and optional remote URL).
    @mcp.tool()
    async def transform_image_from_encoded(encoded_image: str, prompt: str) -> str:
        """Transform an existing image based on the given text prompt using the configured image provider.
    
        Args:
            encoded_image: Base64 encoded image data with header. Must be in format:
                        "data:image/[format];base64,[data]"
                        Where [format] can be: png, jpeg, jpg, gif, webp, etc.
            prompt: Text prompt describing the desired transformation or modifications
            
        Returns:
            Path to the transformed image file saved on the server
        """
        try:
            provider = get_image_provider()
            logger.info(f"Processing transform_image_from_encoded request with {provider.get_name()}")
            logger.info(f"Transformation prompt: {prompt}")
    
            # Load and validate the image
            source_image, _ = await load_image_from_base64(encoded_image)
            
            # Translate the prompt for the provider
            translated_prompt = await translate_prompt_for_provider(prompt, provider)
            
            # Create detailed transformation prompt
            transformation_prompt = get_image_transformation_prompt(translated_prompt)
            
            # Process the transformation using the provider
            _, saved_path, remote_url = await provider.transform_image(source_image, transformation_prompt)
            
            logger.info(f"Image transformed and saved to: {saved_path}")
            
            # Prepare response with remote URL if available
            response = f"Image transformed and saved to: {saved_path}"
            if remote_url:
                response += f"\nRemote URL: {remote_url}"
            
            return response
            
        except Exception as e:
            error_msg = f"Error transforming image: {str(e)}"
            logger.error(error_msg)
            return error_msg
  • The @mcp.tool() decorator registers the transform_image_from_encoded function as an MCP tool. Registration is conditional on the provider supporting image transformation (see lines 252-260).
    @mcp.tool()
  • Helper function used by the handler to load and validate the base64-encoded input image into a PIL Image object.
    async def load_image_from_base64(encoded_image: str) -> Tuple[PIL.Image.Image, str]:
        """Load an image from a base64-encoded string.
        
        Args:
            encoded_image: Base64 encoded image data with header
            
        Returns:
            Tuple containing the PIL Image object and the image format
        """
        if not encoded_image.startswith('data:image/'):
            raise ValueError("Invalid image format. Expected data:image/[format];base64,[data]")
        
        try:
            # Extract the base64 data from the data URL
            image_format, image_data = encoded_image.split(';base64,')
            image_format = image_format.replace('data:', '')  # Get the MIME type e.g., "image/png"
            image_bytes = base64.b64decode(image_data)
            source_image = PIL.Image.open(BytesIO(image_bytes))
            logger.info(f"Successfully loaded image with format: {image_format}")
            return source_image, image_format
        except binascii.Error as e:
            logger.error(f"Error: Invalid base64 encoding: {str(e)}")
            raise ValueError("Invalid base64 encoding. Please provide a valid base64 encoded image.")
        except ValueError as e:
            logger.error(f"Error: Invalid image data format: {str(e)}")
            raise ValueError("Invalid image data format. Image must be in format 'data:image/[format];base64,[data]'")
        except PIL.UnidentifiedImageError:
            logger.error("Error: Could not identify image format")
            raise ValueError("Could not identify image format. Supported formats include PNG, JPEG, GIF, WebP.")
        except Exception as e:
            logger.error(f"Error: Could not load image: {str(e)}")
            raise
Behavior3/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It explains the transformation process and output format ('Path to the transformed image file saved on the server'), but doesn't mention important behavioral aspects like rate limits, authentication requirements, file size limits, transformation time, error conditions, or what happens to the original image. For a tool with no annotations, this leaves significant gaps.

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 description is well-structured with clear sections (purpose, Args, Returns) and every sentence adds value. It could be slightly more concise by combining some formatting details, but overall it's efficiently organized and front-loaded with the core purpose.

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?

Given the tool's complexity (image transformation with specific input requirements), no annotations, and an output schema (implied by 'Returns' statement), the description does a good job covering the essentials. It explains the transformation process, input format requirements, and output format. However, it lacks information about behavioral constraints and error handling that would be important for complete understanding.

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?

With 0% schema description coverage, the description fully compensates by providing detailed semantic information for both parameters. It specifies the exact format required for encoded_image ('Base64 encoded image data with header' with specific format examples) and explains what prompt represents ('Text prompt describing the desired transformation or modifications'). This adds substantial value beyond the bare schema.

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 tool's purpose: 'Transform an existing image based on the given text prompt using the configured image provider.' This specifies the verb ('transform'), resource ('existing image'), method ('based on text prompt'), and distinguishes it from sibling tools like generate_image_from_text (creates new images) and transform_image_from_file/url (different input methods).

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 provides explicit usage guidance by specifying the input method ('Base64 encoded image data') and distinguishing this tool from its siblings. The context of sibling tools (generate_image_from_text, transform_image_from_file, transform_image_from_url) makes it clear when to use this specific tool versus alternatives based on input format.

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/ECNU3D/universal-image-generator-mcp'

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