Skip to main content
Glama

create_gradient_png

Generate PNG images of custom gradients for design projects. Specify gradient type, colors, dimensions, and effects to create visual assets.

Instructions

Generate high-quality PNG images of gradients with various styles and effects

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
gradientYes
dimensionsYesImage dimensions [width, height] in pixels
resolutionNoImage resolution in DPI
formatNoPNG format typepng32
qualityNoImage quality levelstandard
effectsNoVisual effects to apply

Implementation Reference

  • Primary handler function that validates input using Joi schema, validates colors, generates SVG gradient, creates light/dark PNG variants using dualBackgroundPNGGenerator, saves files via enhancedFileOutputManager, and returns structured FileBasedToolResponse or ErrorResponse.
    async function createGradientPng(
      params: unknown
    ): Promise<FileBasedToolResponse | ErrorResponse> {
      const startTime = Date.now();
    
      try {
        // Initialize file output manager
        await enhancedFileOutputManager.initialize();
    
        // Validate parameters
        const { error, value } = gradientPngSchema.validate(params);
        if (error) {
          return createErrorResponse(
            'create_gradient_png',
            'INVALID_PARAMETERS',
            `Invalid parameters: ${error.details.map(d => d.message).join(', ')}`,
            startTime,
            {
              details: error.details,
              suggestions: [
                'Check the parameter format',
                'Ensure all required fields are provided',
              ],
            }
          );
        }
    
        const validatedParams = value as GradientPngParams;
    
        // Validate colors
        const invalidColors: string[] = [];
        validatedParams.gradient.colors.forEach((colorStr, index) => {
          try {
            const color = colord(colorStr);
            if (!color.isValid()) {
              invalidColors.push(`${colorStr} at index ${index}`);
            }
          } catch {
            invalidColors.push(`${colorStr} at index ${index}`);
          }
        });
    
        if (invalidColors.length > 0) {
          return createErrorResponse(
            'create_gradient_png',
            'INVALID_COLOR_FORMAT',
            `Invalid colors found: ${invalidColors.join(', ')}`,
            startTime,
            {
              details: { invalidColors },
              suggestions: [
                'Use valid color formats like #FF0000, rgb(255,0,0), or hsl(0,100%,50%)',
              ],
            }
          );
        }
    
        // Generate dual background PNGs
        const pngResult = await generateGradientPng(validatedParams);
    
        // Save files using enhanced file output manager
        const visualizationResult =
          await enhancedFileOutputManager.saveDualPNGVisualization(
            pngResult.lightBuffer,
            pngResult.darkBuffer,
            {
              toolName: 'create_gradient_png',
              description: `${validatedParams.gradient.type} gradient with ${validatedParams.gradient.colors.length} colors`,
              customName: `gradient-${validatedParams.gradient.type}`,
              dimensions: pngResult.dimensions,
              resolution: validatedParams.resolution || 150,
              colorSpace: 'sRGB',
              parameters: validatedParams as unknown as Record<string, unknown>,
            }
          );
    
        const data: GradientPngData = {
          gradient_type: validatedParams.gradient.type,
          dimensions: validatedParams.dimensions,
          resolution: validatedParams.resolution || 150,
          light_file_size: pngResult.lightBuffer.length,
          dark_file_size: pngResult.darkBuffer.length,
          total_file_size:
            pngResult.lightBuffer.length + pngResult.darkBuffer.length,
          color_count: validatedParams.gradient.colors.length,
        };
    
        const executionTime = Date.now() - startTime;
    
        return createFileBasedSuccessResponse(
          'create_gradient_png',
          data,
          executionTime,
          visualizationResult,
          {
            colorSpaceUsed: 'sRGB',
            accessibilityNotes: [
              'Light background variant optimized for light themes',
              'Dark background variant optimized for dark themes',
            ],
            recommendations: [
              'Use high resolution (300+ DPI) for print applications',
              'Linear gradients work best for backgrounds',
              'Light variant works best on light backgrounds',
              'Dark variant works best on dark backgrounds',
              'Consider adding subtle effects for enhanced visual appeal',
            ],
          }
        );
      } catch (error) {
        logger.error('Error generating gradient PNG', { error: error as Error });
        const errorMessage =
          error instanceof Error ? error.message : 'Unknown error occurred';
        const errorCode =
          errorMessage.includes('memory limits') || errorMessage.includes('exceeds')
            ? 'MEMORY_LIMIT_ERROR'
            : 'PNG_GENERATION_ERROR';
    
        return createErrorResponse(
          'create_gradient_png',
          errorCode,
          errorMessage,
          startTime,
          {
            details: {
              error: errorMessage,
            },
            suggestions: [
              'Check gradient parameters and dimensions',
              'Ensure sufficient memory is available',
              'Try reducing image dimensions or resolution',
            ],
          }
        );
      }
    }
  • ToolHandler definition including the JSON Schema for input validation (parameters object) and reference to the handler function.
    export const createGradientPngTool: ToolHandler = {
      name: 'create_gradient_png',
      description:
        'Generate high-quality PNG images of gradients with various styles and effects',
      parameters: {
        type: 'object',
        properties: {
          gradient: {
            type: 'object',
            properties: {
              type: {
                type: 'string',
                enum: ['linear', 'radial', 'conic'],
                description: 'Type of gradient',
              },
              colors: {
                type: 'array',
                items: { type: 'string' },
                minItems: 2,
                maxItems: 20,
                description: 'Array of colors for the gradient',
              },
              positions: {
                type: 'array',
                items: { type: 'number', minimum: 0, maximum: 100 },
                description: 'Optional positions for color stops (0-100)',
              },
              angle: {
                type: 'number',
                minimum: 0,
                maximum: 360,
                default: 90,
                description: 'Angle for linear gradients (degrees)',
              },
              center: {
                type: 'array',
                items: { type: 'number', minimum: 0, maximum: 100 },
                minItems: 2,
                maxItems: 2,
                default: [50, 50],
                description: 'Center point for radial/conic gradients [x, y]',
              },
              shape: {
                type: 'string',
                enum: ['circle', 'ellipse'],
                default: 'circle',
                description: 'Shape for radial gradients',
              },
            },
            required: ['type', 'colors'],
          },
          dimensions: {
            type: 'array',
            items: { type: 'number', minimum: 100, maximum: 20000 },
            minItems: 2,
            maxItems: 2,
            description: 'Image dimensions [width, height] in pixels',
          },
          resolution: {
            type: 'number',
            enum: [72, 150, 300, 600],
            default: 150,
            description: 'Image resolution in DPI',
          },
          format: {
            type: 'string',
            enum: ['png', 'png24', 'png32'],
            default: 'png32',
            description: 'PNG format type',
          },
          quality: {
            type: 'string',
            enum: ['draft', 'standard', 'high', 'ultra'],
            default: 'standard',
            description: 'Image quality level',
          },
          effects: {
            type: 'array',
            items: {
              type: 'string',
              enum: ['noise', 'texture', 'border', 'shadow'],
            },
            default: [],
            description: 'Visual effects to apply',
          },
        },
        required: ['gradient', 'dimensions'],
      },
      handler: createGradientPng,
    };
  • Registration of the createGradientPngTool (imported from './create-gradient-png') into the central ToolRegistry singleton.
    toolRegistry.registerTool(createPalettePngTool);
    toolRegistry.registerTool(createGradientPngTool);
    toolRegistry.registerTool(createColorComparisonPngTool);
  • Internal Joi schema used for runtime validation of input parameters within the handler.
    const gradientPngSchema = Joi.object({
      gradient: Joi.object({
        type: Joi.string().valid('linear', 'radial', 'conic').required(),
        colors: Joi.array().items(Joi.string()).min(2).max(20).required(),
        positions: Joi.array().items(Joi.number().min(0).max(100)).optional(),
        angle: Joi.number().min(0).max(360).default(90),
        center: Joi.array()
          .items(Joi.number().min(0).max(100))
          .length(2)
          .default([50, 50]),
        shape: Joi.string().valid('circle', 'ellipse').default('circle'),
      }).required(),
      dimensions: Joi.array()
        .items(Joi.number().integer().min(100).max(20000))
        .length(2)
        .required(),
      resolution: Joi.number().valid(72, 150, 300, 600).default(150),
      format: Joi.string().valid('png', 'png24', 'png32').default('png32'),
      quality: Joi.string()
        .valid('draft', 'standard', 'high', 'ultra')
        .default('standard'),
      effects: Joi.array()
        .items(Joi.string().valid('noise', 'texture', 'border', 'shadow'))
        .default([]),
    });
  • Helper function to generate light and dark PNG buffers from gradient SVG content using external PNG generator.
    async function generateGradientPng(params: GradientPngParams): Promise<{
      lightBuffer: Buffer;
      darkBuffer: Buffer;
      dimensions: [number, number];
    }> {
      const { gradient, dimensions, quality = 'standard', effects = [] } = params;
    
      // Create base SVG content (gradients don't need background modification)
      const svgContent = createGradientSvg(gradient, dimensions, effects);
    
      // Generate dual background PNGs
      const result = await dualBackgroundPNGGenerator.generateDualPNG(
        svgContent,
        dimensions,
        {
          lightBackground: '#ffffff',
          darkBackground: '#1a1a1a',
          intelligentTextColor: true,
          quality,
        }
      );
    
      // Validate visual quality
      const qualityCheck = await dualBackgroundPNGGenerator.validateVisualQuality(
        result.lightBuffer,
        result.darkBuffer,
        dimensions
      );
    
      if (!qualityCheck.valid) {
        logger.warn('PNG quality validation issues detected', {
          issues: qualityCheck.issues,
        });
      }
    
      return {
        lightBuffer: result.lightBuffer,
        darkBuffer: result.darkBuffer,
        dimensions,
      };
    }
