generate_image_with_colors
Create images from text prompts with specific color palettes using Amazon Nova Canvas. Generate visuals for mockups, diagrams, and design concepts by providing descriptive text and hexadecimal color values.
Instructions
Generate an image using Amazon Nova Canvas with color guidance.
This tool uses Amazon Nova Canvas to generate images based on a text prompt and color palette.
The generated image will be saved to a file and the path will be returned.
IMPORTANT FOR Assistant: Always send the current workspace directory when calling this tool!
The workspace_dir parameter should be set to the directory where the user is currently working
so that images are saved to a location accessible to the user.
## Prompt Best Practices
An effective prompt often includes short descriptions of:
1. The subject
2. The environment
3. (optional) The position or pose of the subject
4. (optional) Lighting description
5. (optional) Camera position/framing
6. (optional) The visual style or medium ("photo", "illustration", "painting", etc.)
Do not use negation words like "no", "not", "without" in your prompt. Instead, use the
negative_prompt parameter to specify what you don't want in the image.
## Example Colors
- ["#FF5733", "#33FF57", "#3357FF"] - A vibrant color scheme with red, green, and blue
- ["#000000", "#FFFFFF"] - A high contrast black and white scheme
- ["#FFD700", "#B87333"] - A gold and bronze color scheme
Returns:
McpImageGenerationResponse: A response containing the generated image paths.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| prompt | Yes | The text description of the image to generate (1-1024 characters) | |
| colors | Yes | List of up to 10 hexadecimal color values (e.g., "#FF9800") | |
| negative_prompt | No | Text to define what not to include in the image (1-1024 characters) | |
| filename | No | The name of the file to save the image to (without extension) | |
| width | No | The width of the generated image (320-4096, divisible by 16) | |
| height | No | The height of the generated image (320-4096, divisible by 16) | |
| quality | No | The quality of the generated image ("standard" or "premium") | standard |
| cfg_scale | No | How strongly the image adheres to the prompt (1.1-10.0) | |
| seed | No | Seed for generation (0-858,993,459) | |
| number_of_images | No | The number of images to generate (1-5) | |
| workspace_dir | No | The current workspace directory where the image should be saved. CRITICAL: Assistant must always provide this parameter to save images to the user's current project. |
Implementation Reference
- Core handler function that executes the tool logic: validates parameters, constructs Nova Canvas API request, invokes Bedrock Runtime, decodes and saves generated images to workspace.async def generate_image_with_colors( prompt: str, colors: List[str], bedrock_runtime_client: BedrockRuntimeClient, negative_prompt: Optional[str] = None, filename: Optional[str] = None, width: int = DEFAULT_WIDTH, height: int = DEFAULT_HEIGHT, quality: str = DEFAULT_QUALITY, cfg_scale: float = DEFAULT_CFG_SCALE, seed: Optional[int] = None, number_of_images: int = DEFAULT_NUMBER_OF_IMAGES, workspace_dir: Optional[str] = None, ) -> ImageGenerationResponse: """Generate an image using Amazon Nova Canvas with color guidance. This function uses Amazon Nova Canvas to generate images based on a text prompt and color palette. The generated image will be saved to a file and the path will be returned. Args: prompt: The text description of the image to generate (1-1024 characters). colors: List of up to 10 hexadecimal color values (e.g., "#FF9800"). bedrock_runtime_client: BedrockRuntimeClient object. negative_prompt: Text to define what not to include in the image (1-1024 characters). filename: The name of the file to save the image to (without extension). If not provided, a random name will be generated. width: The width of the generated image (320-4096, divisible by 16). height: The height of the generated image (320-4096, divisible by 16). quality: The quality of the generated image ("standard" or "premium"). cfg_scale: How strongly the image adheres to the prompt (1.1-10.0). seed: Seed for generation (0-858,993,459). Random if not provided. number_of_images: The number of images to generate (1-5). workspace_dir: Directory where the images should be saved. If None, uses current directory. Returns: ImageGenerationResponse: An object containing the paths to the generated images, PIL Image objects, and status information. """ logger.debug( f"Generating color-guided image with prompt: '{prompt[:30]}...' and {len(colors)} colors" ) try: # Validate input parameters using Pydantic try: logger.debug('Validating parameters and creating color-guided request model') # Create image generation config config = ImageGenerationConfig( width=width, height=height, quality=Quality.STANDARD if quality == DEFAULT_QUALITY else Quality.PREMIUM, cfgScale=cfg_scale, seed=seed if seed is not None else random.randint(0, 858993459), numberOfImages=number_of_images, ) # Create color-guided params # The Nova Canvas API doesn't accept null for negativeText if negative_prompt is not None: color_params = ColorGuidedGenerationParams( colors=colors, text=prompt, negativeText=negative_prompt, ) else: color_params = ColorGuidedGenerationParams( colors=colors, text=prompt, ) # Create the full request request_model = ColorGuidedRequest( colorGuidedGenerationParams=color_params, imageGenerationConfig=config ) # Convert model to dictionary request_model_dict = request_model.to_api_dict() logger.info('Color-guided request validation successful') except Exception as e: logger.error(f'Color-guided parameter validation failed: {str(e)}') return ImageGenerationResponse( status='error', message=f'Validation error: {str(e)}', paths=[], prompt=prompt, negative_prompt=negative_prompt, colors=colors, ) try: # Invoke the Nova Canvas API logger.debug('Sending color-guided request to Nova Canvas API') model_response = await invoke_nova_canvas(request_model_dict, bedrock_runtime_client) # Extract the image data base64_images = model_response['images'] logger.info(f'Received {len(base64_images)} images from Nova Canvas API') # Save the generated images result = save_generated_images( base64_images, filename, number_of_images, prefix='nova_canvas_color', workspace_dir=workspace_dir, ) logger.info(f'Successfully generated {len(result["paths"])} color-guided image(s)') return ImageGenerationResponse( status='success', message=f'Generated {len(result["paths"])} image(s)', paths=result['paths'], prompt=prompt, negative_prompt=negative_prompt, colors=colors, ) except Exception as e: logger.error(f'Color-guided image generation failed: {str(e)}') return ImageGenerationResponse( status='error', message=str(e), paths=[], prompt=prompt, negative_prompt=negative_prompt, colors=colors, ) except Exception as e: logger.error(f'Unexpected error in generate_image_with_colors: {str(e)}') return ImageGenerationResponse( status='error', message=str(e), paths=[], prompt=prompt, negative_prompt=negative_prompt, colors=colors, )
- MCP tool registration and wrapper handler: decorated with @mcp.tool, defines tool input schema via Pydantic Fields, handles MCP context, logs, and delegates to core generate_image_with_colors function.@mcp.tool(name='generate_image_with_colors') async def mcp_generate_image_with_colors( ctx: Context, prompt: str = Field( description='The text description of the image to generate (1-1024 characters)' ), colors: List[str] = Field( description='List of up to 10 hexadecimal color values (e.g., "#FF9800")' ), negative_prompt: Optional[str] = Field( default=None, description='Text to define what not to include in the image (1-1024 characters)', ), filename: Optional[str] = Field( default=None, description='The name of the file to save the image to (without extension)', ), width: int = Field( default=1024, description='The width of the generated image (320-4096, divisible by 16)', ), height: int = Field( default=1024, description='The height of the generated image (320-4096, divisible by 16)', ), quality: str = Field( default='standard', description='The quality of the generated image ("standard" or "premium")', ), cfg_scale: float = Field( default=6.5, description='How strongly the image adheres to the prompt (1.1-10.0)', ), seed: Optional[int] = Field(default=None, description='Seed for generation (0-858,993,459)'), number_of_images: int = Field(default=1, description='The number of images to generate (1-5)'), workspace_dir: Optional[str] = Field( default=None, description="The current workspace directory where the image should be saved. CRITICAL: Assistant must always provide this parameter to save images to the user's current project.", ), ) -> McpImageGenerationResponse: """Generate an image using Amazon Nova Canvas with color guidance. This tool uses Amazon Nova Canvas to generate images based on a text prompt and color palette. The generated image will be saved to a file and the path will be returned. IMPORTANT FOR Assistant: Always send the current workspace directory when calling this tool! The workspace_dir parameter should be set to the directory where the user is currently working so that images are saved to a location accessible to the user. ## Prompt Best Practices An effective prompt often includes short descriptions of: 1. The subject 2. The environment 3. (optional) The position or pose of the subject 4. (optional) Lighting description 5. (optional) Camera position/framing 6. (optional) The visual style or medium ("photo", "illustration", "painting", etc.) Do not use negation words like "no", "not", "without" in your prompt. Instead, use the negative_prompt parameter to specify what you don't want in the image. ## Example Colors - ["#FF5733", "#33FF57", "#3357FF"] - A vibrant color scheme with red, green, and blue - ["#000000", "#FFFFFF"] - A high contrast black and white scheme - ["#FFD700", "#B87333"] - A gold and bronze color scheme Returns: McpImageGenerationResponse: A response containing the generated image paths. """ logger.debug( f"MCP tool generate_image_with_colors called with prompt: '{prompt[:30]}...', {len(colors)} colors" ) try: color_hex_list = ', '.join(colors[:3]) + (', ...' if len(colors) > 3 else '') logger.info( f'Generating color-guided image with colors: [{color_hex_list}], quality: {quality}' ) response = await generate_image_with_colors( prompt=prompt, colors=colors, bedrock_runtime_client=bedrock_runtime_client, negative_prompt=negative_prompt, filename=filename, width=width, height=height, quality=quality, cfg_scale=cfg_scale, seed=seed, number_of_images=number_of_images, workspace_dir=workspace_dir, ) if response.status == 'success': return McpImageGenerationResponse( status='success', paths=[f'file://{path}' for path in response.paths], ) else: logger.error( f'Color-guided image generation returned error status: {response.message}' ) await ctx.error(f'Failed to generate color-guided image: {response.message}') raise Exception(f'Failed to generate color-guided image: {response.message}') except Exception as e: logger.error(f'Error in mcp_generate_image_with_colors: {str(e)}') await ctx.error(f'Error generating color-guided image: {str(e)}') raise
- Pydantic schema for color-guided generation parameters used in the Nova Canvas API request, including hex color validation.class ColorGuidedGenerationParams(BaseModel): """Parameters for color-guided generation. This model defines the text prompts and color palette used to generate images. Attributes: colors: List of hexadecimal color values (e.g., "#FF9800") to guide the image generation. text: The text description of the image to generate (1-1024 characters). negativeText: Optional text to define what not to include in the image (1-1024 characters). """ colors: List[str] = Field(..., max_length=10) text: str = Field(..., min_length=1, max_length=1024) negativeText: Optional[str] = Field(default=None, min_length=1, max_length=1024) @field_validator('colors') @classmethod def validate_hex_colors(cls, v: List[str]) -> List[str]: """Validate that colors are in the correct hexadecimal format. Args: v: List of color strings to validate. Returns: The validated list if all colors pass. Raises: ValueError: If any color is not a valid hexadecimal color in the format '#RRGGBB'. """ hex_pattern = re.compile(r'^#[0-9A-Fa-f]{6}$') for color in v: if not hex_pattern.match(color): raise ValueError( f"Color '{color}' is not a valid hexadecimal color in the format '#RRGGBB'" ) return v
- Pydantic schema defining image generation configuration parameters with comprehensive validation for Nova Canvas API.class ImageGenerationConfig(BaseModel): """Configuration for image generation. This model defines the parameters that control the image generation process, including dimensions, quality, and generation settings. Attributes: width: Width of the generated image (320-4096, must be divisible by 16). height: Height of the generated image (320-4096, must be divisible by 16). quality: Quality level of the generated image (standard or premium). cfgScale: How strongly the image adheres to the prompt (1.1-10.0). seed: Seed for reproducible generation (0-858993459). numberOfImages: Number of images to generate (1-5). """ width: int = Field(default=1024, ge=320, le=4096) height: int = Field(default=1024, ge=320, le=4096) quality: Quality = Quality.STANDARD cfgScale: float = Field(default=6.5, ge=1.1, le=10.0) seed: int = Field(default_factory=lambda: random.randint(0, 858993459), ge=0, le=858993459) numberOfImages: int = Field(default=1, ge=1, le=5) @field_validator('width', 'height') @classmethod def must_be_divisible_by_16(cls, v: int) -> int: """Validate that width and height are divisible by 16. Args: v: The width or height value to validate. Returns: The validated value if it passes. Raises: ValueError: If the value is not divisible by 16. """ if v % 16 != 0: raise ValueError('Value must be divisible by 16') return v @model_validator(mode='after') def validate_aspect_ratio_and_total_pixels(self): """Validate aspect ratio and total pixel count. Ensures that: 1. The aspect ratio is between 1:4 and 4:1 2. The total pixel count is less than 4,194,304 Returns: The validated model if it passes. Raises: ValueError: If the aspect ratio or total pixel count is invalid. """ width = self.width height = self.height # Check aspect ratio between 1:4 and 4:1 aspect_ratio = width / height if aspect_ratio < 0.25 or aspect_ratio > 4.0: raise ValueError('Aspect ratio must be between 1:4 and 4:1') # Check total pixel count total_pixels = width * height if total_pixels >= 4194304: raise ValueError('Total pixel count must be less than 4,194,304') return self
- Pydantic model for the tool's output response containing status and generated image file paths.class McpImageGenerationResponse(BaseModel): """Response from image generation API. This model represents the response from the Amazon Nova Canvas API for both text-to-image and color-guided image generation. """ status: str paths: List[str]