Skip to main content
Glama

check_color_contrast

Validate color contrast ratios between foreground and background to ensure compliance with WCAG accessibility standards, supporting various color formats and font attributes.

Instructions

Check if a foreground and background color combination meets WCAG contrast requirements

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
backgroundYesBackground color in various formats (e.g., "#FFFFFF", "#FFF", "rgb(255,255,255)", "hsv(0,0%,100%)")
fontSizeNoFont size in pixels
foregroundYesForeground color in various formats (e.g., "#000000", "#000", "rgb(0,0,0)", "hsv(0,0%,0%)")
isBoldNoWhether the text is bold

Implementation Reference

  • The primary handler function for the 'check_color_contrast' tool. It destructures input arguments, parses foreground and background colors using helper functions, calculates the contrast ratio using the WCAG formula, launches a Puppeteer browser to create a test HTML page with the specified styles, runs Axe specifically on the 'color-contrast' rule, extracts results, determines WCAG AA/AAA compliance based on font size and boldness, and returns a detailed JSON response with normalized colors, ratios, and pass/fail status.
    async checkColorContrast(args: any) {
      const { foreground, background, fontSize = 16, isBold = false } = args;
    
      if (!foreground || !background) {
        throw new McpError(
          ErrorCode.InvalidParams,
          'Missing required parameters: foreground and background colors'
        );
      }
    
      let browser;
      try {
        // Parse colors to RGB values
        let fgRgb, bgRgb;
        
        try {
          fgRgb = this.parseColor(foreground);
          bgRgb = this.parseColor(background);
        } catch (error) {
          throw new McpError(
            ErrorCode.InvalidParams,
            `Color parsing error: ${error instanceof Error ? error.message : String(error)}`
          );
        }
        
        // Convert to hex for Axe engine (as that's what it uses internally)
        const fgHex = this.rgbToHex(fgRgb);
        const bgHex = this.rgbToHex(bgRgb);
        
        // Calculate contrast ratio directly
        const directContrastRatio = this.calculateContrastRatio(fgRgb, bgRgb);
    
        browser = await puppeteer.launch({
          headless: true,
          args: ['--no-sandbox', '--disable-setuid-sandbox']
        });
        
        const page = await browser.newPage();
        
        // Create a simple HTML page with the specified colors
        const html = `
          <!DOCTYPE html>
          <html>
            <head>
              <style>
                .test-element {
                  color: ${fgHex};
                  background-color: ${bgHex};
                  font-size: ${fontSize}px;
                  font-weight: ${isBold ? 'bold' : 'normal'};
                  padding: 20px;
                }
              </style>
            </head>
            <body>
              <div class="test-element">Test Text</div>
            </body>
          </html>
        `;
        
        await page.setContent(html);
        
        // Run only the color-contrast rule
        const axe = new AxePuppeteer(page)
          .options({
            runOnly: {
              type: 'rule',
              values: ['color-contrast']
            }
          });
        
        const result = await axe.analyze();
        
        // Check if there are any violations
        const passes = result.violations.length === 0;
        
        // Extract contrast ratio from failure summary text
        let contrastRatio: number | null = directContrastRatio; // Use our calculated ratio as default
        let extractionMethod = 'direct-calculation';
        
        if (result.violations.length > 0 && result.violations[0].nodes.length > 0) {
          const failureSummary = result.violations[0].nodes[0].failureSummary || '';
          
          // Extract contrast ratio from failure summary using regex
          const match = failureSummary.match(/contrast ratio of ([0-9.]+)/);
          if (match && match[1]) {
            contrastRatio = parseFloat(match[1]);
            extractionMethod = 'axe-calculation';
          }
          
          // Additional inspection of violation data
          if (contrastRatio === null) {
            // Log all properties of the first node to see if contrast data is available elsewhere
            const node = result.violations[0].nodes[0];
            
            if (node.any && node.any.length > 0) {
              if (node.any[0].data) {
                if (node.any[0].data.contrastRatio) {
                  contrastRatio = node.any[0].data.contrastRatio;
                  extractionMethod = 'axe-violation-data';
                }
              }
            }
          }
        } else if (result.passes.length > 0 && result.passes[0].nodes.length > 0) {
          // Try to extract from pass data
          const node = result.passes[0].nodes[0];
          if (node.any && node.any.length > 0 && node.any[0].data && node.any[0].data.contrastRatio) {
            contrastRatio = node.any[0].data.contrastRatio;
            extractionMethod = 'axe-pass-data';
          }
        }
        
        // Determine required contrast ratios based on font size
        const isLargeText = (fontSize >= 18) || (fontSize >= 14 && isBold);
        const requiredRatioAA = isLargeText ? 3.0 : 4.5;
        const requiredRatioAAA = isLargeText ? 4.5 : 7.0;
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify({
                originalInput: {
                  foreground: foreground,
                  background: background,
                },
                normalizedColors: {
                  foregroundHex: fgHex,
                  backgroundHex: bgHex,
                  foregroundRgb: `rgb(${fgRgb.r}, ${fgRgb.g}, ${fgRgb.b})`,
                  backgroundRgb: `rgb(${bgRgb.r}, ${bgRgb.g}, ${bgRgb.b})`,
                },
                fontSize,
                isBold,
                contrastRatio,
                calculationMethod: extractionMethod,
                isLargeText,
                passesWCAG2AA: contrastRatio !== null ? contrastRatio >= requiredRatioAA : passes,
                requiredRatioForAA: requiredRatioAA,
                requiredRatioForAAA: requiredRatioAAA,
                passesWCAG2AAA: contrastRatio !== null ? contrastRatio >= requiredRatioAAA : null,
                helpUrl: "https://dequeuniversity.com/rules/axe/4.10/color-contrast"
              }, null, 2),
            },
          ],
        };
      } finally {
        if (browser) {
          await browser.close();
        }
      }
    }
  • The input schema (inputSchema) for the 'check_color_contrast' tool, defining properties for foreground and background colors (strings supporting multiple formats), optional fontSize (number, default 16), and isBold (boolean, default false), with foreground and background required.
    inputSchema: {
      type: 'object',
      properties: {
        foreground: {
          type: 'string',
          description: 'Foreground color in various formats (e.g., "#000000", "#000", "rgb(0,0,0)", "hsv(0,0%,0%)")',
        },
        background: {
          type: 'string',
          description: 'Background color in various formats (e.g., "#FFFFFF", "#FFF", "rgb(255,255,255)", "hsv(0,0%,100%)")',
        },
        fontSize: {
          type: 'number',
          description: 'Font size in pixels',
          default: 16
        },
        isBold: {
          type: 'boolean',
          description: 'Whether the text is bold',
          default: false
        }
      },
      required: ['foreground', 'background'],
    },
  • src/index.ts:100-127 (registration)
    Registration of the 'check_color_contrast' tool in the MCP server's listTools response, including the tool name, description, and full inputSchema.
    {
      name: 'check_color_contrast',
      description: 'Check if a foreground and background color combination meets WCAG contrast requirements',
      inputSchema: {
        type: 'object',
        properties: {
          foreground: {
            type: 'string',
            description: 'Foreground color in various formats (e.g., "#000000", "#000", "rgb(0,0,0)", "hsv(0,0%,0%)")',
          },
          background: {
            type: 'string',
            description: 'Background color in various formats (e.g., "#FFFFFF", "#FFF", "rgb(255,255,255)", "hsv(0,0%,100%)")',
          },
          fontSize: {
            type: 'number',
            description: 'Font size in pixels',
            default: 16
          },
          isBold: {
            type: 'boolean',
            description: 'Whether the text is bold',
            default: false
          }
        },
        required: ['foreground', 'background'],
      },
    },
  • src/index.ts:168-169 (registration)
    Dispatch registration in the CallToolRequestSchema handler's switch statement, routing 'check_color_contrast' calls to the checkColorContrast method.
    case 'check_color_contrast':
      return await this.checkColorContrast(request.params.arguments);
  • Core helper function that calculates the WCAG contrast ratio between two RGB colors using the standard luminance formula and relative luminance calculation.
    private calculateContrastRatio(color1: { r: number, g: number, b: number }, color2: { r: number, g: number, b: number }): number {
      // Calculate luminance for a color
      const luminance = (rgb: { r: number, g: number, b: number }) => {
        const a = [rgb.r, rgb.g, rgb.b].map(v => {
          v /= 255;
          return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
        });
        return a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722;
      };
      
      const l1 = luminance(color1);
      const l2 = luminance(color2);
      
      // Calculate contrast ratio
      const ratio = (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
      
      return parseFloat(ratio.toFixed(2));
    }
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. While it states what the tool does (checking WCAG contrast requirements), it doesn't describe what specific WCAG levels are checked (AA/AAA), whether the tool provides detailed failure reasons, what the return format looks like, or any performance characteristics. For a tool with zero annotation coverage, this represents significant gaps in behavioral 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, efficient sentence that communicates the core purpose without any wasted words. It's appropriately sized for a straightforward validation tool and gets directly to the point without unnecessary elaboration.

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?

Given the tool's moderate complexity (color contrast validation with 4 parameters) and the absence of both annotations and an output schema, the description is minimally complete. It states what the tool does but doesn't provide information about return values, error conditions, or specific WCAG criteria checked. The description would need to do more heavy lifting to compensate for the lack of structured metadata.

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 fully documents all 4 parameters. The description doesn't add any parameter-specific information beyond what's in the schema descriptions. The baseline score of 3 is appropriate when the schema does all the parameter documentation work.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('Check if...meets WCAG contrast requirements') and identifies the resources involved ('foreground and background color combination'). It distinguishes this tool from sibling tools like 'check_aria_attributes' or 'test_html_string' by focusing specifically on color contrast validation rather than broader accessibility testing.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage context (WCAG compliance checking for color combinations) but doesn't explicitly state when to use this tool versus alternatives like 'test_accessibility' or 'get_rules'. No guidance is provided about when NOT to use this tool or about prerequisites for effective use.

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

Related 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/ronantakizawa/a11ymcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server