Skip to main content
Glama

export_css

Generate CSS with custom properties, utility classes, and fallbacks for color palettes to implement consistent color systems across web projects.

Instructions

Generate modern CSS with custom properties, utility classes, and fallbacks for color palettes

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Main handler function that validates input parameters, parses colors into UnifiedColor objects, generates CSS using generateCSS helper, and returns a formatted ToolResponse or ErrorResponse.
    async function exportCss(
      params: ExportCssParams
    ): Promise<ToolResponse | ErrorResponse> {
      const startTime = Date.now();
    
      try {
        // Validate parameters
        const { error, value: validatedParams } = exportCssSchema.validate(params);
        if (error) {
          return createErrorResponse(
            'export_css',
            'INVALID_PARAMETERS',
            `Invalid parameters: ${error.details.map(d => d.message).join(', ')}`,
            Date.now() - startTime
          );
        }
    
        // Parse colors
        const colors: UnifiedColor[] = [];
        for (const colorStr of validatedParams.colors) {
          try {
            const color = new UnifiedColor(colorStr);
            colors.push(color);
          } catch {
            return createErrorResponse(
              'export_css',
              'INVALID_COLOR',
              `Invalid color format: ${colorStr}`,
              Date.now() - startTime,
              {
                details: { provided: colorStr },
                suggestions: [
                  'Use hex format like #FF0000',
                  'Use RGB format like rgb(255, 0, 0)',
                  'Use HSL format like hsl(0, 100%, 50%)',
                ],
              }
            );
          }
        }
    
        // Generate CSS
        const css = generateCSS(colors, validatedParams);
    
        // Generate additional export formats
        const exportFormats = {
          css,
          json: {
            colors: colors.map((color, index) => ({
              index: index + 1,
              hex: color.hex,
              rgb: color.rgb,
              hsl: color.hsl,
              semantic_name: validatedParams.semantic_names?.[index],
            })),
            format: validatedParams.format,
            prefix: validatedParams.prefix,
            metadata: {
              total_colors: colors.length,
              includes_fallbacks: validatedParams.include_fallbacks,
              includes_rgb_hsl: validatedParams.include_rgb_hsl,
              minified: validatedParams.minify,
            },
          },
        };
    
        const executionTime = Date.now() - startTime;
    
        return createSuccessResponse(
          'export_css',
          {
            css_output: css,
            format: validatedParams.format,
            color_count: colors.length,
            prefix: validatedParams.prefix,
            includes_fallbacks: validatedParams.include_fallbacks,
            includes_variants: validatedParams.include_rgb_hsl,
            minified: validatedParams.minify,
          },
          executionTime,
          {
            recommendations: [
              'Use CSS custom properties for better maintainability',
              'Consider using semantic color names for better readability',
              'Test fallback values in older browsers if needed',
            ],
            exportFormats,
          }
        );
      } catch (error) {
        return createErrorResponse(
          'export_css',
          'PROCESSING_ERROR',
          error instanceof Error ? error.message : 'Unknown error occurred',
          Date.now() - startTime
        );
      }
    }
  • Joi validation schema defining the input parameters for the export_css tool, including colors array, format options, prefix, fallbacks, and minification settings.
    const exportCssSchema = Joi.object({
      colors: Joi.array()
        .items(Joi.string())
        .min(1)
        .max(100)
        .required()
        .description('Array of colors to export'),
    
      format: Joi.string()
        .valid('variables', 'classes', 'both')
        .default('both')
        .description('CSS format type'),
    
      prefix: Joi.string()
        .pattern(/^[a-zA-Z][a-zA-Z0-9-_]*$/)
        .default('color')
        .description('Prefix for CSS variable and class names'),
    
      include_fallbacks: Joi.boolean()
        .default(true)
        .description('Include fallback values for older browsers'),
    
      include_rgb_hsl: Joi.boolean()
        .default(true)
        .description('Include RGB and HSL variants'),
    
      semantic_names: Joi.array()
        .items(Joi.string())
        .description('Optional semantic names for colors'),
    
      minify: Joi.boolean().default(false).description('Minify the CSS output'),
    });
  • ToolHandler object definition for 'export_css', exporting the tool with name, description, parameters schema, and handler wrapper calling the main exportCss function.
    export const exportCssTool: ToolHandler = {
      name: 'export_css',
      description:
        'Generate modern CSS with custom properties, utility classes, and fallbacks for color palettes',
      parameters: exportCssSchema.describe(),
      handler: async (params: unknown) => exportCss(params as ExportCssParams),
    };
  • Import of exportCssTool and registration into the central toolRegistry singleton, making the tool available for use.
    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);
    toolRegistry.registerTool(optimizeForAccessibilityTool);
    
    // Register palette generation tools
    toolRegistry.registerTool(generateHarmonyPaletteTool);
    
    // Register gradient generation tools
    toolRegistry.registerTool(generateLinearGradientTool);
    toolRegistry.registerTool(generateRadialGradientTool);
    
    // Register visualization tools
    toolRegistry.registerTool(createPaletteHtmlTool);
    toolRegistry.registerTool(createColorWheelHtmlTool);
    toolRegistry.registerTool(createGradientHtmlTool);
    toolRegistry.registerTool(createThemePreviewHtmlTool);
    
    // Register PNG generation tools
    toolRegistry.registerTool(createPalettePngTool);
    toolRegistry.registerTool(createGradientPngTool);
    toolRegistry.registerTool(createColorComparisonPngTool);
    
    // Register theme generation tools
    toolRegistry.registerTool(generateThemeTool);
    toolRegistry.registerTool(generateSemanticColorsTool);
    
    // Register color utility tools
    toolRegistry.registerTool(mixColorsTool);
    toolRegistry.registerTool(generateColorVariationsTool);
    toolRegistry.registerTool(sortColorsTool);
    toolRegistry.registerTool(analyzeColorCollectionTool);
    
    // Register export format tools
    toolRegistry.registerTool(exportCssTool);
  • Helper function that generates the actual CSS string based on validated parameters, supporting variables, classes, fallbacks, variants, and minification.
    function generateCSS(colors: UnifiedColor[], params: ExportCssParams): string {
      const {
        format,
        prefix,
        include_fallbacks,
        include_rgb_hsl,
        semantic_names,
        minify,
      } = params;
    
      let css = '';
      const indent = minify ? '' : '  ';
      const newline = minify ? '' : '\n';
      const space = minify ? '' : ' ';
    
      // Generate CSS custom properties
      if (format === 'variables' || format === 'both') {
        css += `:root${space}{${newline}`;
    
        colors.forEach((color, index) => {
          const name = semantic_names?.[index] || `${prefix}-${index + 1}`;
          const safeName = name.toLowerCase().replace(/[^a-z0-9-]/g, '-');
    
          // Main color variable
          css += `${indent}--${safeName}:${space}${color.hex};${newline}`;
    
          if (include_rgb_hsl) {
            // RGB values (useful for alpha variations)
            css += `${indent}--${safeName}-rgb:${space}${color.rgb.r},${space}${color.rgb.g},${space}${color.rgb.b};${newline}`;
    
            // HSL values (useful for variations)
            css += `${indent}--${safeName}-hsl:${space}${Math.round(color.hsl.h)},${space}${Math.round(color.hsl.s)}%,${space}${Math.round(color.hsl.l)}%;${newline}`;
          }
    
          if (include_fallbacks) {
            // Lighter and darker variants
            const lighterColor = new UnifiedColor(
              `hsl(${color.hsl.h}, ${color.hsl.s}%, ${Math.min(100, color.hsl.l + 10)}%)`
            );
            const darkerColor = new UnifiedColor(
              `hsl(${color.hsl.h}, ${color.hsl.s}%, ${Math.max(0, color.hsl.l - 10)}%)`
            );
    
            css += `${indent}--${safeName}-light:${space}${lighterColor.hex};${newline}`;
            css += `${indent}--${safeName}-dark:${space}${darkerColor.hex};${newline}`;
          }
        });
    
        css += `}${newline}${newline}`;
      }
    
      // Generate utility classes
      if (format === 'classes' || format === 'both') {
        colors.forEach((color, index) => {
          const name = semantic_names?.[index] || `${prefix}-${index + 1}`;
          const safeName = name.toLowerCase().replace(/[^a-z0-9-]/g, '-');
    
          // Background color classes
          css += `.bg-${safeName}${space}{${newline}`;
          css += `${indent}background-color:${space}var(--${safeName},${space}${color.hex});${newline}`;
          css += `}${newline}`;
    
          // Text color classes
          css += `.text-${safeName}${space}{${newline}`;
          css += `${indent}color:${space}var(--${safeName},${space}${color.hex});${newline}`;
          css += `}${newline}`;
    
          // Border color classes
          css += `.border-${safeName}${space}{${newline}`;
          css += `${indent}border-color:${space}var(--${safeName},${space}${color.hex});${newline}`;
          css += `}${newline}`;
    
          if (include_fallbacks) {
            // Hover variants
            css += `.bg-${safeName}:hover${space}{${newline}`;
            css += `${indent}background-color:${space}var(--${safeName}-dark,${space}${color.hex});${newline}`;
            css += `}${newline}`;
          }
    
          if (!minify) {
            css += newline;
          }
        });
      }
    
      return css.trim();
    }
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 generating CSS with specific features, it doesn't describe what the output looks like (e.g., format, structure), whether it's a read-only operation, potential side effects, or performance considerations. For a tool with no annotations and no output schema, this leaves significant gaps in understanding how the tool behaves.

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 front-loads the core purpose without unnecessary words. It directly states what the tool does ('Generate modern CSS') and key features, making it easy to parse. Every element earns its place, with no redundancy or fluff.

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 (7 parameters, no annotations, no output schema), the description is incomplete. It doesn't explain the output format, usage scenarios, or how parameters interact (e.g., the effect of 'minify' or 'semantic_names'). For a tool that generates CSS code, more context is needed to help an agent use it effectively without trial and error.

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 description mentions 'custom properties, utility classes, and fallbacks for color palettes,' which loosely maps to parameters like 'format' and 'include_fallbacks,' but doesn't add meaningful details beyond what the schema provides. With 100% schema description coverage, the baseline is 3, and the description doesn't compensate with additional context or examples for the 7 parameters.

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: 'Generate modern CSS with custom properties, utility classes, and fallbacks for color palettes.' It specifies the verb ('generate'), resource ('CSS'), and key features (custom properties, utility classes, fallbacks). However, it doesn't explicitly differentiate from sibling tools like 'export_scss' or 'export_tailwind' beyond mentioning CSS format.

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 when to choose 'export_css' over sibling tools like 'export_scss' or 'export_json', nor does it specify prerequisites or appropriate contexts for use. The agent must infer usage from the tool name and description 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