Skip to main content
Glama

convert_color

Convert colors between 22+ formats including HEX, RGB, HSL, CMYK, LAB, and framework-specific outputs for CSS, Swift, Android, Flutter, and Tailwind with configurable precision.

Instructions

Convert colors between different formats with high precision and comprehensive format support

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
colorYesInput color in any supported format (HEX, RGB, HSL, HSV, CMYK, LAB, XYZ, named colors, etc.)
output_formatYesDesired output format
precisionNoNumber of decimal places for numeric values
variable_nameNoVariable name for CSS/SCSS variable formats (optional)

Implementation Reference

  • The complete ToolHandler implementation for 'convert_color', including name, description, parameters schema, and the async handler function that validates inputs, calls the core conversion logic, handles errors, logs performance, and returns structured responses with metadata and recommendations.
    export const convertColorTool: ToolHandler = {
      name: 'convert_color',
      description:
        'Convert colors between different formats with high precision and comprehensive format support',
      parameters: {
        type: 'object',
        properties: {
          color: {
            type: 'string',
            description:
              'Input color in any supported format (HEX, RGB, HSL, HSV, CMYK, LAB, XYZ, named colors, etc.)',
            examples: [
              '#FF0000',
              'rgb(255, 0, 0)',
              'hsl(0, 100%, 50%)',
              'hsv(0, 100%, 100%)',
              'cmyk(0%, 100%, 100%, 0%)',
              'lab(53.23, 80.11, 67.22)',
              'red',
              '255, 0, 0',
            ],
          },
          output_format: {
            type: 'string',
            enum: [
              'hex',
              'rgb',
              'rgba',
              'hsl',
              'hsla',
              'hsv',
              'hsva',
              'hwb',
              'cmyk',
              'lab',
              'xyz',
              'lch',
              'oklab',
              'oklch',
              'css-var',
              'scss-var',
              'tailwind',
              'swift',
              'android',
              'flutter',
              'named',
            ],
            description: 'Desired output format',
          },
          precision: {
            type: 'number',
            minimum: 0,
            maximum: 10,
            default: 2,
            description: 'Number of decimal places for numeric values',
          },
          variable_name: {
            type: 'string',
            description: 'Variable name for CSS/SCSS variable formats (optional)',
            pattern: '^[a-zA-Z][a-zA-Z0-9-_]*$',
          },
        },
        required: ['color', 'output_format'],
      },
    
      handler: async (params: unknown) => {
        const startTime = Date.now();
    
        try {
          // Validate input parameters
          const validation = validateInput(convertColorSchema, params);
          if (!validation.isValid) {
            logger.warn('Color conversion validation failed', {
              tool: 'convert_color',
              executionTime: Date.now() - startTime,
            });
            return createValidationErrorResponse(
              'convert_color',
              validation.error!,
              Date.now() - startTime
            );
          }
    
          const { color, output_format, precision, variable_name } =
            validation.value as ConvertColorParams;
    
          logger.debug(`Converting color "${color}" to ${output_format}`, {
            tool: 'convert_color',
          });
    
          // Perform color conversion
          const result = convertColor(
            color,
            output_format,
            precision !== undefined ? precision : 2,
            variable_name
          );
    
          const executionTime = Date.now() - startTime;
    
          // Get color metadata for additional insights
          const parseResult = ColorParser.parse(color);
          const colorMetadata = parseResult.color?.metadata;
    
          logger.info(
            `Successfully converted color "${color}" to ${output_format}`,
            {
              tool: 'convert_color',
              executionTime,
            }
          );
    
          return createSuccessResponse('convert_color', result, executionTime, {
            colorSpaceUsed: 'sRGB',
            detectedInputFormat: parseResult.detectedFormat || 'unknown',
            ...(colorMetadata
              ? {
                  colorProperties: {
                    brightness: colorMetadata.brightness,
                    temperature: colorMetadata.temperature,
                    wcagAA: colorMetadata.accessibility.wcagAA,
                    wcagAAA: colorMetadata.accessibility.wcagAAA,
                  },
                }
              : {}),
            accessibilityNotes: colorMetadata
              ? [
                  `Brightness: ${colorMetadata.brightness}/255`,
                  `Color temperature: ${colorMetadata.temperature}`,
                  `WCAG AA compliant: ${colorMetadata.accessibility.wcagAA ? 'Yes' : 'No'}`,
                  `WCAG AAA compliant: ${colorMetadata.accessibility.wcagAAA ? 'Yes' : 'No'}`,
                ]
              : [],
            recommendations: [
              'For better color accuracy in professional applications, consider using LAB color space',
              'Use higher precision (3-4 decimal places) for color matching applications',
              'Test color accessibility with the check_contrast tool',
              executionTime > 50
                ? 'Consider caching frequently converted colors for better performance'
                : 'Conversion completed within optimal time',
            ],
          });
        } catch (error) {
          const executionTime = Date.now() - startTime;
          logger.error('Color conversion failed', {
            tool: 'convert_color',
            executionTime,
            error: error as Error,
          });
    
          // Provide helpful error messages based on error type
          let errorMessage = 'Color conversion failed';
          let suggestions: string[] = [];
    
          if (error instanceof Error) {
            if (
              error.message.includes('parse') ||
              error.message.includes('Unrecognized color format')
            ) {
              errorMessage = 'Invalid color format provided';
              suggestions = [
                'Supported formats: ' +
                  ColorParser.getSupportedFormats().join(', '),
                'Check the color value spelling and format',
                'Use quotes around color values in JSON',
              ];
            } else if (error.message.includes('Unsupported output format')) {
              errorMessage = 'Unsupported output format';
              suggestions = [
                'Use one of the supported output formats listed in the tool parameters',
                'Check the output_format parameter spelling',
              ];
            } else {
              // For generic errors, use the error message directly
              errorMessage = error.message;
              suggestions = [
                'Verify the input color is valid',
                'Try a different color format',
                'Check that all parameters are correctly specified',
              ];
            }
          }
    
          return {
            success: false,
            error: {
              code: 'CONVERSION_ERROR',
              message: errorMessage,
              details:
                process.env['NODE_ENV'] === 'development'
                  ? (error as Error).message
                  : undefined,
              suggestions,
            },
            metadata: {
              execution_time: executionTime,
              tool: 'convert_color',
              timestamp: new Date().toISOString(),
            },
          };
        }
      },
    };
  • Core helper function that performs the actual color parsing (using ColorParser), conversion to target format, and optional CSS/SCSS variable generation.
    function convertColor(
      color: string,
      outputFormat: SupportedFormat,
      precision: number = 2,
      variableName?: string
    ): ConversionResult {
      // Parse the input color
      const parseResult = ColorParser.parse(color);
    
      if (!parseResult.success || !parseResult.color) {
        throw new Error(parseResult.error || 'Failed to parse color');
      }
    
      const unifiedColor = parseResult.color;
    
      // Convert to the requested format
      const converted = unifiedColor.toFormat(outputFormat, precision);
    
      // Prepare result
      const result: ConversionResult = {
        original: color,
        converted,
        format: outputFormat,
        precision,
        detected_format: parseResult.detectedFormat || 'unknown',
      };
    
      // Add CSS/SCSS variables if requested or if format requires it
      if (variableName) {
        result.css_variable = unifiedColor.toCSSVariable(variableName);
        result.scss_variable = unifiedColor.toSCSSVariable(variableName);
      } else if (outputFormat === 'css-var') {
        result.css_variable = unifiedColor.toCSSVariable('color');
      } else if (outputFormat === 'scss-var') {
        result.scss_variable = unifiedColor.toSCSSVariable('color');
      }
    
      return result;
    }
  • JSON Schema definition for the tool's input parameters, defining types, enums, descriptions, and examples for color, output_format, precision, and variable_name.
    parameters: {
      type: 'object',
      properties: {
        color: {
          type: 'string',
          description:
            'Input color in any supported format (HEX, RGB, HSL, HSV, CMYK, LAB, XYZ, named colors, etc.)',
          examples: [
            '#FF0000',
            'rgb(255, 0, 0)',
            'hsl(0, 100%, 50%)',
            'hsv(0, 100%, 100%)',
            'cmyk(0%, 100%, 100%, 0%)',
            'lab(53.23, 80.11, 67.22)',
            'red',
            '255, 0, 0',
          ],
        },
        output_format: {
          type: 'string',
          enum: [
            'hex',
            'rgb',
            'rgba',
            'hsl',
            'hsla',
            'hsv',
            'hsva',
            'hwb',
            'cmyk',
            'lab',
            'xyz',
            'lch',
            'oklab',
            'oklch',
            'css-var',
            'scss-var',
            'tailwind',
            'swift',
            'android',
            'flutter',
            'named',
          ],
          description: 'Desired output format',
        },
        precision: {
          type: 'number',
          minimum: 0,
          maximum: 10,
          default: 2,
          description: 'Number of decimal places for numeric values',
        },
        variable_name: {
          type: 'string',
          description: 'Variable name for CSS/SCSS variable formats (optional)',
          pattern: '^[a-zA-Z][a-zA-Z0-9-_]*$',
        },
      },
      required: ['color', 'output_format'],
    },
  • Joi validation schema for runtime input validation of convert_color parameters, composed of individual secure schemas for each field with length limits, patterns, and custom messages.
    export const convertColorSchema = Joi.object({
      color: colorSchema,
      output_format: outputFormatSchema,
      precision: precisionSchema,
      variable_name: variableNameSchema.optional(),
    }).required();
  • Registration of the convertColorTool into the central ToolRegistry singleton, making it available for execution. Preceded by import at line 56.
    toolRegistry.registerTool(convertColorTool);
