Skip to main content
Glama

create_palette_png

Generate PNG images of color palettes with customizable layouts, styles, and resolutions for design workflows.

Instructions

Generate high-quality PNG images of color palettes with professional layout and styling options

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
paletteYesArray of colors in any supported format
layoutNoLayout arrangement of color swatcheshorizontal
resolutionNoImage resolution in DPI
dimensionsNoCustom dimensions [width, height] in pixels
styleNoVisual style of color swatchesflat
labelsNoShow color values as labels
label_styleNoStyle of color labelsminimal
backgroundNoBackground color or transparencywhite
background_colorNoCustom background color (required if background is "custom")
marginNoMargin around the palette in pixels

Implementation Reference

  • The core handler function that executes the tool logic: validates input using Joi schema, checks color validity, generates SVG palette visualization, creates dual light/dark PNGs using dualBackgroundPNGGenerator, saves files via enhancedFileOutputManager, and returns structured FileBasedToolResponse.
    async function createPalettePng(
      params: unknown
    ): Promise<FileBasedToolResponse | ErrorResponse> {
      const startTime = Date.now();
    
      try {
        // Initialize file output manager
        await enhancedFileOutputManager.initialize();
    
        // Validate parameters
        const { error, value } = palettePngSchema.validate(params);
        if (error) {
          return createErrorResponse(
            'create_palette_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 PalettePngParams;
    
        // Validate colors
        const invalidColors: string[] = [];
        validatedParams.palette.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_palette_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 generatePalettePng(validatedParams);
    
        // Save files using enhanced file output manager
        const visualizationResult =
          await enhancedFileOutputManager.saveDualPNGVisualization(
            pngResult.lightBuffer,
            pngResult.darkBuffer,
            {
              toolName: 'create_palette_png',
              description: `Color palette with ${validatedParams.palette.length} colors`,
              customName: `palette-${validatedParams.layout}`,
              dimensions: pngResult.dimensions,
              resolution: validatedParams.resolution || 150,
              colorSpace: 'sRGB',
              parameters: validatedParams as unknown as Record<string, unknown>,
            }
          );
    
        const data: PalettePngData = {
          palette: validatedParams.palette,
          layout: validatedParams.layout || 'horizontal',
          dimensions: pngResult.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.palette.length,
        };
    
        const executionTime = Date.now() - startTime;
    
        return createFileBasedSuccessResponse(
          'create_palette_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',
              'Light variant works best on light backgrounds',
              'Dark variant works best on dark backgrounds',
              'Grid layout works best for large palettes',
            ],
          }
        );
      } catch (error) {
        logger.error('Error generating palette 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_palette_png',
          errorCode,
          errorMessage,
          startTime,
          {
            details: {
              error: errorMessage,
            },
            suggestions: [
              'Check image dimensions and color formats',
              'Ensure sufficient memory is available',
              'Try reducing image dimensions or resolution',
            ],
          }
        );
      }
    }
  • Joi validation schema for tool input parameters including palette array, layout, resolution, dimensions, style options, labels, background settings, and margins.
    const palettePngSchema = Joi.object({
      palette: Joi.array()
        .items(Joi.string().required())
        .min(1)
        .max(100)
        .required()
        .messages({
          'array.min': 'Palette must contain at least 1 color',
          'array.max': 'Palette cannot contain more than 100 colors',
        }),
      layout: Joi.string()
        .valid('horizontal', 'vertical', 'grid', 'circular')
        .default('horizontal'),
      resolution: Joi.number().valid(72, 150, 300, 600).default(150),
      dimensions: Joi.array()
        .items(Joi.number().integer().min(100).max(20000))
        .length(2)
        .optional(),
      style: Joi.string()
        .valid('flat', 'gradient', 'material', 'glossy', 'fabric', 'paper')
        .default('flat'),
      labels: Joi.boolean().default(true),
      label_style: Joi.string()
        .valid('minimal', 'detailed', 'branded')
        .default('minimal'),
      background: Joi.string()
        .valid('transparent', 'white', 'black', 'custom')
        .default('white'),
      background_color: Joi.string().when('background', {
        is: 'custom',
        then: Joi.required(),
        otherwise: Joi.optional(),
      }),
      margin: Joi.number().integer().min(0).max(100).default(20),
    });
  • Import of createPalettePngTool and registration in the central ToolRegistry singleton instance.
    import { createPalettePngTool } from './create-palette-png';
    import { createGradientPngTool } from './create-gradient-png';
    import { createColorComparisonPngTool } from './create-color-comparison-png';
    
    // Import and register theme generation tools
    import { generateThemeTool } from './generate-theme';
    import { generateSemanticColorsTool } from './generate-semantic-colors';
    
    // Import color utility tools
    import { mixColorsTool } from './mix-colors';
    import { generateColorVariationsTool } from './generate-color-variations';
    import { sortColorsTool } from './sort-colors';
    import { analyzeColorCollectionTool } from './analyze-color-collection';
    
    // Import export format tools
    import { exportCssTool } from './export-css';
    import { exportScssTool } from './export-scss';
    import { exportTailwindTool } from './export-tailwind';
    import { exportJsonTool } from './export-json';
    
    // Register conversion tools
    toolRegistry.registerTool(convertColorTool);
    
    // Register analysis tools
    toolRegistry.registerTool(analyzeColorTool);
    toolRegistry.registerTool(checkContrastTool);
    
    // Register accessibility tools
    toolRegistry.registerTool(simulateColorblindnessTool);
    toolRegistry.registerTool(optimizeForAccessibilityTool);
    
    // Register palette generation tools
    toolRegistry.registerTool(generateHarmonyPaletteTool);
    
    // Register gradient generation tools
    toolRegistry.registerTool(generateLinearGradientTool);
    toolRegistry.registerTool(generateRadialGradientTool);
    
    // Register visualization tools
    toolRegistry.registerTool(createPaletteHtmlTool);
    toolRegistry.registerTool(createColorWheelHtmlTool);
    toolRegistry.registerTool(createGradientHtmlTool);
    toolRegistry.registerTool(createThemePreviewHtmlTool);
    
    // Register PNG generation tools
    toolRegistry.registerTool(createPalettePngTool);
  • Exported Joi schema for create_palette_png tool parameters, providing global validation reference.
    export const createPalettePngSchema = Joi.object({
      palette: colorArraySchema.required(),
      layout: Joi.string()
        .valid('horizontal', 'vertical', 'grid', 'circular')
        .default('horizontal'),
      resolution: Joi.number().valid(72, 150, 300, 600).default(150),
      dimensions: dimensionSchema.optional(),
      style: Joi.string()
        .valid('flat', 'gradient', 'material', 'glossy', 'fabric', 'paper')
        .default('flat'),
      labels: Joi.boolean().default(true),
      label_style: Joi.string()
        .valid('minimal', 'detailed', 'branded')
        .default('minimal'),
      background: Joi.string()
        .valid('transparent', 'white', 'black', 'custom')
        .default('white'),
      background_color: colorSchema.when('background', {
        is: 'custom',
        then: Joi.required(),
        otherwise: Joi.optional(),
      }),
      margin: Joi.number().min(0).max(100).default(20),
    }).required();
  • Helper function that orchestrates PNG generation: dimension calculation, SVG creation, dual-background PNG rendering, and quality validation.
    async function generatePalettePng(params: PalettePngParams): Promise<{
      lightBuffer: Buffer;
      darkBuffer: Buffer;
      dimensions: [number, number];
    }> {
      const {
        palette,
        layout = 'horizontal',
        dimensions,
        style = 'flat',
        labels = true,
        label_style = 'minimal',
        margin = 20,
      } = params;
    
      // Calculate dimensions
      const [width, height] = calculateDimensions(
        palette.length,
        layout,
        dimensions
      );
    
      // Create base SVG content (without background)
      const svgContent = createPaletteSvg(
        palette,
        layout,
        [width, height],
        style,
        labels,
        label_style,
        'transparent', // Always use transparent for base SVG
        undefined,
        margin
      );
    
      // Generate dual background PNGs
      const result = await dualBackgroundPNGGenerator.generateDualPNG(
        svgContent,
        [width, height],
        {
          lightBackground: '#ffffff',
          darkBackground: '#1a1a1a',
          intelligentTextColor: true,
          quality: 'standard',
        }
      );
    
      // Validate visual quality
      const qualityCheck = await dualBackgroundPNGGenerator.validateVisualQuality(
        result.lightBuffer,
        result.darkBuffer,
        [width, height]
      );
    
      if (!qualityCheck.valid) {
        logger.warn('PNG quality validation issues detected', {
          issues: qualityCheck.issues,
        });
      }
    
      return {
        lightBuffer: result.lightBuffer,
        darkBuffer: result.darkBuffer,
        dimensions: [width, height],
      };
    }
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. It mentions 'high-quality' and 'professional' traits but lacks critical details: whether this is a read-only or mutating operation, any rate limits, authentication needs, error handling, or what the output looks like (e.g., file format details). For a tool with 10 parameters and no annotations, 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 without unnecessary words. It directly states what the tool does ('Generate high-quality PNG images of color palettes') and adds key features ('with professional layout and styling options'), making it easy to parse quickly.

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

Completeness2/5

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

Given the tool's complexity (10 parameters, no annotations, no output schema), the description is incomplete. It doesn't address behavioral aspects like mutation risks, output format details, or usage context relative to siblings. For a tool that generates files with many options, more guidance is needed to ensure correct invocation.

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?

The description adds minimal meaning beyond the input schema, which has 100% coverage. It implies parameters like 'layout' and 'styling options' but doesn't elaborate on their semantics or interactions. With high schema coverage, the baseline is 3, as the schema already documents parameters well, but the description doesn't enhance understanding significantly.

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 color palettes with professional layout and styling options.' It specifies the verb ('Generate'), resource ('PNG images of color palettes'), and key characteristics ('high-quality,' 'professional layout and styling options'). However, it doesn't explicitly differentiate from sibling tools like 'create_palette_html' or 'create_color_comparison_png,' which prevents 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. It doesn't mention sibling tools like 'create_palette_html' (for HTML output) or 'create_color_comparison_png' (for comparisons), nor does it specify prerequisites or exclusions. This leaves the agent without context for tool selection.

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