Skip to main content
Glama

check_contrast

Verify color contrast ratios between foreground and background colors to meet WCAG accessibility standards for web and app design.

Instructions

Check color contrast compliance with WCAG accessibility standards

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
foregroundYesForeground color (typically text color)
backgroundYesBackground color
text_sizeNoText size category for WCAG compliancenormal
standardNoAccessibility standard to check againstWCAG_AA

Implementation Reference

  • Core handler function that executes the check_contrast tool logic: validates parameters, parses colors, computes contrast ratio using ColorAnalyzer, generates recommendations and alternative color combinations, and returns formatted response.
    export async function checkContrast(
      params: CheckContrastParams
    ): Promise<ToolResponse | ErrorResponse> {
      const startTime = Date.now();
    
      try {
        // Validate required parameters
        if (!params.foreground) {
          return createErrorResponse(
            'check_contrast',
            'MISSING_PARAMETER',
            'Foreground color parameter is required',
            Date.now() - startTime,
            {
              details: { parameter: 'foreground' },
              suggestions: ['Provide a foreground color in any supported format'],
            }
          );
        }
    
        if (!params.background) {
          return createErrorResponse(
            'check_contrast',
            'MISSING_PARAMETER',
            'Background color parameter is required',
            Date.now() - startTime,
            {
              details: { parameter: 'background' },
              suggestions: ['Provide a background color in any supported format'],
            }
          );
        }
    
        // Validate color inputs
        const fgValidation = validateColorInput(params.foreground);
        if (!fgValidation.isValid) {
          return createErrorResponse(
            'check_contrast',
            'INVALID_FOREGROUND_COLOR',
            `Invalid foreground color format: ${params.foreground}`,
            Date.now() - startTime,
            {
              details: { provided: params.foreground, error: fgValidation.error },
              suggestions: [
                'Use a valid color format like #FF0000 or rgb(255, 0, 0)',
              ],
            }
          );
        }
    
        const bgValidation = validateColorInput(params.background);
        if (!bgValidation.isValid) {
          return createErrorResponse(
            'check_contrast',
            'INVALID_BACKGROUND_COLOR',
            `Invalid background color format: ${params.background}`,
            Date.now() - startTime,
            {
              details: { provided: params.background, error: bgValidation.error },
              suggestions: [
                'Use a valid color format like #FFFFFF or rgb(255, 255, 255)',
              ],
            }
          );
        }
    
        // Parse colors
        const foregroundColor = new UnifiedColor(params.foreground);
        const backgroundColor = new UnifiedColor(params.background);
    
        // Set defaults
        const textSize = params.text_size || 'normal';
        const standard = params.standard || 'WCAG_AA';
    
        // Check contrast
        const contrastResult = ColorAnalyzer.checkContrast(
          foregroundColor,
          backgroundColor,
          textSize,
          standard
        );
    
        // Generate recommendations
        const recommendations: string[] = [];
    
        if (!contrastResult.passes) {
          recommendations.push(
            'This color combination does not meet accessibility standards'
          );
    
          if (contrastResult.ratio < 3.0) {
            recommendations.push(
              'Consider using colors with more contrast difference'
            );
          }
    
          // Suggest adjustments
          if (
            foregroundColor.metadata?.brightness &&
            backgroundColor.metadata?.brightness
          ) {
            const fgBrightness = foregroundColor.metadata.brightness;
            const bgBrightness = backgroundColor.metadata.brightness;
    
            if (Math.abs(fgBrightness - bgBrightness) < 100) {
              if (fgBrightness > 127) {
                recommendations.push('Try using a darker foreground color');
              } else {
                recommendations.push('Try using a lighter foreground color');
              }
    
              if (bgBrightness > 127) {
                recommendations.push('Try using a darker background color');
              } else {
                recommendations.push('Try using a lighter background color');
              }
            }
          }
        } else {
          if (contrastResult.wcag_aaa) {
            recommendations.push('Excellent contrast - meets AAA standards');
          } else {
            recommendations.push('Good contrast - meets AA standards');
          }
        }
    
        // Generate alternative combinations
        const alternativeCombinations = await generateAlternatives(
          foregroundColor,
          backgroundColor,
          textSize,
          contrastResult.ratio,
          standard
        );
    
        // Prepare response
        const responseData: CheckContrastResponse = {
          foreground: params.foreground,
          background: params.background,
          contrast_ratio: contrastResult.ratio,
          text_size: textSize,
          standard,
          compliance: (() => {
            const compliance: CheckContrastResponse['compliance'] = {
              wcag_aa: contrastResult.wcag_aa,
              wcag_aaa: contrastResult.wcag_aaa,
              passes: contrastResult.passes,
            };
    
            if (standard === 'APCA') {
              compliance.apca_passes = contrastResult.passes;
            }
    
            return compliance;
          })(),
          recommendations,
          alternative_combinations: alternativeCombinations,
        };
    
        if (contrastResult.apca_score !== undefined) {
          responseData.apca_score = contrastResult.apca_score;
        }
    
        const executionTime = Date.now() - startTime;
    
        // Generate accessibility notes
        const accessibilityNotes: string[] = [];
        if (!contrastResult.wcag_aa) {
          accessibilityNotes.push(
            `Contrast ratio ${contrastResult.ratio}:1 does not meet WCAG AA standards`
          );
        }
        if (contrastResult.wcag_aaa) {
          accessibilityNotes.push(
            `Excellent contrast ratio ${contrastResult.ratio}:1 meets WCAG AAA standards`
          );
        }
    
        return createSuccessResponse(
          'check_contrast',
          responseData,
          executionTime,
          {
            colorSpaceUsed: 'sRGB',
            accessibilityNotes: accessibilityNotes,
            recommendations: recommendations.slice(0, 5),
          }
        );
      } catch (error) {
        const executionTime = Date.now() - startTime;
        return createErrorResponse(
          'check_contrast',
          'CONTRAST_CHECK_ERROR',
          `Failed to check contrast: ${error instanceof Error ? error.message : 'Unknown error'}`,
          executionTime,
          {
            details: {
              foreground: params.foreground,
              background: params.background,
            },
            suggestions: [
              'Check that both colors are in valid formats',
              'Try different color formats',
            ],
          }
        );
      }
    }
  • TypeScript interfaces defining input parameters and output response structure for the check_contrast tool.
    export interface CheckContrastParams {
      foreground: string;
      background: string;
      text_size?: 'normal' | 'large';
      standard?: 'WCAG_AA' | 'WCAG_AAA' | 'APCA';
    }
    
    export interface CheckContrastResponse {
      foreground: string;
      background: string;
      contrast_ratio: number;
      apca_score?: number;
      text_size: 'normal' | 'large';
      standard: string;
      compliance: {
        wcag_aa: boolean;
        wcag_aaa: boolean;
        apca_passes?: boolean;
        passes: boolean;
      };
      recommendations: string[];
      alternative_combinations?:
        | {
            foreground_adjustments: Array<{
              color: string;
              contrast_ratio: number;
              apca_score?: number;
              passes: boolean;
            }>;
            background_adjustments: Array<{
              color: string;
              contrast_ratio: number;
              apca_score?: number;
              passes: boolean;
            }>;
          }
        | undefined;
    }
  • Import of checkContrastTool and registration with the central ToolRegistry singleton.
    import { checkContrastTool } from './check-contrast';
    
    // Import and register accessibility tools
    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);
  • Tool definition object with name, description, parameters schema, and handler wrapper that is exported for registration.
    export const checkContrastTool = {
      name: 'check_contrast',
      description:
        'Check color contrast compliance with WCAG accessibility standards',
      parameters: {
        type: 'object',
        properties: {
          foreground: {
            type: 'string',
            description: 'Foreground color (typically text color)',
          },
          background: {
            type: 'string',
            description: 'Background color',
          },
          text_size: {
            type: 'string',
            enum: ['normal', 'large'],
            description: 'Text size category for WCAG compliance',
            default: 'normal',
          },
          standard: {
            type: 'string',
            enum: ['WCAG_AA', 'WCAG_AAA', 'APCA'],
            description: 'Accessibility standard to check against',
            default: 'WCAG_AA',
          },
        },
        required: ['foreground', 'background'],
      },
      handler: async (params: unknown) =>
        checkContrast(params as CheckContrastParams),
    };
  • Core helper function in ColorAnalyzer that performs the actual contrast ratio calculation between two colors using WCAG formula and APCA support.
    static checkContrast(
      foreground: UnifiedColor,
      background: UnifiedColor,
      textSize: 'normal' | 'large' = 'normal',
      standard: 'WCAG_AA' | 'WCAG_AAA' | 'APCA' = 'WCAG_AA'
    ): {
      ratio: number;
      wcag_aa: boolean;
      wcag_aaa: boolean;
      apca_score?: number;
      passes: boolean;
    } {
      const fgLuminance = this.calculateRelativeLuminance(foreground.rgb);
      const bgLuminance = this.calculateRelativeLuminance(background.rgb);
    
      const ratio =
        (Math.max(fgLuminance, bgLuminance) + 0.05) /
        (Math.min(fgLuminance, bgLuminance) + 0.05);
    
      const aaThreshold = textSize === 'large' ? 3.0 : 4.5;
      const aaaThreshold = textSize === 'large' ? 4.5 : 7.0;
    
      const wcagAA = ratio >= aaThreshold;
      const wcagAAA = ratio >= aaaThreshold;
    
      let passes = wcagAA;
      let apcaScore: number | undefined;
    
      // Calculate APCA score if requested
      if (standard === 'APCA') {
        apcaScore = this.calculateAPCA(foreground, background);
        // APCA passing criteria (simplified - actual APCA has more complex rules)
        const apcaThreshold = textSize === 'large' ? 60 : 75;
        passes = Math.abs(apcaScore) >= apcaThreshold;
      } else if (standard === 'WCAG_AAA') {
        passes = wcagAAA;
      }
    
      const result: {
        ratio: number;
        wcag_aa: boolean;
        wcag_aaa: boolean;
        apca_score?: number;
        passes: boolean;
      } = {
        ratio: Math.round(ratio * 100) / 100,
        wcag_aa: wcagAA,
        wcag_aaa: wcagAAA,
        passes,
      };
    
      if (apcaScore !== undefined) {
        result.apca_score = apcaScore;
      }
    
      return result;
    }

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