Skip to main content
Glama

Place Image

photopea_place_image

Place an image from a URL or local file into the active document. Creates a new layer; optionally set position (x, y) and resize (width, height) while preserving aspect ratio.

Instructions

Place an image into the active document from a URL or local file path. Creates a new layer with the placed image as the active layer. Use width/height to resize while preserving aspect ratio, or x/y to position the layer.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sourceYesURL or absolute local file path of the image to place
xNoX position offset in pixels from the left edge
yNoY position offset in pixels from the top edge
widthNoResize to this width in pixels (preserves aspect ratio if only one dimension is set)
heightNoResize to this height in pixels (preserves aspect ratio if only one dimension is set)
nameNoDisplay name for the placed layer in the layers panel

Implementation Reference

  • The async handler function that executes the photopea_place_image tool logic. It fetches file data (URL or local), loads it into Photopea via bridge.loadFile, duplicates the layer into the target document via copy/paste, optionally renames, resizes, and positions the layer, then confirms success.
    const { source } = params;
    bridge.sendActivity({ type: "activity", id: "", tool: "place_image", summary: `Place image: ${source}` });
    
    // Step 1: Fetch the file data (server-side for both URLs and local files)
    // This avoids Photopea's async app.open(url) which sends "done" before the file loads.
    let fileData: Buffer;
    try {
      fileData = isUrl(source) ? await fetchUrlToBuffer(source) : await readLocalFile(source);
    } catch (err) {
      return { isError: true, content: [{ type: "text" as const, text: (err as Error).message }] };
    }
    
    // Step 2: Send ArrayBuffer to Photopea (opens as new document synchronously)
    const filename = source.split("/").pop() || "image";
    const loadResult = await bridge.loadFile(fileData, filename);
    if (!loadResult.success) return { isError: true, content: [{ type: "text" as const, text: loadResult.error || "Failed to load image" }] };
    
    // Step 3: Duplicate layer into target doc, close source, position in target
    {
      const lines = [
        `var _srcDoc = app.activeDocument;`,
        // Copy merged preserves transparency (unlike flatten/mergeVisible)
        `_srcDoc.selection.selectAll();`,
        `_srcDoc.selection.copy(true);`,
        `_srcDoc.close(2);`,
        `app.activeDocument.paste();`,
      ];
    
      const safeName = params.name ? escapeString(params.name) : "";
      // Helper to extract numeric value from bounds (may be UnitValue objects or raw numbers)
      lines.push(`function _bv(v) { return typeof v === 'object' && v !== null ? v.value || v.L || 0 : v; }`);
      if (safeName) lines.push(`app.activeDocument.activeLayer.name = '${safeName}';`);
      if (params.width || params.height) {
        lines.push(`var _b = app.activeDocument.activeLayer.bounds;`);
        lines.push(`var _cw = _bv(_b[2]) - _bv(_b[0]);`);
        lines.push(`var _ch = _bv(_b[3]) - _bv(_b[1]);`);
        if (params.width && params.height) {
          // Fit within box, preserving aspect ratio
          lines.push(`var _scale = Math.min(${params.width} / _cw, ${params.height} / _ch);`);
        } else if (params.width) {
          lines.push(`var _scale = ${params.width} / _cw;`);
        } else {
          lines.push(`var _scale = ${params.height} / _ch;`);
        }
        lines.push(`if (_cw > 0 && _ch > 0) { app.activeDocument.activeLayer.resize(_scale * 100, _scale * 100); }`);
      }
      if (params.x !== undefined || params.y !== undefined) {
        const xPos = params.x ?? 0;
        const yPos = params.y ?? 0;
        lines.push(`var _b2 = app.activeDocument.activeLayer.bounds;`);
        lines.push(`app.activeDocument.activeLayer.translate(${xPos} - _bv(_b2[0]), ${yPos} - _bv(_b2[1]));`);
      }
      lines.push(`app.echoToOE('ok');`);
      const mergeResult = await bridge.executeScript(lines.join("\n"));
      if (!mergeResult.success) return { isError: true, content: [{ type: "text" as const, text: mergeResult.error || "Failed to place image into document" }] };
    }
    
    return { content: [{ type: "text" as const, text: `Image placed: ${source}` }] };
  • The input schema for photopea_place_image, defining parameters: source (required URL or file path), x/y (optional position offset), width/height (optional resize dimensions), and name (optional layer name).
    inputSchema: {
      source: z.string().describe("URL or absolute local file path of the image to place"),
      x: z.number().optional().describe("X position offset in pixels from the left edge"),
      y: z.number().optional().describe("Y position offset in pixels from the top edge"),
      width: z.number().positive().optional().describe("Resize to this width in pixels (preserves aspect ratio if only one dimension is set)"),
      height: z.number().positive().optional().describe("Resize to this height in pixels (preserves aspect ratio if only one dimension is set)"),
      name: z.string().optional().describe("Display name for the placed layer in the layers panel"),
    },
  • The MCP tool registration using server.registerTool('photopea_place_image', ...) with title, description, inputSchema, annotations, and handler callback.
    server.registerTool("photopea_place_image", {
  • The registerImageTools function which registers all image tools including photopea_place_image. Exported and called from src/server.ts.
    export function registerImageTools(server: McpServer, bridge: PhotopeaBridge): void {
      // 19. photopea_place_image
      server.registerTool("photopea_place_image", {
        title: "Place Image",
        description: "Place an image into the active document from a URL or local file path. Creates a new layer with the placed image as the active layer. Use width/height to resize while preserving aspect ratio, or x/y to position the layer.",
        inputSchema: {
          source: z.string().describe("URL or absolute local file path of the image to place"),
          x: z.number().optional().describe("X position offset in pixels from the left edge"),
          y: z.number().optional().describe("Y position offset in pixels from the top edge"),
          width: z.number().positive().optional().describe("Resize to this width in pixels (preserves aspect ratio if only one dimension is set)"),
          height: z.number().positive().optional().describe("Resize to this height in pixels (preserves aspect ratio if only one dimension is set)"),
          name: z.string().optional().describe("Display name for the placed layer in the layers panel"),
        },
        annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
      }, async (params) => {
        const { source } = params;
        bridge.sendActivity({ type: "activity", id: "", tool: "place_image", summary: `Place image: ${source}` });
    
        // Step 1: Fetch the file data (server-side for both URLs and local files)
        // This avoids Photopea's async app.open(url) which sends "done" before the file loads.
        let fileData: Buffer;
        try {
          fileData = isUrl(source) ? await fetchUrlToBuffer(source) : await readLocalFile(source);
        } catch (err) {
          return { isError: true, content: [{ type: "text" as const, text: (err as Error).message }] };
        }
    
        // Step 2: Send ArrayBuffer to Photopea (opens as new document synchronously)
        const filename = source.split("/").pop() || "image";
        const loadResult = await bridge.loadFile(fileData, filename);
        if (!loadResult.success) return { isError: true, content: [{ type: "text" as const, text: loadResult.error || "Failed to load image" }] };
    
        // Step 3: Duplicate layer into target doc, close source, position in target
        {
          const lines = [
            `var _srcDoc = app.activeDocument;`,
            // Copy merged preserves transparency (unlike flatten/mergeVisible)
            `_srcDoc.selection.selectAll();`,
            `_srcDoc.selection.copy(true);`,
            `_srcDoc.close(2);`,
            `app.activeDocument.paste();`,
          ];
    
          const safeName = params.name ? escapeString(params.name) : "";
          // Helper to extract numeric value from bounds (may be UnitValue objects or raw numbers)
          lines.push(`function _bv(v) { return typeof v === 'object' && v !== null ? v.value || v.L || 0 : v; }`);
          if (safeName) lines.push(`app.activeDocument.activeLayer.name = '${safeName}';`);
          if (params.width || params.height) {
            lines.push(`var _b = app.activeDocument.activeLayer.bounds;`);
            lines.push(`var _cw = _bv(_b[2]) - _bv(_b[0]);`);
            lines.push(`var _ch = _bv(_b[3]) - _bv(_b[1]);`);
            if (params.width && params.height) {
              // Fit within box, preserving aspect ratio
              lines.push(`var _scale = Math.min(${params.width} / _cw, ${params.height} / _ch);`);
            } else if (params.width) {
              lines.push(`var _scale = ${params.width} / _cw;`);
            } else {
              lines.push(`var _scale = ${params.height} / _ch;`);
            }
            lines.push(`if (_cw > 0 && _ch > 0) { app.activeDocument.activeLayer.resize(_scale * 100, _scale * 100); }`);
          }
          if (params.x !== undefined || params.y !== undefined) {
            const xPos = params.x ?? 0;
            const yPos = params.y ?? 0;
            lines.push(`var _b2 = app.activeDocument.activeLayer.bounds;`);
            lines.push(`app.activeDocument.activeLayer.translate(${xPos} - _bv(_b2[0]), ${yPos} - _bv(_b2[1]));`);
          }
          lines.push(`app.echoToOE('ok');`);
          const mergeResult = await bridge.executeScript(lines.join("\n"));
          if (!mergeResult.success) return { isError: true, content: [{ type: "text" as const, text: mergeResult.error || "Failed to place image into document" }] };
        }
    
        return { content: [{ type: "text" as const, text: `Image placed: ${source}` }] };
      });
  • The PlaceImageParams interface defining the typed parameter structure for the place_image operation: source, x, y, width, height, name.
    export interface PlaceImageParams {
      source: string;
      x?: number;
      y?: number;
      width?: number;
      height?: number;
      name?: string;
Behavior4/5

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

The description discloses that it creates a new layer and sets it as active, which is consistent with annotations (readOnlyHint=false). It adds behavioral context beyond the minimal annotations, though it doesn't mention edge cases like invalid sources.

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?

Two concise sentences front-load the core purpose and key parameter usage. No extraneous information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity and complete schema coverage, the description covers the main usage (placement, resize, position). It lacks details on error handling or document requirements, but is adequate for an image placement tool with minimal annotations.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100%. The description adds value by explaining that width/height preserve aspect ratio and x/y position the layer, which supplements the schema's parameter descriptions.

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 it places an image into the active document, creating a new layer. It differentiates from siblings like photopea_add_layer (empty layer) or photopea_open_file (opens as document).

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 gives parameter usage hints but does not explicitly state when to use this tool versus alternatives like photopea_add_layer or photopea_open_file. No when/not-when guidance 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/attalla1/photopea-mcp-server'

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