Skip to main content
Glama
frankdeno

FLUX Image Generator MCP Server

by frankdeno

generateImage

Create images from text descriptions using the FLUX AI model, with options to customize dimensions, enhance detail, and adjust safety settings.

Instructions

Generate an image using Black Forest Lab's FLUX model based on a text prompt

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
promptYesText description of the image to generate
widthNoWidth of the image in pixels
heightNoHeight of the image in pixels
promptUpsamplingNoEnhance detail by upsampling the prompt
seedNoRandom seed for reproducible results
safetyToleranceNoContent moderation tolerance (1-5)
customPathNoCustom path to save the generated image

Implementation Reference

  • The core handler function that executes the generateImage tool logic: makes API call to Black Forest Lab FLUX, polls for completion, downloads and saves image locally if requested.
    export async function generateImage(
      prompt: string, 
      options: ImageGenerationOptions = {}
    ): Promise<ImageGenerationResult> {
      const apiKey = process.env.BFL_API_KEY;
      
      if (!apiKey) {
        throw new Error('API key is required. Set BFL_API_KEY environment variable.');
      }
      
      // Build the request payload
      const payload = {
        prompt,
        width: options.width || 1024,
        height: options.height || 1024,
        prompt_upsampling: options.promptUpsampling || false,
        safety_tolerance: options.safetyTolerance || 3,
        ...(options.seed !== undefined && { seed: options.seed })
      };
      
      let pollingUrl;
      try {
        // Make the initial API request
        console.error(`[INFO] Sending request to FLUX API for prompt: "${prompt}"`);
        const response = await axios.post(BFL_API_ENDPOINT, payload, {
          headers: {
            'Content-Type': 'application/json',
            'X-Key': apiKey
          }
        });
        
        // Check if we need to poll for results
        if (response.data.polling_url) {
          pollingUrl = response.data.polling_url;
          console.error(`[INFO] Got polling URL: ${pollingUrl}`);
        } else if (response.data.image_url) {
          // If we got an image URL directly, no need to poll
          console.error(`[INFO] Got image URL directly: ${response.data.image_url}`);
          
          const result: ImageGenerationResult = {
            image_url: response.data.image_url,
            local_path: null
          };
          
          // Save the image locally if requested
          if (options.saveImage) {
            try {
              const filename = options.filename || `flux_${Date.now()}.png`;
              const savePath = await downloadImage(
                result.image_url, 
                filename, 
                options.outputDir || process.env.OUTPUT_DIR || './output',
                options.customPath
              );
              result.local_path = savePath;
            } catch (downloadError: any) {
              console.error(`[ERROR] Error saving image: ${downloadError.message}`);
              // Continue with the operation even if download fails
            }
          }
          
          return result;
        } else {
          throw new Error('Invalid response from Black Forest Lab API: No polling URL or image URL');
        }
      } catch (error: any) {
        const errorMsg = error.response?.data?.message || error.message || 'Unknown error';
        console.error(`[ERROR] Error calling Black Forest Lab API: ${errorMsg}`);
        throw new Error(`Failed to generate image: ${errorMsg}`);
      }
      
      // If we have a polling URL, poll for the result
      try {
        const maxPollingAttempts = options.maxPollingAttempts || 30;
        const pollingInterval = options.pollingInterval || 2000;
        
        const pollResult = await pollForResults(
          pollingUrl, 
          apiKey, 
          maxPollingAttempts, 
          pollingInterval
        );
        
        // Check if we have a direct image_url or need to extract it from result.sample
        if (!pollResult.image_url && pollResult.result && pollResult.result.sample) {
          pollResult.image_url = pollResult.result.sample;
        }
        
        if (!pollResult.image_url) {
          throw new Error('No image URL in completed result');
        }
        
        const result: ImageGenerationResult = {
          image_url: pollResult.image_url,
          local_path: null
        };
        
        // Save the image locally if requested
        if (options.saveImage) {
          try {
            const filename = options.filename || `flux_${Date.now()}.png`;
            const savePath = await downloadImage(
              result.image_url, 
              filename, 
              options.outputDir || process.env.OUTPUT_DIR || './output',
              options.customPath
            );
            result.local_path = savePath;
          } catch (downloadError: any) {
            console.error(`[ERROR] Error saving image: ${downloadError.message}`);
            // Continue with the operation even if download fails
          }
        }
        
        return result;
      } catch (error: any) {
        console.error(`[ERROR] Error in polling process: ${error.message}`);
        throw new Error(`Failed to generate image: ${error.message}`);
      }
    }
  • The schema definition for the generateImage tool, including input schema, description, and parameters.
    export const GENERATE_IMAGE_TOOL: Tool = {
      name: "generateImage",
      description: "Generate an image using Black Forest Lab's FLUX model based on a text prompt",
      inputSchema: {
        type: "object",
        properties: {
          prompt: {
            type: "string",
            description: "Text description of the image to generate"
          },
          width: {
            type: "number",
            description: "Width of the image in pixels",
            default: 1024
          },
          height: {
            type: "number",
            description: "Height of the image in pixels",
            default: 1024
          },
          promptUpsampling: {
            type: "boolean",
            description: "Enhance detail by upsampling the prompt",
            default: false
          },
          seed: {
            type: "number",
            description: "Random seed for reproducible results"
          },
          safetyTolerance: {
            type: "number",
            description: "Content moderation tolerance (1-5)",
            default: 3
          },
          customPath: {
            type: "string",
            description: "Custom path to save the generated image"
          }
        },
        required: ["prompt"]
      }
    };
  • src/index.ts:48-54 (registration)
    Registration of the generateImage tool schema in the MCP server's listTools request handler.
    server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: [
        GENERATE_IMAGE_TOOL,
        QUICK_IMAGE_TOOL,
        BATCH_GENERATE_IMAGES_TOOL
      ],
    }));
  • The MCP CallToolRequestSchema handler case for generateImage: validates input arguments, prepares options, calls the core generateImage function, and formats the response.
    case "generateImage": {
      // Validate parameters
      if (typeof args.prompt !== 'string') {
        throw new Error("Invalid prompt: must be a string");
      }
    
      // Use the full image generation capabilities
      const options = {
        width: typeof args.width === 'number' ? args.width : 1024,
        height: typeof args.height === 'number' ? args.height : 1024,
        promptUpsampling: typeof args.promptUpsampling === 'boolean' ? args.promptUpsampling : false,
        seed: typeof args.seed === 'number' ? args.seed : undefined,
        safetyTolerance: typeof args.safetyTolerance === 'number' ? args.safetyTolerance : 3,
        saveImage: true,
        filename: `flux_${Date.now()}.png`,
        customPath: typeof args.customPath === 'string' ? args.customPath : undefined
      };
      
      const result = await generateImage(args.prompt, options);
      
      // Return a plain text response with the image URL and save location
      let textContent = `Image generated\nLink: ${result.image_url}`;
      
      // Add information about where the image was saved
      if (result.local_path) {
        textContent += `\nImage saved to: ${result.local_path}`;
      }
      
      return {
        content: [
          { type: "text", text: textContent }
        ],
        isError: false,
      };
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions the model (FLUX) but fails to describe key traits like rate limits, authentication needs, output format (e.g., image file type), error handling, or performance characteristics. This leaves significant gaps for a tool that likely involves external API calls and resource-intensive operations.

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?

The description is a single, efficient sentence that directly states the tool's purpose without unnecessary words. It is front-loaded and wastes no space, making it easy for an agent to parse quickly.

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?

Given the complexity of an image generation tool with 7 parameters, no annotations, and no output schema, the description is incomplete. It lacks information on behavioral aspects, usage guidelines, and output details (e.g., how the image is returned), which are crucial for proper tool invocation in this context.

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. The description does not add any additional meaning or context beyond what the schema provides (e.g., it doesn't explain prompt best practices or safety tolerance implications). With high schema coverage, the baseline score of 3 is appropriate as the description doesn't compensate but also doesn't detract.

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 action ('Generate an image') and specifies the resource (using Black Forest Lab's FLUX model based on a text prompt), which is specific and unambiguous. However, it does not explicitly differentiate from sibling tools like 'batchGenerateImages' or 'quickImage', which might offer batch processing or faster generation, so it misses full 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 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 such as 'batchGenerateImages' or 'quickImage'. It lacks context about scenarios, prerequisites, or exclusions, leaving the agent without explicit usage instructions beyond the basic function.

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/frankdeno/flux-image-generator-mcp'

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