Skip to main content
Glama

create_gradient_html

Generate HTML previews with CSS code display and interactive controls for visualizing gradient designs across multiple shapes and themes.

Instructions

Generate HTML gradient preview visualizations with CSS code display and interactive controls

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Core handler function that validates input parameters, analyzes CSS gradient syntax and accessibility, generates interactive HTML visualization using enhanced HTML generator, handles file output, provides export formats (CSS, SCSS, JSON), and returns comprehensive metadata including performance timings and recommendations.
    async function createGradientHtml(
      params: CreateGradientHtmlParams
    ): Promise<ToolResponse | ErrorResponse> {
      const startTime = Date.now();
    
      try {
        // Validate parameters
        const { error, value } = createGradientHtmlSchema.validate(params);
        if (error) {
          return {
            success: false,
            error: {
              code: 'INVALID_PARAMETERS',
              message: 'Invalid parameters provided',
              details: error.details,
              suggestions: [
                'Ensure gradient_css is a valid CSS gradient string',
                'Check that preview_shapes contains valid shape names',
                'Verify size is an array of two numbers [width, height]',
              ],
            },
            metadata: {
              execution_time: Date.now() - startTime,
              tool: 'create_gradient_html',
              timestamp: new Date().toISOString(),
            },
          };
        }
    
        const validatedParams = value as CreateGradientHtmlParams;
    
        // Validate CSS gradient syntax
        const gradientValidation = validateGradientCSS(
          validatedParams.gradient_css
        );
        if (!gradientValidation.isValid) {
          return {
            success: false,
            error: {
              code: 'INVALID_GRADIENT_CSS',
              message: 'Invalid CSS gradient syntax',
              details: {
                gradient: validatedParams.gradient_css,
                reason: gradientValidation.error,
              },
              suggestions: [
                'Use valid CSS gradient syntax like "linear-gradient(45deg, #ff0000, #0000ff)"',
                'Check for proper color format in gradient stops',
                'Ensure gradient type is supported (linear-gradient, radial-gradient, conic-gradient)',
              ],
            },
            metadata: {
              execution_time: Date.now() - startTime,
              tool: 'create_gradient_html',
              timestamp: new Date().toISOString(),
            },
          };
        }
    
        const accessibilityNotes: string[] = [];
        const recommendations: string[] = [];
    
        // Analyze gradient for accessibility and recommendations
        const gradientAnalysis = analyzeGradient(validatedParams.gradient_css);
    
        if (gradientAnalysis.colorCount > 5) {
          recommendations.push(
            'Consider using fewer colors for smoother gradient transitions'
          );
        }
    
        if (gradientAnalysis.hasLowContrast) {
          accessibilityNotes.push(
            'Some color combinations in the gradient may have low contrast'
          );
        }
    
        if (
          validatedParams.preview_shapes &&
          validatedParams.preview_shapes.length > 4
        ) {
          recommendations.push(
            'Consider using fewer preview shapes for better performance'
          );
        }
    
        // Determine gradient type for metadata
        const gradientType = determineGradientType(validatedParams.gradient_css);
    
        // Prepare visualization data
        const visualizationData: GradientVisualizationData = {
          gradientCSS: validatedParams.gradient_css,
          previewShapes: validatedParams.preview_shapes || ['rectangle'],
          size: validatedParams.size || [400, 300],
          showCSSCode: validatedParams.show_css_code !== false,
          interactiveControls: validatedParams.interactive_controls || false,
          variations: validatedParams.variations || false,
          metadata: {
            title: 'Gradient Preview',
            description: `${gradientType} gradient with ${gradientAnalysis.colorCount} colors`,
            timestamp: new Date().toLocaleString(),
            gradientType,
          },
        };
    
        // Generate enhanced HTML with background controls
        let result: EnhancedVisualizationResult;
    
        try {
          const enhancedOptions: EnhancedHTMLOptions = {
            interactive: true, // Enable interactive features including JavaScript
            backgroundControls: {
              enableToggle: validatedParams.enable_background_controls ?? true,
              enableColorPicker: validatedParams.enable_background_controls ?? true,
              defaultBackground:
                validatedParams.theme === 'dark' ? 'dark' : 'light',
            },
            enableAccessibilityTesting:
              validatedParams.enable_accessibility_testing ?? true,
            includeKeyboardHelp: validatedParams.include_keyboard_help ?? true,
          };
    
          result = await enhancedHTMLGenerator.generateEnhancedGradientHTML(
            visualizationData,
            enhancedOptions
          );
        } catch (htmlError) {
          throw new Error(
            `Failed to generate enhanced HTML: ${htmlError instanceof Error ? htmlError.message : String(htmlError)}`
          );
        }
    
        // Prepare export formats
        const exportFormats: Record<string, string | object> = {};
    
        exportFormats['css'] = generateGradientCSSExport(
          validatedParams.gradient_css,
          gradientType
        );
        exportFormats['scss'] = generateGradientSCSSExport(
          validatedParams.gradient_css,
          gradientType
        );
        exportFormats['json'] = {
          gradient_css: validatedParams.gradient_css,
          gradient_type: gradientType,
          color_count: gradientAnalysis.colorCount,
          preview_shapes: validatedParams.preview_shapes,
          size: validatedParams.size,
          metadata: visualizationData.metadata,
        };
    
        const executionTime = Date.now() - startTime;
    
        // Try to save file using enhanced file output manager
        let visualizationResult;
        try {
          await enhancedFileOutputManager.initialize();
    
          // If we have HTML content, save it using the enhanced file output manager
          if (result.htmlContent) {
            visualizationResult =
              await enhancedFileOutputManager.saveHTMLVisualization(
                result.htmlContent,
                {
                  toolName: 'create_gradient_html',
                  description: `Enhanced gradient visualization (${gradientType})`,
                }
              );
          }
        } catch (fileError) {
          // If file saving fails, we'll fall back to returning HTML content directly
          logger.warn('Failed to save HTML file, falling back to content', {
            error: fileError as Error,
          });
        }
    
        return {
          success: true,
          data: {
            gradient_css: validatedParams.gradient_css,
            gradient_type: gradientType,
            color_count: gradientAnalysis.colorCount,
            preview_shapes: validatedParams.preview_shapes || ['rectangle'],
            size: validatedParams.size || [400, 300],
            has_interactive_controls: validatedParams.interactive_controls || false,
            file_path: result.filePath,
            file_name: result.fileName,
            file_size: result.fileSize,
            background_controls_enabled: result.backgroundControlsEnabled,
            accessibility_features: result.accessibilityFeatures,
          },
          metadata: {
            execution_time: executionTime,
            tool: 'create_gradient_html',
            timestamp: new Date().toISOString(),
            color_space_used: 'sRGB',
            accessibility_notes: accessibilityNotes,
            recommendations: [
              ...recommendations,
              'HTML file saved with interactive background controls',
              'Use Alt+T to toggle background theme',
              'Use Alt+C to open color picker',
            ],
          },
          visualizations: {
            html: result.htmlContent || `File saved: ${result.filePath}`,
            ...(visualizationResult?.html_file && {
              html_file: visualizationResult.html_file,
            }),
          },
          export_formats: exportFormats,
        };
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        const errorStack = error instanceof Error ? error.stack : undefined;
    
        return {
          success: false,
          error: {
            code: 'INTERNAL_ERROR',
            message: `Gradient HTML generation error: ${errorMessage}`,
            details: {
              errorMessage,
              errorStack,
              errorType: error?.constructor?.name || 'Unknown',
            },
            suggestions: [
              'Verify the CSS gradient syntax is correct',
              'Try with simpler gradient definitions',
              'Check if all colors in the gradient are valid',
            ],
          },
          metadata: {
            execution_time: Date.now() - startTime,
            tool: 'create_gradient_html',
            timestamp: new Date().toISOString(),
          },
        };
      }
    }
  • Joi object schema defining all input parameters for the tool: gradient_css (required), preview_shapes, size, show_css_code, interactive_controls, variations, theme, enable_background_controls, enable_accessibility_testing, include_keyboard_help.
    const createGradientHtmlSchema = Joi.object({
      gradient_css: Joi.string().required().description('CSS gradient definition'),
    
      preview_shapes: Joi.array()
        .items(Joi.string().valid('rectangle', 'circle', 'text', 'button', 'card'))
        .default(['rectangle'])
        .description('Preview shapes to show'),
    
      size: Joi.array()
        .items(Joi.number().integer().min(100).max(2000))
        .length(2)
        .default([400, 300])
        .description('Preview size [width, height]'),
    
      show_css_code: Joi.boolean().default(true).description('Display CSS code'),
    
      interactive_controls: Joi.boolean()
        .default(false)
        .description('Enable interactive controls'),
    
      variations: Joi.boolean()
        .default(false)
        .description('Show angle/position variations'),
    
      theme: Joi.string()
        .valid('light', 'dark', 'auto')
        .default('light')
        .description('Color theme for the visualization'),
    
      enable_background_controls: Joi.boolean()
        .default(true)
        .description('Enable interactive background controls'),
    
      enable_accessibility_testing: Joi.boolean()
        .default(true)
        .description('Enable accessibility testing and warnings'),
    
      include_keyboard_help: Joi.boolean()
        .default(true)
        .description('Include keyboard shortcuts help'),
    });
  • Definition and export of the ToolHandler interface implementation for 'create_gradient_html', including name, description, parameters from schema, and handler wrapper calling the main createGradientHtml function.
    export const createGradientHtmlTool: ToolHandler = {
      name: 'create_gradient_html',
      description:
        'Generate HTML gradient preview visualizations with CSS code display and interactive controls',
      parameters: createGradientHtmlSchema.describe(),
      handler: async (params: unknown) =>
        createGradientHtml(params as CreateGradientHtmlParams),
    };
  • Registration of createGradientHtmlTool with the central ToolRegistry singleton instance, making it available for execution.
    toolRegistry.registerTool(createGradientHtmlTool);
  • TypeScript interface defining the CreateGradientHtmlParams type matching the Joi schema for type safety.
    interface CreateGradientHtmlParams {
      gradient_css: string;
      preview_shapes?: string[];
      size?: [number, number];
      show_css_code?: boolean;
      interactive_controls?: boolean;
      variations?: boolean;
      theme?: 'light' | 'dark' | 'auto';
      enable_background_controls?: boolean;
      enable_accessibility_testing?: boolean;
      include_keyboard_help?: boolean;
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. While it mentions 'interactive controls' and 'CSS code display,' it doesn't describe what the tool actually produces (e.g., a complete HTML page, an embeddable component, or raw HTML markup). It also doesn't mention whether this is a read-only visualization tool or if it has any side effects, performance characteristics, or authentication requirements.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that communicates the core functionality. It's appropriately sized for the tool's complexity and gets straight to the point without unnecessary elaboration. However, it could be slightly more structured by separating the visualization aspect from the interactive features for better clarity.

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?

For a tool with 10 parameters and no output schema, the description is somewhat incomplete. While the schema provides excellent parameter documentation, the description doesn't explain what the tool returns (HTML content, a URL, a file?) or how the output should be used. Given the complexity of the tool and the absence of both annotations and output schema, the description should provide more context about the tool's behavior and output format.

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 schema description coverage is 100%, meaning all parameters are well-documented in the schema itself. The description adds minimal value beyond what's already in the schema - it mentions 'CSS code display' which relates to show_css_code, and 'interactive controls' which relates to interactive_controls and enable_background_controls, but doesn't provide additional semantic context about how these parameters work together or their practical implications.

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 ('Generate HTML gradient preview visualizations') and resources involved ('CSS code display and interactive controls'). It distinguishes this tool from sibling tools like create_gradient_png (which outputs PNG) and create_color_wheel_html (which focuses on color wheels rather than gradients).

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 this HTML visualization tool is preferable over create_gradient_png for static images, or how it relates to other gradient tools like generate_linear_gradient or generate_radial_gradient. No context about appropriate use cases or limitations is provided.

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