Skip to main content
Glama

merge_images

Combine multiple images into one by arranging them horizontally, vertically, or in a grid layout with customizable spacing and background color.

Instructions

Merge multiple images into a single image by arranging them horizontally, vertically, or in a grid.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
input_pathsYesOrdered list of absolute paths to the images to merge (minimum 2)
layoutNoArrangement: horizontal (side by side), vertical (stacked), or grid (auto columns)horizontal
gapNoGap in pixels between images (default 0)
backgroundNoBackground/gap fill color as hex (default #ffffff)#ffffff
output_pathYesAbsolute path for the output file (format inferred from extension)

Implementation Reference

  • The handler function that performs the logic of merging multiple images based on input parameters (layout, gap, etc.) using the sharp library.
      async ({ input_paths, layout = "horizontal", gap = 0, background = "#ffffff", output_path }) => {
        try {
          // Load metadata for all images
          const metas = await Promise.all(input_paths.map(async (p) => {
            await fs.access(p);
            const meta = await sharp(p).metadata();
            return { path: p, width: meta.width, height: meta.height };
          }));
    
          // Parse background color
          let bg = { r: 255, g: 255, b: 255, alpha: 1 };
          const hex = background.replace('#', '');
          if (hex.length === 6) {
            bg = { r: parseInt(hex.slice(0,2),16), g: parseInt(hex.slice(2,4),16), b: parseInt(hex.slice(4,6),16), alpha: 1 };
          }
    
          let canvasW, canvasH, positions;
    
          if (layout === "horizontal") {
            canvasH = Math.max(...metas.map(m => m.height));
            canvasW = metas.reduce((sum, m) => sum + m.width, 0) + gap * (metas.length - 1);
            positions = [];
            let x = 0;
            for (const m of metas) {
              positions.push({ x, y: Math.floor((canvasH - m.height) / 2) });
              x += m.width + gap;
            }
          } else if (layout === "vertical") {
            canvasW = Math.max(...metas.map(m => m.width));
            canvasH = metas.reduce((sum, m) => sum + m.height, 0) + gap * (metas.length - 1);
            positions = [];
            let y = 0;
            for (const m of metas) {
              positions.push({ x: Math.floor((canvasW - m.width) / 2), y });
              y += m.height + gap;
            }
          } else {
            // grid: auto columns = ceil(sqrt(n))
            const cols = Math.ceil(Math.sqrt(metas.length));
            const rows = Math.ceil(metas.length / cols);
            const cellW = Math.max(...metas.map(m => m.width));
            const cellH = Math.max(...metas.map(m => m.height));
            canvasW = cols * cellW + gap * (cols - 1);
            canvasH = rows * cellH + gap * (rows - 1);
            positions = metas.map((m, i) => {
              const col = i % cols;
              const row = Math.floor(i / cols);
              return {
                x: col * (cellW + gap) + Math.floor((cellW - m.width) / 2),
                y: row * (cellH + gap) + Math.floor((cellH - m.height) / 2),
              };
            });
          }
    
          // Build composite layers
          const composites = await Promise.all(metas.map(async (m, i) => ({
            input: await sharp(m.path).toBuffer(),
            left: positions[i].x,
            top: positions[i].y,
          })));
    
          const outExt = path.extname(output_path).slice(1).toLowerCase() || "png";
          const formatMap = { jpg: "jpeg" };
          const fmt = formatMap[outExt] || outExt;
    
          await sharp({
            create: { width: canvasW, height: canvasH, channels: 4, background: bg },
          })
            .composite(composites)
            .toFormat(fmt)
            .toFile(output_path);
    
          const stat = await fs.stat(output_path);
          return {
            content: [{ type: "text", text: JSON.stringify({ success: true, output_path, width: canvasW, height: canvasH, size_bytes: stat.size }) }],
          };
        } catch (err) {
          return { isError: true, content: [{ type: "text", text: `Error: ${err.message}` }] };
        }
      }
    );
  • index.js:227-236 (registration)
    Registration of the "merge_images" tool with schema definitions for input arguments using Zod.
    server.tool(
      "merge_images",
      "Merge multiple images into a single image by arranging them horizontally, vertically, or in a grid.",
      {
        input_paths: z.array(z.string()).min(2).describe("Ordered list of absolute paths to the images to merge (minimum 2)"),
        layout: z.enum(["horizontal", "vertical", "grid"]).optional().default("horizontal").describe("Arrangement: horizontal (side by side), vertical (stacked), or grid (auto columns)"),
        gap: z.number().int().min(0).optional().default(0).describe("Gap in pixels between images (default 0)"),
        background: z.string().optional().default("#ffffff").describe("Background/gap fill color as hex (default #ffffff)"),
        output_path: z.string().describe("Absolute path for the output file (format inferred from extension)"),
      },
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. It mentions the merging action and layout options but omits critical details: whether the operation is destructive to input files, authentication requirements, rate limits, error handling, or output specifics (e.g., image quality, format support). For a mutation tool with zero annotation coverage, this is a significant gap.

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 functionality ('Merge multiple images into a single image') and specifies the arrangement methods. There is zero waste, and every word earns its place by clarifying the tool's purpose without redundancy.

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 (5 parameters, mutation operation) and lack of annotations or output schema, the description is incomplete. It fails to address behavioral aspects like file handling, error cases, or output format details, leaving gaps that could hinder an AI agent's correct invocation. For a tool with no structured safety or output information, more context is needed.

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 fully documents all 5 parameters. The description adds no additional meaning beyond what the schema provides—it mentions layout options but not details like 'grid' behavior or path requirements. With high schema coverage, the baseline score of 3 is appropriate, as the description does not compensate but also does not detract.

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: 'Merge multiple images into a single image by arranging them horizontally, vertically, or in a grid.' It specifies the verb ('merge'), resource ('multiple images'), and method ('arranging them'), but does not explicitly differentiate from sibling tools like 'convert_and_resize' or 'resize_image', which focus on transformation rather than composition.

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 lacks context about prerequisites (e.g., image formats supported), exclusions, or comparisons to sibling tools like 'process_folder' for batch operations. Usage is implied only by the tool's name and description.

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