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 ]; }

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