Skip to main content
Glama
dh1011

Auto Favicon MCP Server

by dh1011

generate_favicon_from_png

Convert a PNG image into a complete favicon set with multiple sizes, ICO files, Apple touch icons, and manifest.json for web application deployment.

Instructions

Generate a complete favicon set from a PNG image file.

Args:
    image_path: Path to the PNG image file.
    output_path: Directory where favicon files will be generated.
Returns:
    A message describing the generated files and output directory.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
image_pathYes
output_pathYes

Implementation Reference

  • The primary handler for the 'generate_favicon_from_png' tool, decorated with @mcp.tool() for registration. It validates input paths, reads the PNG image, invokes the helper to generate favicon files, and returns a success message with file list or error.
    @mcp.tool()
    async def generate_favicon_from_png(image_path: str, output_path: str) -> str:
        """
        Generate a complete favicon set from a PNG image file.
    
        Args:
            image_path: Absolute path to the PNG image file.
            output_path: Absolute path to the directory where favicon files will be generated.
        Returns:
            A message describing the generated files and output directory.
        """
        try:
            # Validate absolute paths
            image_path_obj = validate_absolute_path(image_path, "image_path")
            output_path_obj = validate_absolute_path(output_path, "output_path")
            
            # Check if image file exists
            if not image_path_obj.exists():
                return f"Error: Image file does not exist: {image_path}"
            
            if not image_path_obj.is_file():
                return f"Error: Path is not a file: {image_path}"
            
            # Check if output directory can be created
            try:
                output_path_obj.mkdir(parents=True, exist_ok=True)
            except Exception as e:
                return f"Error: Cannot create output directory {output_path}: {str(e)}"
            
            with open(image_path_obj, 'rb') as f:
                image_data = f.read()
            result = create_favicon_set(image_data, str(output_path_obj))
            return (
                f"Successfully generated favicon set!\n\n"
                f"Output directory: {result['output_directory']}\n"
                f"Generated files:\n" + "\n".join(f"- {f}" for f in result['generated_files'])
            )
        except ValueError as e:
            return f"Error: {str(e)}"
        except Exception as e:
            return f"Error generating favicon: {str(e)}"
  • Key helper function that processes image data to create a full favicon set: PNGs in various sizes, ICO, Apple touch icons, and manifest.json.
    def create_favicon_set(image_data: bytes, output_dir: str) -> Dict[str, Any]:
        """Create a complete favicon set from image data."""
        # Write image data to a temp file
        with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as temp_file:
            temp_file.write(image_data)
            temp_file.flush()
            temp_path = temp_file.name
    
        try:
            with Image.open(temp_path) as img:
                # Convert to RGBA if needed
                if img.mode != 'RGBA':
                    img = img.convert('RGBA')
    
                output_path = Path(output_dir)
                output_path.mkdir(parents=True, exist_ok=True)
                generated_files = []
    
                # Generate PNG favicons
                for size in FAVICON_SIZES:
                    resized = img.resize((size, size), Image.Resampling.LANCZOS)
                    filename = f"favicon-{size}x{size}.png"
                    filepath = output_path / filename
                    resized.save(filepath, "PNG")
                    generated_files.append(str(filepath))
    
                # Generate ICO file
                ico_images = [img.resize((size, size), Image.Resampling.LANCZOS) for size in ICO_SIZES]
                ico_path = output_path / "favicon.ico"
                ico_images[0].save(ico_path, format='ICO', sizes=[(size, size) for size in ICO_SIZES])
                generated_files.append(str(ico_path))
    
                # Generate Apple touch icons
                for size in APPLE_SIZES:
                    resized = img.resize((size, size), Image.Resampling.LANCZOS)
                    filename = f"apple-touch-icon-{size}x{size}.png"
                    filepath = output_path / filename
                    resized.save(filepath, "PNG")
                    generated_files.append(str(filepath))
    
                # Generate manifest.json
                manifest = {
                    "name": "Favicon App",
                    "short_name": "Favicon",
                    "description": "Generated favicon application",
                    "start_url": "/",
                    "display": "standalone",
                    "background_color": "#ffffff",
                    "theme_color": "#000000",
                    "icons": [
                        {
                            "src": f"favicon-{size}x{size}.png",
                            "sizes": f"{size}x{size}",
                            "type": "image/png"
                        } for size in FAVICON_SIZES
                    ]
                }
                manifest_path = output_path / "manifest.json"
                with open(manifest_path, 'w') as f:
                    json.dump(manifest, f, indent=2)
                generated_files.append(str(manifest_path))
    
                return {
                    "generated_files": generated_files,
                    "manifest": manifest,
                    "output_directory": str(output_path)
                }
        finally:
            os.unlink(temp_path)
  • Helper function used by the handler to validate that input paths are absolute.
    def validate_absolute_path(path: str, path_type: str) -> Path:
        """Validate that a path is absolute and exists (for files) or can be created (for directories)."""
        path_obj = Path(path)
        
        if not path_obj.is_absolute():
            raise ValueError(f"{path_type} must be an absolute path: {path}")
        
        return path_obj
  • Initialization of the FastMCP server instance where tools are registered via decorators.
    mcp = FastMCP(name="favicon-generator")
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/dh1011/auto-favicon-mcp'

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