Skip to main content
Glama
mhe8mah

WebP Batch Converter

by mhe8mah

convert_to_webp

Convert multiple PNG, JPG, and JPEG images to WebP format in batches with customizable quality, lossless encoding, and directory scanning.

Instructions

Batch convert images (PNG, JPG, JPEG) to WebP format with customizable options. Recursively scans directories and provides detailed conversion reports.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
srcNoSource directory to scan for images (default: current directory).
qualityNoWebP quality (0-100, default: 75)
losslessNoUse lossless encoding (recommended for PNG images)
overwriteNoReplace original files with WebP versions
threadsNoNumber of concurrent conversions (default: 2)
preserveMetaNoPreserve EXIF and ICC metadata
flatNoOutput all WebP files to specified directory (optional)

Implementation Reference

  • Core batch conversion implementation: finds images recursively, converts them to WebP concurrently using cwebp or sharp fallback, computes statistics including space savings.
    async batchConvert(options: ConvertOptions): Promise<ConvertResult> {
      console.log(chalk.blue(`🔍 Scanning ${options.src} for images...`));
      
      const images = await this.findImages(options.src);
      const limit = pLimit(options.threads);
      
      console.log(chalk.blue(`📁 Found ${images.length} images`));
      console.log(chalk.blue(`🚀 Converting with ${options.threads} threads...`));
      
      const result: ConvertResult = {
        converted: [],
        skipped: [],
        errors: [],
        originalKB: 0,
        webpKB: 0,
        savings: 0
      };
    
      const tasks = images.map(imagePath => 
        limit(async () => {
          const convertResult = await this.convertSingle(imagePath, options);
          
          if (convertResult.success) {
            result.converted.push(imagePath);
            result.originalKB += convertResult.originalSize / 1024;
            result.webpKB += convertResult.webpSize / 1024;
            console.log(chalk.green(`✓ ${basename(imagePath)}`));
          } else {
            result.errors.push({ file: imagePath, error: convertResult.error || 'Unknown error' });
            console.log(chalk.red(`✗ ${basename(imagePath)}: ${convertResult.error}`));
          }
        })
      );
    
      await Promise.all(tasks);
      
      result.savings = result.originalKB > 0 ? 
        Math.round(((result.originalKB - result.webpKB) / result.originalKB) * 100) : 0;
      
      return result;
    }
  • MCP CallToolRequestSchema handler for 'convert_to_webp': parameter validation, defaults, calls WebPConverter.batchConvert, formats success/error response.
    this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
      if (request.params.name !== 'convert_to_webp') {
        throw new Error(`Unknown tool: ${request.params.name}`);
      }
    
      const args = request.params.arguments as any;
      
      try {
        // Validate and set defaults
        const options = {
          src: args.src || '.',
          quality: args.quality || 75,
          lossless: args.lossless || false,
          overwrite: args.overwrite || false,
          threads: args.threads || cpus().length,
          preserveMeta: args.preserveMeta || false,
          flat: args.flat
        };
    
        // Validate quality range
        if (options.quality < 0 || options.quality > 100) {
          throw new Error('Quality must be between 0-100');
        }
    
        // Validate threads
        if (options.threads < 1) {
          throw new Error('Threads must be a positive number');
        }
    
        const result = await this.converter.batchConvert(options);
    
        return {
          content: [
            {
              type: 'text',
              text: `WebP Batch Conversion Complete!\n\n` +
                   `📊 Results:\n` +
                   `✅ Converted: ${result.converted.length} files\n` +
                   `⏭️  Skipped: ${result.skipped.length} files\n` +
                   `❌ Errors: ${result.errors.length} files\n` +
                   `💾 Original size: ${Math.round(result.originalKB)} KB\n` +
                   `🗜️  WebP size: ${Math.round(result.webpKB)} KB\n` +
                   `💰 Space saved: ${result.savings}%\n\n` +
                   `📋 Detailed Report:\n${JSON.stringify(result, null, 2)}`
            }
          ]
        };
      } catch (error) {
        return {
          content: [
            {
              type: 'text',
              text: `❌ Conversion failed: ${error instanceof Error ? error.message : String(error)}`
            }
          ],
          isError: true
        };
      }
    });
  • JSON input schema for the convert_to_webp tool, defining parameters with descriptions, defaults, and constraints.
    inputSchema: {
      type: 'object',
      properties: {
        src: {
          type: 'string',
          description: 'Source directory to scan for images (default: current directory)',
          default: '.'
        },
        quality: {
          type: 'number',
          description: 'WebP quality (0-100, default: 75)',
          minimum: 0,
          maximum: 100,
          default: 75
        },
        lossless: {
          type: 'boolean',
          description: 'Use lossless encoding (recommended for PNG images)',
          default: false
        },
        overwrite: {
          type: 'boolean',
          description: 'Replace original files with WebP versions',
          default: false
        },
        threads: {
          type: 'number',
          description: `Number of concurrent conversions (default: ${cpus().length})`,
          minimum: 1,
          default: cpus().length
        },
        preserveMeta: {
          type: 'boolean',
          description: 'Preserve EXIF and ICC metadata',
          default: false
        },
        flat: {
          type: 'string',
          description: 'Output all WebP files to specified directory (optional)'
        }
      },
      required: []
    }
  • src/server.ts:33-84 (registration)
    Tool registration via ListToolsRequestSchema handler, listing 'convert_to_webp' with description and schema.
    this.server.setRequestHandler(ListToolsRequestSchema, async () => {
      return {
        tools: [
          {
            name: 'convert_to_webp',
            description: 'Batch convert images (PNG, JPG, JPEG) to WebP format with customizable options. Recursively scans directories and provides detailed conversion reports.',
            inputSchema: {
              type: 'object',
              properties: {
                src: {
                  type: 'string',
                  description: 'Source directory to scan for images (default: current directory)',
                  default: '.'
                },
                quality: {
                  type: 'number',
                  description: 'WebP quality (0-100, default: 75)',
                  minimum: 0,
                  maximum: 100,
                  default: 75
                },
                lossless: {
                  type: 'boolean',
                  description: 'Use lossless encoding (recommended for PNG images)',
                  default: false
                },
                overwrite: {
                  type: 'boolean',
                  description: 'Replace original files with WebP versions',
                  default: false
                },
                threads: {
                  type: 'number',
                  description: `Number of concurrent conversions (default: ${cpus().length})`,
                  minimum: 1,
                  default: cpus().length
                },
                preserveMeta: {
                  type: 'boolean',
                  description: 'Preserve EXIF and ICC metadata',
                  default: false
                },
                flat: {
                  type: 'string',
                  description: 'Output all WebP files to specified directory (optional)'
                }
              },
              required: []
            }
          }
        ]
      };
  • TypeScript interfaces defining ConvertOptions input and ConvertResult output for the converter class.
    export interface ConvertOptions {
      src: string;
      quality: number;
      lossless: boolean;
      overwrite: boolean;
      threads: number;
      preserveMeta: boolean;
      flat?: string;
    }
    
    export interface ConvertResult {
      converted: string[];
      skipped: string[];
      errors: Array<{ file: string; error: string }>;
      originalKB: number;
      webpKB: number;
      savings: number;
    }
Behavior3/5

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

With no annotations provided, the description carries the full burden. It discloses key behavioral traits like batch processing, recursive directory scanning, and detailed reports, but lacks information on permissions, error handling, rate limits, or what the reports contain. It's adequate but has gaps.

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 front-loaded with core functionality and efficiently uses two sentences with zero waste. Every phrase ('batch convert', 'customizable options', 'recursively scans', 'detailed conversion reports') adds value without redundancy.

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 no annotations, no output schema, and a 7-parameter tool with high schema coverage, the description is moderately complete. It covers the tool's scope and key behaviors but lacks details on outputs (reports), error cases, or advanced usage, leaving room for improvement.

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 additional meaning beyond implying batch and recursive behavior, which is partially covered by parameters like 'src' and 'threads'. 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.

Purpose5/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 with specific verbs ('batch convert', 'recursively scans') and resources ('images (PNG, JPG, JPEG) to WebP format'), and distinguishes it by mentioning batch processing and directory scanning. No siblings exist, but it's still specific.

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 (e.g., single-file conversion tools or other formats). It mentions 'customizable options' but doesn't specify scenarios or exclusions, leaving usage context implied at best.

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/mhe8mah/webp-batch-mcp'

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