Skip to main content
Glama

generateImage

Generates an image from a text description, with options to customize model, size, seed, and enhancement. Saves the image to a file and returns base64 data.

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

  • The main handler for the generateImage tool. Generates an image from a text prompt, fetches the image data, converts to base64, and saves to a file by default. Returns base64 data, mime type, metadata, and file path.
    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;
      }
    }
  • Schema definition for the generateImage tool. Defines the name, description, and inputSchema with parameters: prompt (required), model, seed, width, height, enhance, safe, outputPath, fileName, and format.
    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']
      }
    };
  • src/index.js:1-29 (registration)
    Central registration/export of the generateImage function. Imports from imageService.js and re-exports it as part of the public API.
    /**
     * Pollinations API Client
     *
     * A simple client for the Pollinations APIs that follows the thin proxy design principle
     */
    
    // Import services
    import { generateImageUrl, generateImage, editImage, generateImageFromReference, listImageModels } from './services/imageService.js';
    import { respondAudio, listAudioVoices } from './services/audioService.js';
    import { respondText, listTextModels } from './services/textService.js';
    
    
    // Export all service functions
    export {
      // Image services
      generateImageUrl,
      generateImage,
      editImage,
      generateImageFromReference,
      listImageModels,
    
      // Audio services
      respondAudio,
      listAudioVoices,
    
      // Text services
      respondText,
      listTextModels,
    };
  • src/schemas.js:1-44 (registration)
    Central registration of the generateImageSchema. Imports from imageSchema.js, re-exports it, and includes it in the getAllToolSchemas array for tool registration.
    /**
     * Central export for all schema definitions
     */
    
    import { generateImageUrlSchema, generateImageSchema, editImageSchema, generateImageFromReferenceSchema, listImageModelsSchema } from './services/imageSchema.js';
    import { respondAudioSchema, listAudioVoicesSchema } from './services/audioSchema.js';
    import { respondTextSchema, listTextModelsSchema } from './services/textSchema.js';
    
    
    // Re-export all schemas
    export {
      // Image schemas
      generateImageUrlSchema,
      generateImageSchema,
      editImageSchema,
      generateImageFromReferenceSchema,
      listImageModelsSchema,
    
      // Audio schemas
      respondAudioSchema,
      listAudioVoicesSchema,
    
      // Text schemas
      respondTextSchema,
      listTextModelsSchema
    };
    
    /**
     * Get all tool schemas as an array
     * @returns {Array} Array of all tool schemas
     */
    export function getAllToolSchemas() {
      return [
        generateImageUrlSchema,
        generateImageSchema,
        editImageSchema,
        generateImageFromReferenceSchema,
        listImageModelsSchema,
        respondAudioSchema,
        listAudioVoicesSchema,
        respondTextSchema,
        listTextModelsSchema
      ];
    }
  • Helper function generateImageUrl called by generateImage. Builds the Pollinations API URL with query parameters and returns metadata including the image URL.
    export async function generateImageUrl(prompt, model = 'flux', seed = Math.floor(Math.random() * 1000000), width = 1024, height = 1024, enhance = true, safe = false, authConfig = null) {
      if (!prompt || typeof prompt !== 'string') {
        throw new Error('Prompt is required and must be a string');
      }
    
      // Parameters are now directly passed as function arguments
    
      // Build the query parameters
      const queryParams = new URLSearchParams();
    
      // Always include model (with default 'flux')
      queryParams.append('model', model);
    
      // Add other parameters
      if (seed !== undefined) queryParams.append('seed', seed);
      if (width) queryParams.append('width', width);
      if (height) 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();
Behavior2/5

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

No annotations are provided, so the description must fully disclose behavior. It states the return of base64 data and file saving, but omits side effects, error handling, permission needs, or whether existing files are overwritten. The default behavior is mentioned but not the underlying service.

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 sentences with no redundancy. The first sentence succinctly describes the core action and outputs. The second sentence adds important default behavior information. Front-loaded and efficient.

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 complexity (10 parameters, no output schema), the description covers the high-level output (base64, file save) and default handling. However, it does not explain the format of base64, file overwrite behavior, or the external service involved. Adequate but not comprehensive.

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%, so each parameter has a description. The description adds value by clarifying that user-configured settings in MCP config serve as defaults, which is not in the schema. This provides meaningful context beyond the 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 'Generate an image' and specifies the outputs: base64-encoded data and saving to a file. It distinguishes from sibling tools like generateImageUrl (URL return) and editImage (edit action).

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 mentions that user-configured settings are used as defaults, which implies context, but does not explicitly state when to use this tool versus generateImageUrl or editImage. No guidance on exclusions or alternatives.

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