Skip to main content
Glama

edit_image

Modify existing image files using text prompts and optional reference images. Edit specific images by providing their file paths to apply changes like style adjustments or element additions.

Instructions

Edit a SPECIFIC existing image file, optionally using additional reference images. Use this when you have the exact file path of an image to modify.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
imagePathYesFull file path to the main image file to edit
promptYesText describing the modifications to make to the existing image
referenceImagesNoOptional array of file paths to additional reference images to use during editing (e.g., for style transfer, adding elements, etc.)

Implementation Reference

  • The primary handler function that performs image editing using the Gemini API. It reads the input image and optional reference images, encodes them to base64, sends to Gemini with the edit prompt, processes the response, saves the output image, and returns MCP-formatted content with the image and status text.
    private async editImage(request: CallToolRequest): Promise<CallToolResult> {
      if (!this.ensureConfigured()) {
        throw new McpError(ErrorCode.InvalidRequest, "Gemini API token not configured. Use configure_gemini_token first.");
      }
    
      const { imagePath, prompt, referenceImages } = request.params.arguments as { 
        imagePath: string; 
        prompt: string; 
        referenceImages?: string[];
      };
      
      try {
        // Prepare the main image
        const imageBuffer = await fs.readFile(imagePath);
        const mimeType = this.getMimeType(imagePath);
        const imageBase64 = imageBuffer.toString('base64');
        
        // Prepare all image parts
        const imageParts: any[] = [
          { 
            inlineData: {
              data: imageBase64,
              mimeType: mimeType,
            }
          }
        ];
        
        // Add reference images if provided
        if (referenceImages && referenceImages.length > 0) {
          for (const refPath of referenceImages) {
            try {
              const refBuffer = await fs.readFile(refPath);
              const refMimeType = this.getMimeType(refPath);
              const refBase64 = refBuffer.toString('base64');
              
              imageParts.push({
                inlineData: {
                  data: refBase64,
                  mimeType: refMimeType,
                }
              });
            } catch (error) {
              // Continue with other images, don't fail the entire operation
              continue;
            }
          }
        }
        
        // Add the text prompt
        imageParts.push({ text: prompt });
        
        // Use new API format with multiple images and text
        const response = await this.genAI!.models.generateContent({
          model: "gemini-2.5-flash-image-preview",
          contents: [
            {
              parts: imageParts
            }
          ],
        });
        
        // Process response
        const content: any[] = [];
        const savedFiles: string[] = [];
        let textContent = "";
        
        // Get appropriate save directory
        const imagesDir = this.getImagesDirectory();
        await fs.mkdir(imagesDir, { recursive: true, mode: 0o755 });
        
        // Extract image from response
        if (response.candidates && response.candidates[0]?.content?.parts) {
          for (const part of response.candidates[0].content.parts) {
            if (part.text) {
              textContent += part.text;
            }
            
            if (part.inlineData) {
              // Save edited image
              const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
              const randomId = Math.random().toString(36).substring(2, 8);
              const fileName = `edited-${timestamp}-${randomId}.png`;
              const filePath = path.join(imagesDir, fileName);
              
              if (part.inlineData.data) {
                const imageBuffer = Buffer.from(part.inlineData.data, 'base64');
                await fs.writeFile(filePath, imageBuffer);
                savedFiles.push(filePath);
                this.lastImagePath = filePath;
              }
              
              // Add to MCP response
              if (part.inlineData.data) {
                content.push({
                  type: "image",
                  data: part.inlineData.data,
                  mimeType: part.inlineData.mimeType || "image/png",
                });
              }
            }
          }
        }
        
        // Build response
        let statusText = `šŸŽØ Image edited with nano-banana!\n\nOriginal: ${imagePath}\nEdit prompt: "${prompt}"`;
        
        if (referenceImages && referenceImages.length > 0) {
          statusText += `\n\nReference images used:\n${referenceImages.map(f => `- ${f}`).join('\n')}`;
        }
        
        if (textContent) {
          statusText += `\n\nDescription: ${textContent}`;
        }
        
        if (savedFiles.length > 0) {
          statusText += `\n\nšŸ“ Edited image saved to:\n${savedFiles.map(f => `- ${f}`).join('\n')}`;
          statusText += `\n\nšŸ’” View the edited image by:`;
          statusText += `\n1. Opening the file at the path above`;
          statusText += `\n2. Clicking on "Called edit_image" in Cursor to expand the MCP call details`;
          statusText += `\n\nšŸ”„ To continue editing, use: continue_editing`;
          statusText += `\nšŸ“‹ To check current image info, use: get_last_image_info`;
        } else {
          statusText += `\n\nNote: No edited image was generated.`;
          statusText += `\n\nšŸ’” Tip: Try running the command again - sometimes the first call needs to warm up the model.`;
        }
        
        content.unshift({
          type: "text",
          text: statusText,
        });
        
        return { content };
        
      } catch (error) {
        throw new McpError(
          ErrorCode.InternalError,
          `Failed to edit image: ${error instanceof Error ? error.message : String(error)}`
        );
      }
    }
  • JSON schema defining the input parameters for the edit_image tool: required imagePath and prompt, optional referenceImages array.
    inputSchema: {
      type: "object",
      properties: {
        imagePath: {
          type: "string",
          description: "Full file path to the main image file to edit",
        },
        prompt: {
          type: "string",
          description: "Text describing the modifications to make to the existing image",
        },
        referenceImages: {
          type: "array",
          items: {
            type: "string"
          },
          description: "Optional array of file paths to additional reference images to use during editing (e.g., for style transfer, adding elements, etc.)",
        },
      },
      required: ["imagePath", "prompt"],
  • src/index.ts:85-109 (registration)
    Tool registration in the ListTools response, defining name, description, and inputSchema for edit_image.
    {
      name: "edit_image",
      description: "Edit a SPECIFIC existing image file, optionally using additional reference images. Use this when you have the exact file path of an image to modify.",
      inputSchema: {
        type: "object",
        properties: {
          imagePath: {
            type: "string",
            description: "Full file path to the main image file to edit",
          },
          prompt: {
            type: "string",
            description: "Text describing the modifications to make to the existing image",
          },
          referenceImages: {
            type: "array",
            items: {
              type: "string"
            },
            description: "Optional array of file paths to additional reference images to use during editing (e.g., for style transfer, adding elements, etc.)",
          },
        },
        required: ["imagePath", "prompt"],
      },
    },
  • src/index.ts:162-163 (registration)
    Dispatch in the CallTool handler switch statement that routes 'edit_image' calls to the editImage method.
    case "edit_image":
      return await this.editImage(request);

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

A3.9/5.0
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 of behavioral disclosure. It mentions the tool edits existing files and uses reference images, but lacks details on permissions, side effects, error handling, or output format. For a mutation tool with zero annotation coverage, this is a moderate gap, though the core action is clear.

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 two concise sentences that are front-loaded with the main purpose and usage guideline. Every word earns its place, with no redundancy or fluff, making it highly efficient and easy to parse.

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 the tool's complexity (editing images with mutations), lack of annotations, and no output schema, the description is adequate but incomplete. It covers the basic purpose and usage but misses behavioral details like what the tool returns or potential side effects, leaving gaps for an AI agent to operate safely.

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, only implying that 'imagePath' must be exact and 'referenceImages' are optional for tasks like style transfer. 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 verb ('Edit') and resource ('a SPECIFIC existing image file'), distinguishing it from sibling tools like 'generate_image' (creates new) and 'continue_editing' (continues previous edits). The specificity about modifying existing files is explicit and well-articulated.

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

Usage Guidelines4/5

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

The description provides clear context for when to use this tool ('when you have the exact file path of an image to modify'), which implicitly distinguishes it from 'generate_image' (for new images) and 'continue_editing' (for ongoing edits). However, it doesn't explicitly mention when NOT to use it or name alternatives, keeping it at a 4.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.