Skip to main content
Glama

gemini_edit_image

Modify existing images using text prompts while maintaining style consistency through session history and reference images. Supports aspect ratio adjustments and real-world reference grounding.

Instructions

Edit or modify existing images based on prompts. Supports session history references ('last' or 'history:N') and image consistency features.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
image_pathYesPath to the original image. Use 'last' for most recent generated image, or 'history:N' (e.g., 'history:0') to reference by index
edit_promptYesInstructions for how to edit the image
aspect_ratioNoAspect ratio for the edited image. Overrides session setting if provided.
output_pathNoOptional output path. If not provided, saves to ~/Documents/nanobanana_generated/
conversation_idNoSession ID for accessing image history and maintaining consistency
reference_imagesNoAdditional reference images for style consistency (max 10). Supports file paths, 'last', or 'history:N' references.
enable_google_searchNoEnable Google Search for real-world reference grounding

Implementation Reference

  • The handler for the gemini_edit_image tool, which processes the input arguments, validates the image paths (including history), prepares the parts for the Gemini API, and calls the API to generate the edited image.
          case "gemini_edit_image": {
            const {
              image_path,
              edit_prompt,
              aspect_ratio,
              output_path,
              conversation_id = "default",
              reference_images = [],
            } = args as any;
    
            try {
              // 대화 컨텍스트 가져오기/생성
              const context = getOrCreateContext(conversation_id);
    
              // Validate directly passed aspect_ratio
              if (aspect_ratio && !VALID_ASPECT_RATIOS.includes(aspect_ratio as AspectRatio)) {
                return {
                  content: [{
                    type: "text",
                    text: `Invalid aspect ratio: ${aspect_ratio}. Valid: ${VALID_ASPECT_RATIOS.join(", ")}`,
                  }],
                  isError: true,
                };
              }
    
              // Priority: direct param > session setting
              const effectiveAspectRatio = aspect_ratio ?? context.aspectRatio;
    
              // aspectRatio 필수 체크 (둘 다 없으면 에러)
              if (effectiveAspectRatio === null) {
                return {
                  content: [{
                    type: "text",
                    text: `Error: Aspect ratio not specified. Either pass aspect_ratio parameter or call set_aspect_ratio first.\nValid ratios: ${VALID_ASPECT_RATIOS.join(", ")}`,
                  }],
                  isError: true,
                };
              }
    
              // 히스토리 참조 확인 ("last", "history:N")
              let resolvedImagePath = image_path;
              let imageBase64: string;
    
              const historyImage = getImageFromHistory(context, image_path);
              if (historyImage) {
                // 히스토리에서 이미지 가져오기
                resolvedImagePath = historyImage.filePath;
                imageBase64 = historyImage.base64Data;
              } else {
                // 파일 경로로 처리
                if (!path.isAbsolute(resolvedImagePath)) {
                  resolvedImagePath = path.join(process.cwd(), resolvedImagePath);
                }
    
                // Check if file exists
                try {
                  await fs.access(resolvedImagePath);
                } catch {
                  // If file doesn't exist in CWD, try in Documents/nanobanana_generated
                  const homeDir = os.homedir();
                  const altPath = path.join(homeDir, 'Documents', 'nanobanana_generated', path.basename(image_path));
                  try {
                    await fs.access(altPath);
                    resolvedImagePath = altPath;
                  } catch {
                    throw new Error(`Image file not found: ${image_path}. Use 'last' or 'history:N' to reference session images.`);
                  }
                }
    
                // Read the original image
                imageBase64 = await imageToBase64(resolvedImagePath);
              }
    
              // contents 구성: 참조 이미지들 + 프롬프트 + 원본 이미지
              const parts: GeminiImageRequestPart[] = [];
              const failedReferenceImages: Array<{ path: string; reason: string }> = [];
    
              // 1. 추가 참조 이미지 (스타일 일관성용, 최대 10개)
              const refImages = (reference_images as string[] || []).slice(0, 10);
              for (const imgRef of refImages) {
                try {
                  // Check for history reference
                  const refHistoryImage = getImageFromHistory(context, imgRef);
                  if (refHistoryImage) {
                    parts.push({
                      inlineData: {
                        mimeType: refHistoryImage.mimeType,
                        data: refHistoryImage.base64Data,
                      },
                    });
                  } else {
                    // File path
                    let refPath = imgRef;
                    if (!path.isAbsolute(refPath)) {
                      refPath = path.join(process.cwd(), refPath);
                    }
                    // Try alternative path if not found
                    try {
                      await fs.access(refPath);
                    } catch {
                      const homeDir = os.homedir();
                      const altPath = path.join(homeDir, 'Documents', 'nanobanana_generated', path.basename(imgRef));
                      await fs.access(altPath);
                      refPath = altPath;
                    }
                    const refBase64 = await imageToBase64(refPath);
                    parts.push({
                      inlineData: {
                        mimeType: "image/png",
                        data: refBase64,
                      },
                    });
                  }
                } catch (error) {
                  failedReferenceImages.push({
                    path: imgRef,
                    reason: error instanceof Error ? error.message : String(error),
                  });
                }
              }
    
              // 2. 편집 프롬프트
              const editingPrompt = `Based on this image, generate a new edited version with the following modifications: ${edit_prompt}
    
    IMPORTANT: Create a completely new image that incorporates the requested changes while maintaining the style and overall composition of the original.`;
              parts.push({ text: editingPrompt });
    
              // 3. 원본 이미지
              parts.push({
                inlineData: {
                  mimeType: "image/png",
                  data: imageBase64,
                },
              });
    
              // REST API 직접 호출 (세션 모델 우선, 없으면 환경 변수 기본값)
              const effectiveModel = context.selectedModel ?? IMAGE_MODEL;
              const apiResponse = await callGeminiImageAPI(parts, effectiveAspectRatio, effectiveModel);
    
              if (apiResponse.error) {
                return {
                  content: [{
                    type: "text",
                    text: `Image editing failed: ${apiResponse.error}\n${apiResponse.textResponse}`,
                  }],
                  isError: true,
                };
              }
    
              if (!apiResponse.imageData) {
                return {
                  content: [{
                    type: "text",
                    text: `Image editing failed.\nOriginal: ${image_path}\nEdit request: "${edit_prompt}"\n` +
                          (apiResponse.textResponse ? `Model response: ${apiResponse.textResponse}` : 'No image returned from model'),
                  }],
                  isError: true,
                };
              }
    
              // Determine output path - ensure PNG extension for edited images
  • The definition of the gemini_edit_image tool, including its input schema and description.
    name: "gemini_edit_image",
    description: "Edit or modify existing images based on prompts. Supports session history references ('last' or 'history:N') and image consistency features.",
    inputSchema: {
      type: "object",
      properties: {
        image_path: {
          type: "string",
          description: "Path to the original image. Use 'last' for most recent generated image, or 'history:N' (e.g., 'history:0') to reference by index",
        },
        edit_prompt: {
          type: "string",
          description: "Instructions for how to edit the image",
        },
        aspect_ratio: {
          type: "string",
          enum: [...VALID_ASPECT_RATIOS],
          description: "Aspect ratio for the edited image. Overrides session setting if provided.",
        },
        output_path: {
          type: "string",
          description: "Optional output path. If not provided, saves to ~/Documents/nanobanana_generated/",
        },
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 that the tool 'supports session history references' and 'image consistency features,' which adds useful context about how it interacts with session state. However, it doesn't disclose critical behavioral traits like whether edits are destructive to the original image, authentication requirements, rate limits, error conditions, or what happens when output_path isn't provided (beyond the schema's description). The description adds some value but leaves significant gaps for a mutation tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/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 ('Edit or modify existing images based on prompts') and adds two key features. There's no wasted verbiage, and every clause adds value. It could be slightly more structured by separating core purpose from features, but it's appropriately sized for the tool's complexity.

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 (7 parameters, mutation operation, no annotations, no output schema), the description is moderately complete. It covers the core purpose and hints at session integration, but it lacks details on behavioral outcomes, error handling, or what the tool returns. Without annotations or output schema, the description should do more to explain the mutation's effects and results, but it provides a basic foundation.

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%, meaning all parameters are documented in the schema itself. The description doesn't add any parameter-specific semantics beyond what's already in the schema (e.g., it doesn't explain how 'edit_prompt' interacts with 'reference_images' or clarify the 'conversation_id' usage). With high schema coverage, the baseline is 3, and the description doesn't compensate with additional insights.

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 as editing or modifying existing images based on prompts, which is a specific verb+resource combination. However, it doesn't explicitly differentiate from sibling tools like 'gemini_generate_image' (which likely creates new images) or 'get_image_history' (which retrieves but doesn't edit). The description mentions session history references and image consistency features, which adds specificity but not explicit sibling differentiation.

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 through mentions of session history references ('last' or 'history:N') and image consistency features, suggesting this tool is for iterative editing within a session. However, it doesn't provide explicit guidance on when to use this tool versus alternatives like 'gemini_generate_image' for new images or 'clear_conversation' for session management. No when-not-to-use scenarios or prerequisites are mentioned.

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/pistachiomatt/nanobanana-mcp'

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