Skip to main content
Glama

process_folder

Process all images in a folder by converting formats, resizing dimensions, or both operations simultaneously while automatically skipping non-image files.

Instructions

Apply a convert, resize, or convert-and-resize operation to all image files in a folder. Non-image files are automatically skipped.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
folder_pathYesAbsolute path to the folder containing images
operationYesOperation to apply to every image
output_formatNoTarget format (required for convert / convert_and_resize)
qualityNoJPEG/WebP quality (1-100, default 90)
widthNoTarget width in pixels
heightNoTarget height in pixels
presetNoNamed size preset (overrides width/height)
lock_aspect_ratioNoKeep aspect ratio when resizing (default true)
output_folderNoWhere to save the processed files (defaults to the same folder as input)

Implementation Reference

  • The implementation of the 'process_folder' MCP tool. It iterates over files in a given directory, filters them to include only images, and performs the specified image transformation (convert, resize, or convert_and_resize) on each.
    server.tool(
      "process_folder",
      "Apply a convert, resize, or convert-and-resize operation to all image files in a folder. Non-image files are automatically skipped.",
      {
        folder_path: z.string().describe("Absolute path to the folder containing images"),
        operation: z.enum(["convert", "resize", "convert_and_resize"]).describe("Operation to apply to every image"),
        output_format: z.enum(["png", "jpeg", "gif", "webp", "ico"]).optional().describe("Target format (required for convert / convert_and_resize)"),
        quality: z.number().int().min(1).max(100).optional().describe("JPEG/WebP quality (1-100, default 90)"),
        width: z.number().int().positive().optional().describe("Target width in pixels"),
        height: z.number().int().positive().optional().describe("Target height in pixels"),
        preset: z.enum([
          "instagram-square", "instagram-portrait", "instagram-landscape",
          "twitter-post", "twitter-header", "full-hd", "4k",
          "youtube-thumbnail", "favicon",
        ]).optional().describe("Named size preset (overrides width/height)"),
        lock_aspect_ratio: z.boolean().optional().default(true).describe("Keep aspect ratio when resizing (default true)"),
        output_folder: z.string().optional().describe("Where to save the processed files (defaults to the same folder as input)"),
      },
      async ({ folder_path, operation, output_format, quality = 90, width, height, preset, lock_aspect_ratio = true, output_folder }) => {
        try {
          const stat = await fs.stat(folder_path);
          if (!stat.isDirectory()) {
            return { isError: true, content: [{ type: "text", text: `Error: ${folder_path} is not a directory.` }] };
          }
    
          const entries = await fs.readdir(folder_path);
          const imageFiles = entries.filter(isImageFile);
    
          if (imageFiles.length === 0) {
            return { content: [{ type: "text", text: JSON.stringify({ success: true, processed: 0, skipped: entries.length, results: [] }) }] };
          }
    
          const outDir = output_folder ?? folder_path;
          if (output_folder) {
            await fs.mkdir(output_folder, { recursive: true });
          }
    
          let targetW = width;
          let targetH = height;
          if (preset) {
            targetW = PRESETS[preset].width;
            targetH = PRESETS[preset].height;
          }
    
          const results = [];
    
          for (const filename of imageFiles) {
            const inputPath = path.join(folder_path, filename);
            try {
              let outPath;
    
              if (operation === "convert") {
                if (!output_format) throw new Error("output_format is required for convert operation");
                const outExt = output_format === "jpeg" ? "jpg" : output_format;
                const base = path.basename(filename, path.extname(filename));
                outPath = path.join(outDir, `${base}.${outExt}`);
    
                if (output_format === "ico") {
                  const icoBuffer = await encodeIco(inputPath);
                  await fs.writeFile(outPath, icoBuffer);
                } else {
                  await sharp(inputPath).toFormat(output_format, { quality }).toFile(outPath);
                }
    
              } else if (operation === "resize") {
                if (!targetW && !targetH) throw new Error("Provide width, height, or a preset for resize operation");
                const ext = path.extname(filename).slice(1).toLowerCase() || "jpg";
                outPath = path.join(outDir, filename);
                const fit = lock_aspect_ratio ? "inside" : "fill";
                await sharp(inputPath).resize(targetW, targetH, { fit }).toFile(outPath);
    
              } else { // convert_and_resize
                if (!output_format) throw new Error("output_format is required for convert_and_resize operation");
                const outExt = output_format === "jpeg" ? "jpg" : output_format;
                const base = path.basename(filename, path.extname(filename));
                outPath = path.join(outDir, `${base}.${outExt}`);
    
                if (output_format === "ico") {
                  const icoBuffer = await encodeIco(inputPath);
                  await fs.writeFile(outPath, icoBuffer);
                } else {
                  let pipeline = sharp(inputPath);
                  if (targetW || targetH) {
                    const fit = lock_aspect_ratio ? "inside" : "fill";
                    pipeline = pipeline.resize(targetW, targetH, { fit });
                  }
                  await pipeline.toFormat(output_format, { quality }).toFile(outPath);
                }
              }
    
              const outStat = await fs.stat(outPath);
              results.push({ file: filename, output_path: outPath, size_bytes: outStat.size, success: true });
            } catch (fileErr) {
              results.push({ file: filename, success: false, error: fileErr.message });
            }
          }
    
          const succeeded = results.filter(r => r.success).length;
          const failed = results.filter(r => !r.success).length;
          return {
            content: [{ type: "text", text: JSON.stringify({
              success: true,
              processed: succeeded,
              failed,
              skipped: entries.length - imageFiles.length,
              results,
            }) }],
          };
        } catch (err) {
          return { isError: true, content: [{ type: "text", text: `Error: ${err.message}` }] };
        }
      }
    );
Behavior2/5

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

With no annotations provided, the description carries full burden but lacks critical behavioral details: it doesn't disclose whether the operation is destructive (e.g., overwrites files), what permissions or authentication are needed, rate limits, error handling, or output behavior. The description only covers the basic operation and file filtering, leaving significant gaps for a tool with 9 parameters and batch processing.

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 and includes a useful clarification about non-image files. Every word earns its place with no redundancy or fluff, making it easy to parse quickly.

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 tool's complexity (9 parameters, batch processing, no output schema, and no annotations), the description is incomplete. It lacks details on behavioral traits (e.g., destructiveness, error handling), output expectations, and how it differs from sibling tools. For a multi-operation batch tool, more context is needed to guide effective use.

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 minimal value beyond the schema by implying the tool processes all images in a folder and skips non-images, but doesn't provide additional context on parameter interactions (e.g., how preset overrides width/height) or usage nuances. 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 specific action ('Apply a convert, resize, or convert-and-resize operation') and target resource ('to all image files in a folder'), with explicit differentiation from siblings by noting it processes entire folders rather than individual images like convert_image or resize_image. The mention that 'Non-image files are automatically skipped' further clarifies scope.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage context by specifying it operates on folders and skips non-image files, but does not explicitly state when to use this tool versus alternatives like convert_image or resize_image for single files, or how it relates to convert_and_resize (which might be a sibling tool for single images). No explicit exclusions or prerequisites are 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/sonic0002/imagic-mcp'

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