Skip to main content
Glama

generate_semantic_colors

Map base colors to semantic UI roles like primary, secondary, and error while ensuring WCAG accessibility compliance for web, mobile, or desktop applications.

Instructions

Map colors to semantic roles for UI design with accessibility compliance

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
base_paletteYesArray of base colors to map to semantic roles
semantic_rolesNoSemantic roles to generate colors for
contextNoContext for color usageweb
ensure_contrastNoEnsure WCAG contrast compliance
accessibility_levelNoWCAG accessibility level to targetAA

Implementation Reference

  • Core handler function executing the tool logic: validates base palette, generates semantic color mappings for roles like primary/success/error, ensures accessibility compliance, produces reports and recommendations.
    export async function generateSemanticColors(
      params: GenerateSemanticColorsParams
    ): Promise<ToolResponse | ErrorResponse> {
      const startTime = Date.now();
    
      try {
        // Validate required parameters
        if (!params.base_palette || params.base_palette.length === 0) {
          return createErrorResponse(
            'generate_semantic_colors',
            'MISSING_PARAMETER',
            'Base palette parameter is required and must contain at least one color',
            Date.now() - startTime,
            {
              details: { parameter: 'base_palette' },
              suggestions: ['Provide an array of colors in any supported format'],
            }
          );
        }
    
        // Validate all colors in base palette
        const basePalette: UnifiedColor[] = [];
        for (let i = 0; i < params.base_palette.length; i++) {
          const colorStr = params.base_palette[i];
          if (!colorStr) {
            return createErrorResponse(
              'generate_semantic_colors',
              'INVALID_COLOR',
              `Color at index ${i} is undefined`,
              Date.now() - startTime,
              {
                details: { index: i },
                suggestions: ['Ensure all colors in the palette are defined'],
              }
            );
          }
    
          const validation = validateColorInput(colorStr);
          if (!validation.isValid) {
            return createErrorResponse(
              'generate_semantic_colors',
              'INVALID_COLOR',
              `Invalid color at index ${i}: ${colorStr}`,
              Date.now() - startTime,
              {
                details: { index: i, provided: colorStr, error: validation.error },
                suggestions: [
                  'Ensure all colors are in valid formats like #FF0000 or rgb(255, 0, 0)',
                ],
              }
            );
          }
          basePalette.push(new UnifiedColor(colorStr));
        }
    
        // Set defaults
        const semanticRoles = params.semantic_roles || [
          'primary',
          'secondary',
          'success',
          'warning',
          'error',
          'info',
          'neutral',
        ];
        const context = params.context || 'web';
        const ensureContrast = params.ensure_contrast !== false; // Default to true
        const accessibilityLevel = params.accessibility_level || 'AA';
    
        // Generate semantic mapping
        const semanticMapping = await generateSemanticMapping(
          basePalette,
          semanticRoles,
          context,
          ensureContrast,
          accessibilityLevel
        );
    
        // Generate accessibility report
        const accessibilityReport = await generateSemanticAccessibilityReport(
          semanticMapping,
          accessibilityLevel
        );
    
        // Generate usage recommendations
        const usageRecommendations = generateUsageRecommendations(
          semanticMapping,
          context,
          accessibilityReport
        );
    
        // Prepare response
        const responseData: GenerateSemanticColorsResponse = {
          base_palette: params.base_palette,
          context,
          semantic_mapping: semanticMapping,
          accessibility_report: accessibilityReport,
          usage_recommendations: usageRecommendations,
        };
    
        const executionTime = Date.now() - startTime;
    
        // Generate accessibility notes
        const accessibilityNotes: string[] = [];
        if (accessibilityReport.overall_compliance === 'FAIL') {
          accessibilityNotes.push(
            'Some semantic colors do not meet accessibility standards'
          );
        } else if (accessibilityReport.overall_compliance === 'AA') {
          accessibilityNotes.push('Semantic colors meet WCAG AA standards');
        } else {
          accessibilityNotes.push('Semantic colors meet WCAG AAA standards');
        }
    
        if (accessibilityReport.adjustments_made > 0) {
          accessibilityNotes.push(
            `${accessibilityReport.adjustments_made} colors were adjusted for accessibility`
          );
        }
    
        const recommendations: string[] = [];
        if (accessibilityReport.contrast_issues.length > 0) {
          recommendations.push(
            `${accessibilityReport.contrast_issues.length} contrast issues found`
          );
        }
        recommendations.push(...usageRecommendations.slice(0, 3));
    
        return createSuccessResponse(
          'generate_semantic_colors',
          responseData,
          executionTime,
          {
            colorSpaceUsed: 'sRGB',
            accessibilityNotes,
            recommendations: recommendations.slice(0, 5),
          }
        );
      } catch (error) {
        const executionTime = Date.now() - startTime;
        return createErrorResponse(
          'generate_semantic_colors',
          'SEMANTIC_MAPPING_ERROR',
          `Failed to generate semantic colors: ${error instanceof Error ? error.message : 'Unknown error'}`,
          executionTime,
          {
            details: {
              base_palette: params.base_palette,
              context: params.context,
            },
            suggestions: [
              'Check that all colors in the base palette are valid',
              'Ensure the context is supported',
              'Try with different parameters',
            ],
          }
        );
      }
    }
  • TypeScript interface for input parameters including base color palette and optional semantic roles/context.
    export interface GenerateSemanticColorsParams {
      base_palette: string[];
      semantic_roles?: Array<
        | 'primary'
        | 'secondary'
        | 'success'
        | 'warning'
        | 'error'
        | 'info'
        | 'neutral'
      >;
      context?: 'web' | 'mobile' | 'desktop' | 'print';
      ensure_contrast?: boolean;
      accessibility_level?: 'AA' | 'AAA';
    }
  • TypeScript interface for the tool's response structure including semantic mappings and accessibility report.
    export interface GenerateSemanticColorsResponse {
      base_palette: string[];
      context: string;
      semantic_mapping: SemanticColorRole[];
      accessibility_report: {
        overall_compliance: 'AA' | 'AAA' | 'FAIL';
        contrast_issues: Array<{
          role: string;
          color: string;
          issue: string;
          recommendation: string;
        }>;
        adjustments_made: number;
      };
      usage_recommendations: string[];
    }
  • Import statement for the generateSemanticColorsTool.
    import { generateSemanticColorsTool } from './generate-semantic-colors';
  • Registration of the generate_semantic_colors tool in the central tool registry.
    toolRegistry.registerTool(generateSemanticColorsTool);
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 mentions 'accessibility compliance' but doesn't specify what that entails (e.g., WCAG standards, contrast ratios, or error handling). It lacks details on output format, performance, rate limits, or side effects. For a tool with 5 parameters and no annotations, this is insufficient.

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 with zero waste. It's front-loaded with the core purpose and includes key context ('UI design with accessibility compliance'). Every word earns its place, making it highly concise and well-structured.

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 5 parameters, no annotations, and no output schema, the description is moderately complete. It covers the high-level purpose but lacks details on behavior, output, or usage compared to siblings. For a tool with this complexity, more context would be helpful, but it meets minimum viability.

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 thoroughly. The description adds no specific parameter semantics beyond what's in the schema (e.g., it doesn't explain how 'base_palette' maps to 'semantic_roles' or what 'context' affects). Baseline 3 is appropriate as 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: 'Map colors to semantic roles for UI design with accessibility compliance.' It specifies the verb ('map'), resource ('colors to semantic roles'), and domain ('UI design with accessibility compliance'). However, it doesn't explicitly differentiate from sibling tools like 'generate_theme' or 'optimize_for_accessibility', which might have overlapping functionality in color/theme generation.

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 other tools might be more appropriate (e.g., 'generate_theme' for broader theme generation or 'optimize_for_accessibility' for accessibility-focused adjustments). Usage is implied through the description but not explicitly stated.

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