Skip to main content
Glama

simulate_colorblindness

Simulate color appearance for users with color vision deficiencies to test accessibility and ensure designs are perceivable by all.

Instructions

Simulate how colors appear to users with color vision deficiencies

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
colorsYesArray of colors to simulate
typeYesType of color vision deficiency to simulate
severityNoSeverity percentage (0-100, default: 100)

Implementation Reference

  • The primary handler function executing the colorblindness simulation logic using transformation matrices for various deficiency types.
    export async function simulateColorblindness(
      params: SimulateColorblindnessParams
    ): Promise<ToolResponse | ErrorResponse> {
      const startTime = Date.now();
    
      try {
        // Validate required parameters
        if (
          !params.colors ||
          !Array.isArray(params.colors) ||
          params.colors.length === 0
        ) {
          return createErrorResponse(
            'simulate_colorblindness',
            'MISSING_COLORS',
            'Colors array parameter is required and must not be empty',
            Date.now() - startTime,
            {
              details: { provided: params.colors },
              suggestions: ['Provide an array of colors in any supported format'],
            }
          );
        }
    
        if (!params.type) {
          return createErrorResponse(
            'simulate_colorblindness',
            'MISSING_TYPE',
            'Deficiency type parameter is required',
            Date.now() - startTime,
            {
              details: {
                supportedTypes: [
                  'protanopia',
                  'deuteranopia',
                  'tritanopia',
                  'protanomaly',
                  'deuteranomaly',
                  'tritanomaly',
                  'monochromacy',
                ],
              },
              suggestions: ['Specify a color vision deficiency type'],
            }
          );
        }
    
        // Validate deficiency type
        const validTypes = [
          'protanopia',
          'deuteranopia',
          'tritanopia',
          'protanomaly',
          'deuteranomaly',
          'tritanomaly',
          'monochromacy',
        ];
        if (!validTypes.includes(params.type)) {
          return createErrorResponse(
            'simulate_colorblindness',
            'INVALID_DEFICIENCY_TYPE',
            `Invalid deficiency type: ${params.type}`,
            Date.now() - startTime,
            {
              details: { provided: params.type, supported: validTypes },
              suggestions: ['Use one of the supported deficiency types'],
            }
          );
        }
    
        // Validate severity
        const severity = params.severity ?? 100;
        if (severity < 0 || severity > 100) {
          return createErrorResponse(
            'simulate_colorblindness',
            'INVALID_SEVERITY',
            'Severity must be between 0 and 100',
            Date.now() - startTime,
            {
              details: { provided: severity },
              suggestions: [
                'Use a severity value between 0 (no effect) and 100 (full effect)',
              ],
            }
          );
        }
    
        // Validate all color inputs
        const validatedColors: UnifiedColor[] = [];
        for (let i = 0; i < params.colors.length; i++) {
          const colorInput = params.colors[i];
          if (!colorInput) {
            return createErrorResponse(
              'simulate_colorblindness',
              'INVALID_COLOR_FORMAT',
              `Color at index ${i} is undefined or null`,
              Date.now() - startTime,
              {
                details: { index: i, provided: colorInput },
                suggestions: ['Ensure all colors in the array are valid strings'],
              }
            );
          }
    
          const validation = validateColorInput(colorInput);
    
          if (!validation.isValid) {
            return createErrorResponse(
              'simulate_colorblindness',
              'INVALID_COLOR_FORMAT',
              `Invalid color format at index ${i}: ${colorInput}`,
              Date.now() - startTime,
              {
                details: {
                  index: i,
                  provided: colorInput,
                  error: validation.error,
                },
                suggestions: [
                  'Use valid color formats like #FF0000 or rgb(255, 0, 0)',
                ],
              }
            );
          }
    
          try {
            validatedColors.push(new UnifiedColor(colorInput));
          } catch (error) {
            return createErrorResponse(
              'simulate_colorblindness',
              'COLOR_PARSING_ERROR',
              `Failed to parse color at index ${i}: ${colorInput}`,
              Date.now() - startTime,
              {
                details: {
                  index: i,
                  provided: colorInput,
                  error: error instanceof Error ? error.message : 'Unknown error',
                },
                suggestions: ['Check the color format and try again'],
              }
            );
          }
        }
    
        // Simulate colorblindness for each color
        const results: ColorblindSimulationResult[] = [];
        let totalDifference = 0;
        let colorsAffected = 0;
    
        for (let i = 0; i < validatedColors.length; i++) {
          const originalColor = validatedColors[i];
          const originalColorString = params.colors[i];
    
          if (!originalColor || !originalColorString) {
            continue; // Skip invalid entries
          }
    
          const simulatedColor = simulateColorVisionDeficiency(
            originalColor,
            params.type,
            severity
          );
    
          // Calculate difference between original and simulated colors
          const differenceScore = calculateColorDifference(
            originalColor,
            simulatedColor
          );
    
          // Determine accessibility impact
          let accessibilityImpact: ColorblindSimulationResult['accessibility_impact'];
          if (differenceScore < 5) {
            accessibilityImpact = 'none';
          } else if (differenceScore < 15) {
            accessibilityImpact = 'minimal';
          } else if (differenceScore < 30) {
            accessibilityImpact = 'moderate';
          } else {
            accessibilityImpact = 'severe';
          }
    
          if (differenceScore > 5) {
            colorsAffected++;
          }
    
          totalDifference += differenceScore;
    
          results.push({
            original_color: originalColorString,
            simulated_color: simulatedColor.hex,
            difference_score: Math.round(differenceScore * 100) / 100,
            accessibility_impact: accessibilityImpact,
          });
        }
    
        // Generate summary
        const averageDifference = totalDifference / validatedColors.length;
        const accessibilityConcerns: string[] = [];
    
        if (colorsAffected > 0) {
          accessibilityConcerns.push(
            `${colorsAffected} out of ${validatedColors.length} colors are significantly affected`
          );
        }
    
        if (averageDifference > 20) {
          accessibilityConcerns.push('High overall color distortion detected');
        }
    
        if (params.type.includes('anomaly') && severity > 50) {
          accessibilityConcerns.push(
            'Moderate to severe color vision anomaly simulation'
          );
        }
    
        // Generate recommendations
        const recommendations = generateRecommendations(
          params.type,
          results,
          averageDifference
        );
    
        const responseData: SimulateColorblindnessResponse = {
          deficiency_type: params.type,
          severity,
          results,
          summary: {
            total_colors: validatedColors.length,
            colors_affected: colorsAffected,
            average_difference: Math.round(averageDifference * 100) / 100,
            accessibility_concerns: accessibilityConcerns,
          },
          recommendations,
        };
    
        const executionTime = Date.now() - startTime;
    
        // Generate accessibility notes
        const accessibilityNotes: string[] = [];
        if (colorsAffected > 0) {
          accessibilityNotes.push(
            `${colorsAffected} colors show significant changes for ${params.type} users`
          );
        }
        if (averageDifference > 15) {
          accessibilityNotes.push(
            'Consider using alternative color combinations for better accessibility'
          );
        }
    
        return createSuccessResponse(
          'simulate_colorblindness',
          responseData,
          executionTime,
          {
            colorSpaceUsed: 'sRGB',
            accessibilityNotes,
            recommendations: recommendations.slice(0, 5),
          }
        );
      } catch (error) {
        const executionTime = Date.now() - startTime;
        return createErrorResponse(
          'simulate_colorblindness',
          'SIMULATION_ERROR',
          `Failed to simulate colorblindness: ${error instanceof Error ? error.message : 'Unknown error'}`,
          executionTime,
          {
            details: {
              type: params.type,
              colors: params.colors?.length || 0,
            },
            suggestions: [
              'Check input parameters and try again',
              'Ensure all colors are in valid formats',
            ],
          }
        );
      }
    }
  • Imports and registers the simulate_colorblindness tool with the central tool registry.
    import { simulateColorblindnessTool } from './simulate-colorblindness';
    import { optimizeForAccessibilityTool } from './optimize-for-accessibility';
    
    // Import and register palette generation tools
    import { generateHarmonyPaletteTool } from './generate-harmony-palette';
    
    // Import and register gradient generation tools
    import { generateLinearGradientTool } from './generate-linear-gradient';
    import { generateRadialGradientTool } from './generate-radial-gradient';
    
    // Import and register visualization tools
    import { createPaletteHtmlTool } from './create-palette-html';
    import { createColorWheelHtmlTool } from './create-color-wheel-html';
    import { createGradientHtmlTool } from './create-gradient-html';
    import { createThemePreviewHtmlTool } from './create-theme-preview-html';
    
    // Import and register PNG generation tools
    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);
  • Joi validation schema for simulate_colorblindness tool inputs.
    export const simulateColorblindnessSchema = Joi.object({
      colors: colorArraySchema.required(),
      type: Joi.string()
        .valid(
          'protanopia',
          'deuteranopia',
          'tritanopia',
          'protanomaly',
          'deuteranomaly',
          'tritanomaly',
          'monochromacy'
        )
        .required(),
      severity: Joi.number().min(0).max(100).default(100),
    }).required();
  • Tool object definition including MCP schema and handler wrapper for registration.
    export const simulateColorblindnessTool = {
      name: 'simulate_colorblindness',
      description:
        'Simulate how colors appear to users with color vision deficiencies',
      parameters: {
        type: 'object',
        properties: {
          colors: {
            type: 'array',
            items: { type: 'string' },
            description: 'Array of colors to simulate',
          },
          type: {
            type: 'string',
            enum: [
              'protanopia',
              'deuteranopia',
              'tritanopia',
              'protanomaly',
              'deuteranomaly',
              'tritanomaly',
              'monochromacy',
            ],
            description: 'Type of color vision deficiency to simulate',
          },
          severity: {
            type: 'number',
            minimum: 0,
            maximum: 100,
            description: 'Severity percentage (0-100, default: 100)',
            default: 100,
          },
        },
        required: ['colors', 'type'],
      },
      handler: async (params: unknown) =>
        simulateColorblindness(params as SimulateColorblindnessParams),
    };
  • Helper function that applies the specific color vision deficiency transformation matrix to a single color.
    function simulateColorVisionDeficiency(
      color: UnifiedColor,
      deficiencyType: SimulateColorblindnessParams['type'],
      severity: number
    ): UnifiedColor {
      const rgb = color.rgb;
    
      // Convert RGB to linear RGB (remove gamma correction)
      const linearR = Math.pow(rgb.r / 255, 2.2);
      const linearG = Math.pow(rgb.g / 255, 2.2);
      const linearB = Math.pow(rgb.b / 255, 2.2);
    
      let transformedR: number, transformedG: number, transformedB: number;
    
      switch (deficiencyType) {
        case 'protanopia':
        case 'protanomaly': {
          const result = applyMatrix(
            [linearR, linearG, linearB],
            CVD_MATRICES.protanopia
          );
          transformedR = result[0] ?? 0;
          transformedG = result[1] ?? 0;
          transformedB = result[2] ?? 0;
          break;
        }
    
        case 'deuteranopia':
        case 'deuteranomaly': {
          const result = applyMatrix(
            [linearR, linearG, linearB],
            CVD_MATRICES.deuteranopia
          );
          transformedR = result[0] ?? 0;
          transformedG = result[1] ?? 0;
          transformedB = result[2] ?? 0;
          break;
        }
    
        case 'tritanopia':
        case 'tritanomaly': {
          const result = applyMatrix(
            [linearR, linearG, linearB],
            CVD_MATRICES.tritanopia
          );
          transformedR = result[0] ?? 0;
          transformedG = result[1] ?? 0;
          transformedB = result[2] ?? 0;
          break;
        }
    
        case 'monochromacy':
          // Convert to grayscale using luminance formula
          const luminance = 0.2126 * linearR + 0.7152 * linearG + 0.0722 * linearB;
          transformedR = transformedG = transformedB = luminance;
          break;
    
        default:
          transformedR = linearR;
          transformedG = linearG;
          transformedB = linearB;
      }
    
      // Apply severity (blend between original and transformed)
      const severityFactor = severity / 100;
      const blendedR = linearR + (transformedR - linearR) * severityFactor;
      const blendedG = linearG + (transformedG - linearG) * severityFactor;
      const blendedB = linearB + (transformedB - linearB) * severityFactor;
    
      // Convert back to sRGB (apply gamma correction)
      const srgbR = Math.round(
        Math.pow(Math.max(0, Math.min(1, blendedR)), 1 / 2.2) * 255
      );
      const srgbG = Math.round(
        Math.pow(Math.max(0, Math.min(1, blendedG)), 1 / 2.2) * 255
      );
      const srgbB = Math.round(
        Math.pow(Math.max(0, Math.min(1, blendedB)), 1 / 2.2) * 255
      );
    
      return UnifiedColor.fromRgb(srgbR, srgbG, srgbB);
    }
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 states the tool simulates color appearances but doesn't explain what the simulation outputs (e.g., transformed colors, visual previews), whether it's a read-only operation, or any side effects like rate limits or authentication needs. For a tool with no annotations, this is a significant gap in transparency.

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, clear sentence that efficiently conveys the core purpose without unnecessary details. It's front-loaded and wastes no words, making it easy for an agent 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 lack of annotations and output schema, the description is incomplete. It doesn't explain what the tool returns (e.g., modified colors, error messages) or behavioral aspects like performance or limitations. For a tool with 3 parameters and no structured output information, the description should provide more context to guide effective use.

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 100%, so the schema already documents all parameters ('colors', 'type', 'severity') with descriptions and constraints. The description doesn't add any meaning beyond what the schema provides, such as explaining the 'type' enum values or how 'severity' affects the simulation. Baseline 3 is appropriate when the schema does the heavy lifting.

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: 'Simulate how colors appear to users with color vision deficiencies.' It specifies the verb 'simulate' and the resource 'colors,' making it easy to understand. However, it doesn't explicitly differentiate from sibling tools like 'check_contrast' or 'optimize_for_accessibility,' which are related to color accessibility but serve 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?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention sibling tools or contexts where this simulation is preferred over other color analysis tools, such as 'analyze_color' or 'check_contrast.' This lack of usage context leaves the agent to infer based on tool names alone.

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