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;
    }
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 compliance checking, it doesn't describe what the tool returns (e.g., pass/fail results, contrast ratios, specific WCAG level details), whether it has side effects, or any rate limits or authentication needs. For a tool with no annotation coverage, this leaves significant gaps in understanding its behavior.

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 directly states the tool's purpose without unnecessary words. It's front-loaded with the core functionality ('check color contrast compliance'), making it easy to parse. Every part of the sentence earns its place by specifying the domain (accessibility) and standard (WCAG).

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 complexity of accessibility checking and the lack of annotations and output schema, the description is incomplete. It doesn't explain what the tool returns (e.g., a compliance status, contrast ratio, or detailed report), which is critical for an agent to use it effectively. Without this, the agent lacks context on how to interpret results or handle errors.

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 input schema has 100% description coverage, clearly documenting all four parameters with enums and defaults. The description adds no additional parameter semantics beyond what's in the schema—it doesn't explain color format expectations (e.g., hex codes, RGB), how 'text_size' affects compliance, or differences between standards like WCAG_AA vs. APCA. With high schema coverage, the baseline score of 3 is appropriate.

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: checking color contrast compliance with WCAG accessibility standards. It specifies the verb ('check') and resource ('color contrast compliance'), making it immediately understandable. However, it doesn't explicitly differentiate from sibling tools like 'optimize_for_accessibility' or 'simulate_colorblindness', 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 'optimize_for_accessibility' (which might adjust colors for compliance) or 'analyze_color' (which might provide broader analysis), leaving the agent with no context for tool selection. The description only states what the tool does, not when it's appropriate.

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