Behavior2/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. While it mentions 'high-quality' and 'various styles and effects,' it doesn't address critical behavioral aspects like whether this is a read-only operation, what happens on failure, performance characteristics, or output format details. For a tool that generates images with multiple parameters, this is insufficient.

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 a single, efficient sentence that front-loads the core purpose. Every word earns its place: 'Generate' (action), 'high-quality PNG images' (output type and quality), 'of gradients' (subject), 'with various styles and effects' (capabilities). There's no wasted verbiage or 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 the tool's complexity (6 parameters with nested objects, no output schema, no annotations), the description is minimally adequate but incomplete. It identifies what the tool does but doesn't address behavioral aspects, usage context, or output expectations. For a tool that generates visual content with multiple configuration options, more guidance would be helpful despite the good schema coverage.

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 83%, which is high, so the baseline is 3. The description adds minimal value beyond the schema - it mentions 'various styles and effects' which loosely relates to the 'effects' parameter, but doesn't provide additional semantic context about how parameters interact or what constitutes 'high-quality' in relation to the quality parameter. The schema already documents parameters well.

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's purpose: 'Generate high-quality PNG images of gradients with various styles and effects.' It specifies the verb ('Generate'), resource ('PNG images of gradients'), and quality attributes. However, it doesn't explicitly differentiate from sibling tools like create_gradient_html or create_palette_png, which would be needed for a perfect score.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. With many sibling tools for creating gradients and other color-related outputs (e.g., create_gradient_html, create_palette_png, generate_linear_gradient), there's no indication of when PNG output is preferred over HTML or when this tool should be chosen over more specific gradient generators.

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/keyurgolani/ColorMcp'

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