Skip to main content
Glama

generateImage

Create images from text descriptions using AI models, with options to customize dimensions, apply content filtering, and save files automatically.

Instructions

Generate an image, return the base64-encoded data, and save to a file by default. User-configured settings in MCP config will be used as defaults unless specifically overridden.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
promptYesThe text description of the image to generate
modelNoModel name to use for generation (default: user config or "flux"). Use listImageModels to see all available models
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: "./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

  • Core handler function that generates an image: constructs Pollinations API URL via generateImageUrl, fetches image data, converts to base64, saves to unique file in output directory, returns base64 data and metadata.
    export async function generateImage(prompt, model = 'flux', 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');
      }
    
      // First, generate the image URL
      const urlResult = await generateImageUrl(prompt, model, seed, width, height, enhance, safe, authConfig);
    
      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(urlResult.imageUrl, fetchOptions);
    
        if (!response.ok) {
          throw new Error(`Failed to generate 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: urlResult.prompt,
            width: urlResult.width,
            height: urlResult.height,
            model: urlResult.model,
            seed: urlResult.seed,
            enhance: urlResult.enhance,
            private: urlResult.private,
            nologo: urlResult.nologo,
            safe: urlResult.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 });
        }
    
        // Validate the file format
        const validFormats = ['png', 'jpeg', 'jpg', 'webp'];
        if (!validFormats.includes(format)) {
          warn(`Invalid format '${format}', defaulting to 'png'`);
        }
        const extension = validFormats.includes(format) ? format : 'png';
    
        // Generate a file name if not provided or ensure it's unique
        let baseFileName = fileName;
        if (!baseFileName) {
          // Create a safe filename from the prompt (first 20 chars, alphanumeric only)
          const safePrompt = prompt.slice(0, 20).replace(/[^a-z0-9]/gi, '_').toLowerCase();
          const timestamp = Date.now();
          // Add a random component to ensure uniqueness
          const randomSuffix = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
          baseFileName = `${safePrompt}_${timestamp}_${randomSuffix}`;
        }
    
        // Ensure the filename is unique to prevent overwriting
        let fileNameWithSuffix = baseFileName;
        let filePath = path.join(outputPath, `${fileNameWithSuffix}.${extension}`);
        let counter = 1;
    
        // If the file already exists, add a numeric suffix
        while (fs.existsSync(filePath)) {
          fileNameWithSuffix = `${baseFileName}_${counter}`;
          filePath = path.join(outputPath, `${fileNameWithSuffix}.${extension}`);
          counter++;
        }
    
        // Save the image to the file
        fs.writeFileSync(filePath, Buffer.from(base64Data, 'base64'));
    
        // Add the file path to the result
        result.filePath = filePath;
    
        return result;
      } catch (error) {
        log('Error generating image:', error);
        throw error;
      }
    }
  • Input schema validation and description for the generateImage MCP tool.
     * Schema for the generateImage tool
     */
    export const generateImageSchema = {
      name: 'generateImage',
      description: 'Generate an image, return the base64-encoded data, and save to a file by default. 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 the image to generate'
          },
          model: {
            type: 'string',
            description: 'Model name to use for generation (default: user config or "flux"). Use listImageModels to see all available models'
          },
          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: "./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']
      }
    };
  • MCP server registration: responds to ListToolsRequest with all tool schemas, including generateImageSchema via getAllToolSchemas()
    server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: getAllToolSchemas()
    }));
  • MCP-specific tool call handler for generateImage: applies default configs, calls service function, formats MCP response with image artifact and text summary including file path.
    } else if (name === 'generateImage') {
      try {
        const { prompt, model = defaultConfig.image.model, 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 generateImage(prompt, 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 = `Generated image from prompt: "${prompt}"\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}`;
        }
    
        // Add the text content
        content.push({ type: 'text', text: responseText });
    
        return { content };
      } catch (error) {
        return {
          content: [
            { type: 'text', text: `Error generating image: ${error.message}` }
          ],
          isError: true
        };
      }
    } else if (name === 'respondAudio') {
  • src/schemas.js:32-44 (registration)
    Central registry function that includes generateImageSchema in the list of all MCP tools returned for ListTools.
    export function getAllToolSchemas() {
      return [
        generateImageUrlSchema,
        generateImageSchema,
        editImageSchema,
        generateImageFromReferenceSchema,
        listImageModelsSchema,
        respondAudioSchema,
        listAudioVoicesSchema,
        respondTextSchema,
        listTextModelsSchema
      ];
    }
Behavior3/5

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

With no annotations provided, the description carries full burden. It discloses key behaviors: generates an image, returns base64-encoded data, saves to a file by default, and uses config defaults. However, it lacks details on permissions, rate limits, error handling, or what happens if save fails. For a mutation tool (image generation) with zero annotation coverage, this is a moderate gap.

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?

Two sentences, front-loaded with core purpose. The first sentence covers generation, output format, and file saving. The second adds config default behavior. No wasted words, though it could be slightly more structured (e.g., bullet points for behaviors).

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?

For a 10-parameter tool with no annotations and no output schema, the description is moderately complete. It covers the core action and default behaviors but lacks details on return values (beyond 'base64-encoded data'), error cases, or advanced usage. Given the complexity, it should do more to guide the agent on what to expect.

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 10 parameters thoroughly. The description adds no parameter-specific semantics beyond implying defaults from config. Baseline is 3 when schema does heavy lifting, and the description doesn't compensate with additional insights like parameter interactions or constraints.

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: 'Generate an image, return the base64-encoded data, and save to a file by default.' This specifies the verb (generate), resource (image), and key behaviors (return base64, save to file). It distinguishes from siblings like editImage (modify existing) and generateImageUrl (return URL instead of base64), though not explicitly named. A 5 would require explicit sibling naming.

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 'User-configured settings in MCP config will be used as defaults unless specifically overridden,' suggesting it's for image generation with configurable defaults. However, it doesn't explicitly state when to use this vs. alternatives like generateImageUrl (for URLs) or editImage (for modifications). Guidelines are implied but not explicit.

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