Behavior2/5

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

No annotations are provided, so the description carries full burden. It mentions 'high precision' and 'comprehensive format support' which are useful behavioral traits, but doesn't disclose important details like error handling, performance characteristics, rate limits, or what happens with invalid inputs. For a tool with no annotations, this leaves significant behavioral gaps.

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 clearly states the core functionality. It's appropriately sized for a straightforward conversion tool and wastes no words on redundant information.

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?

For a conversion tool with comprehensive schema documentation but no output schema and no annotations, the description provides basic context but lacks important details. It doesn't explain what the output looks like, how errors are handled, or provide examples of conversion results. Given the rich parameter schema, the description feels somewhat minimal.

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?

With 100% schema description coverage, the schema already documents all 4 parameters thoroughly. The description doesn't add meaningful parameter semantics beyond what's in the schema - it doesn't explain relationships between parameters or provide usage examples that go beyond the schema's examples and descriptions.

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: converting colors between formats with high precision and comprehensive format support. It specifies the verb ('convert') and resource ('colors'), but doesn't explicitly differentiate from sibling tools like 'analyze_color' or 'mix_colors' which have different functions.

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?

No guidance is provided about when to use this tool versus alternatives. With many sibling tools for color analysis, generation, and export, the description doesn't indicate whether this is for format conversion specifically versus other color operations, leaving the agent to infer usage context.

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