Skip to main content
Glama

editImage

Modify existing images using text prompts to add, remove, or change elements like objects and backgrounds. Supports multiple image models and customizable settings for precise editing.

Instructions

Edit or modify an existing image based on a text prompt. User-configured settings in MCP config will be used as defaults unless specifically overridden.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
promptYesThe text description of how to edit the image (e.g., "remove the cat and add a dog", "change background to mountains")
imageUrlYesPublic HTTP(S) URL(s) of the input image(s) to edit. Accepts a string or an array for multiple references (first is most important). Local file paths, file uploads, or base64/data URLs are not supported.
modelNoModel name to use for editing (default: user config or "kontext"). Available: "kontext", "nanobanana", "seedream"
seedNoSeed for reproducible results (default: random)
widthNoWidth of the generated image (default: 1024)
heightNoHeight of the generated image (default: 1024)
enhanceNoWhether to enhance the prompt using an LLM before generating (default: true)
safeNoWhether to apply content filtering (default: false)
outputPathNoDirectory path where to save the image (default: user config or "./mcpollinations-output")
fileNameNoName of the file to save (without extension, default: generated from prompt)
formatNoImage format to save as (png, jpeg, jpg, webp - default: png)

Implementation Reference

  • The primary handler function that executes the editImage tool: validates inputs, builds Pollinations.ai API URL for image editing, fetches and processes the image into base64, saves to output file, and returns structured result with metadata.
    export async function editImage(prompt, imageUrl, model = 'kontext', seed = Math.floor(Math.random() * 1000000), width = 1024, height = 1024, enhance = true, safe = false, outputPath = './mcpollinations-output', fileName = '', format = 'png', authConfig = null) {
      if (!prompt || typeof prompt !== 'string') {
        throw new Error('Prompt is required and must be a string');
      }
    
      if (!imageUrl || (typeof imageUrl !== 'string' && !Array.isArray(imageUrl))) {
        throw new Error('Image URL(s) are required and must be a string or array of strings');
      }
    
      // Support multi-reference images. Prefer repeating the `image` param per URL
      // to avoid comma-encoding ambiguities.
      const imageList = Array.isArray(imageUrl)
        ? imageUrl.filter(Boolean)
        : (typeof imageUrl === 'string' && imageUrl.includes(','))
          ? imageUrl.split(',').map(s => s.trim()).filter(Boolean)
          : [imageUrl];
    
      // Build the query parameters
      const queryParams = new URLSearchParams();
      queryParams.append('model', model);
      for (const u of imageList) {
        queryParams.append('image', u);
      }
      if (seed !== undefined) queryParams.append('seed', seed);
      if (width !== 1024) queryParams.append('width', width);
      if (height !== 1024) queryParams.append('height', height);
    
      // Add enhance parameter if true
      if (enhance) queryParams.append('enhance', 'true');
    
      // Add parameters
      queryParams.append('nologo', 'true'); // Always set nologo to true
      queryParams.append('private', 'true'); // Always set private to true)
      queryParams.append('safe', safe.toString()); // Use the customizable safe parameter
    
      // Construct the URL
      const encodedPrompt = encodeURIComponent(prompt);
      const baseUrl = 'https://image.pollinations.ai';
      let url = `${baseUrl}/prompt/${encodedPrompt}`;
    
      // Add query parameters
      const queryString = queryParams.toString();
      url += `?${queryString}`;
    
      try {
        // Prepare fetch options with optional auth headers
        const fetchOptions = {};
        if (authConfig) {
          fetchOptions.headers = {};
          if (authConfig.token) {
            fetchOptions.headers['Authorization'] = `Bearer ${authConfig.token}`;
          }
          if (authConfig.referrer) {
            fetchOptions.headers['Referer'] = authConfig.referrer;
          }
        }
    
        // Fetch the image from the URL
        const response = await fetch(url, fetchOptions);
    
        if (!response.ok) {
          throw new Error(`Failed to edit image: ${response.statusText}`);
        }
    
        // Get the image data as an ArrayBuffer
        const imageBuffer = await response.arrayBuffer();
    
        // Convert the ArrayBuffer to a base64 string
        const base64Data = Buffer.from(imageBuffer).toString('base64');
    
        // Determine the mime type from the response headers or default to image/jpeg
        const contentType = response.headers.get('content-type') || 'image/jpeg';
    
        // Prepare the result object
        const result = {
          data: base64Data,
          mimeType: contentType,
          metadata: {
            prompt,
            inputImageUrl: imageUrl,
            width,
            height,
            model,
            seed,
            enhance,
            private: true,
            nologo: true,
            safe
          }
        };
    
        // Always save the image to a file
        // Import required modules
        const fs = await import('fs');
        const path = await import('path');
    
        // Create the output directory if it doesn't exist
        if (!fs.existsSync(outputPath)) {
          fs.mkdirSync(outputPath, { recursive: true });
        }
    
        // Generate a filename if not provided
        let finalFileName = fileName;
        if (!finalFileName) {
          // Create a filename from the prompt (first 20 characters) and timestamp
          const sanitizedPrompt = prompt.replace(/[^a-zA-Z0-9]/g, '_').substring(0, 20);
          const timestamp = Date.now();
          const randomSuffix = Math.floor(Math.random() * 1000);
          finalFileName = `edited_${sanitizedPrompt}_${timestamp}_${randomSuffix}`;
        }
    
        // Ensure the filename has the correct extension
        const extension = format.toLowerCase();
        if (!finalFileName.endsWith(`.${extension}`)) {
          finalFileName += `.${extension}`;
        }
    
        // Check if file already exists and add a number suffix if needed
        let finalFilePath = path.join(outputPath, finalFileName);
        let counter = 1;
        while (fs.existsSync(finalFilePath)) {
          const nameWithoutExt = finalFileName.replace(`.${extension}`, '');
          const numberedFileName = `${nameWithoutExt}_${counter}.${extension}`;
          finalFilePath = path.join(outputPath, numberedFileName);
          counter++;
        }
    
        // Write the image data to the file
        fs.writeFileSync(finalFilePath, Buffer.from(base64Data, 'base64'));
    
        // Add the file path to the result
        result.filePath = finalFilePath;
    
        return result;
    
      } catch (error) {
        log('Error editing image:', error);
        throw error;
      }
    }
  • TypeScript/JSON schema defining the input parameters, descriptions, types, and validation rules for the editImage tool.
    export const editImageSchema = {
      name: 'editImage',
      description: 'Edit or modify an existing image based on a text prompt. User-configured settings in MCP config will be used as defaults unless specifically overridden.',
      inputSchema: {
        type: 'object',
        properties: {
          prompt: {
            type: 'string',
            description: 'The text description of how to edit the image (e.g., "remove the cat and add a dog", "change background to mountains")'
          },
          imageUrl: {
            oneOf: [
              { type: 'string' },
              { type: 'array', items: { type: 'string' } }
            ],
            description: 'Public HTTP(S) URL(s) of the input image(s) to edit. Accepts a string or an array for multiple references (first is most important). Local file paths, file uploads, or base64/data URLs are not supported.'
          },
          model: {
            type: 'string',
            description: 'Model name to use for editing (default: user config or "kontext"). Available: "kontext", "nanobanana", "seedream"'
          },
          seed: {
            type: 'number',
            description: 'Seed for reproducible results (default: random)'
          },
          width: {
            type: 'number',
            description: 'Width of the generated image (default: 1024)'
          },
          height: {
            type: 'number',
            description: 'Height of the generated image (default: 1024)'
          },
          enhance: {
            type: 'boolean',
            description: 'Whether to enhance the prompt using an LLM before generating (default: true)'
          },
          safe: {
            type: 'boolean',
            description: 'Whether to apply content filtering (default: false)'
          },
          outputPath: {
            type: 'string',
            description: 'Directory path where to save the image (default: user config or "./mcpollinations-output")'
          },
          fileName: {
            type: 'string',
            description: 'Name of the file to save (without extension, default: generated from prompt)'
          },
          format: {
            type: 'string',
            description: 'Image format to save as (png, jpeg, jpg, webp - default: png)'
          }
        },
        required: ['prompt', 'imageUrl']
      }
    };
  • MCP server CallToolRequestSchema handler that registers and dispatches the 'editImage' tool: matches name, applies defaults from config/env, invokes the handler function, constructs MCP response with image artifact and text summary, handles errors.
    } else if (name === 'editImage') {
      try {
        const { prompt, imageUrl, model = 'kontext', seed, width = defaultConfig.image.width, height = defaultConfig.image.height, enhance = defaultConfig.image.enhance, safe = defaultConfig.image.safe, outputPath = defaultConfig.resources.output_dir, fileName = '', format = 'png' } = args;
        const result = await editImage(prompt, imageUrl, model, seed, width, height, enhance, safe, outputPath, fileName, format, finalAuthConfig);
    
        // Prepare the response content
        const content = [
          {
            type: 'image',
            data: result.data,
            mimeType: result.mimeType
          }
        ];
    
        // Prepare the response text
        let responseText = `Edited image from prompt: "${prompt}"\nInput image: ${imageUrl}\n\nImage metadata: ${JSON.stringify(result.metadata, null, 2)}`;
    
        // Add file path information if the image was saved to a file
        if (result.filePath) {
          responseText += `\n\nImage saved to: ${result.filePath}`;
        }
    
        content.push({
          type: 'text',
          text: responseText
        });
    
        return { content };
      } catch (error) {
        return {
          content: [
            { type: 'text', text: `Error editing image: ${error.message}` }
          ],
          isError: true
        };
      }
  • Central function that collects and returns all tool schemas including editImageSchema for the ListTools MCP endpoint.
    export function getAllToolSchemas() {
      return [
        generateImageUrlSchema,
        generateImageSchema,
        editImageSchema,
        generateImageFromReferenceSchema,
        listImageModelsSchema,
        respondAudioSchema,
        listAudioVoicesSchema,
        respondTextSchema,
        listTextModelsSchema
      ];
    }
  • MCP ListToolsRequestSchema handler that provides the tool list including editImage schema.
    server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: getAllToolSchemas()
    }));
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 reveals minimal behavioral traits. It mentions using MCP config defaults and that the tool edits existing images, but doesn't disclose important behaviors like whether edits are destructive to the original, authentication requirements, rate limits, error conditions, or what the output looks like (only mentions saving to a path).

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 appropriately concise with two clear sentences that front-load the core functionality. Every sentence earns its place by stating the tool's purpose and explaining the default behavior, though it could be slightly more structured with explicit usage guidance.

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?

For a complex image editing tool with 11 parameters, no annotations, and no output schema, the description is insufficient. It doesn't explain what the tool returns (presumably a modified image file), error handling, performance characteristics, or important behavioral constraints beyond the basic editing concept.

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?

With 100% schema description coverage, the baseline is 3. The description adds minimal value beyond the schema, only mentioning that user-configured settings serve as defaults unless overridden, which provides some context about parameter precedence but doesn't significantly enhance understanding of individual parameters.

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 tool's purpose with specific verb ('edit or modify') and resource ('an existing image'), and distinguishes it from sibling tools like 'generateImage' by specifying it works on existing images rather than generating new ones from scratch.

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 like 'generateImageFromReference' or 'generateImage'. It mentions user-configured defaults but offers no explicit when/when-not criteria or sibling tool comparisons.

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/pinkpixel-dev/MCPollinations'

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