Skip to main content
Glama

flux_generate

Generate images from text prompts using FLUX AI models, save files to specified directories, and apply variations, inpainting, or edge-guided creation.

Instructions

Generate an image with a FLUX model via Replicate and save files to download_path

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
promptYesText prompt describing the image
download_pathYesDirectory to save generated images
modelNoFLUX model to useblack-forest-labs/flux-1.1-pro-ultra
image_pathNoLocal path or URL to input image (for image-accepting models)
mask_pathNoLocal path or URL to mask for inpainting (Fill model)
aspect_ratioNoAspect ratio (e.g., '1:1', '16:9', '3:4')
seedNoRandom seed for reproducibility
rawNoEnable raw realism mode (Ultra model)
num_outputsNoNumber of images to generate
output_qualityNoQuality setting (model-dependent)
go_fastNoSpeed vs quality tradeoff
strengthNoVariation strength (Redux model)
num_inference_stepsNoInference steps (Fill model)
guidanceNoGuidance scale (Fill model)
output_formatNoOutput image format (png, jpeg, or webp)png

Implementation Reference

  • The core handler for the 'flux_generate' tool. It validates inputs, runs the specified FLUX model on Replicate, downloads the generated image(s) to a secure download path, and returns the file paths and URLs.
    if (name === "flux_generate") {
      try {
        const apiToken = process.env.REPLICATE_API_TOKEN;
        if (!apiToken) {
          throw new Error("REPLICATE_API_TOKEN environment variable is not set");
        }
    
        const replicate = new Replicate({ auth: apiToken });
    
        const modelId = args.model || "black-forest-labs/flux-1.1-pro-ultra";
        const meta = FLUX_MODELS[modelId];
    
        if (!meta) {
          throw new Error(`Unknown model: ${modelId}`);
        }
    
        // Build input
        const input = { prompt: args.prompt };
    
        // Set output format (default to png for better compatibility)
        const outputFormat = args.output_format || "png";
        input.output_format = outputFormat;
    
        // Add optional parameters if they exist for this model
        const optionalParams = [
          "aspect_ratio",
          "seed",
          "raw",
          "num_outputs",
          "output_quality",
          "go_fast",
          "strength",
          "num_inference_steps",
          "guidance",
        ];
    
        for (const param of optionalParams) {
          if (args[param] !== undefined && meta.inputs[param]) {
            input[param] = args[param];
          }
        }
    
        // Handle image input for models that accept it
        if (meta.accepts_image) {
          if (!args.image_path) {
            throw new Error(`Model ${modelId} requires image_path`);
          }
          // Validate image_path to prevent SSRF
          // Only allow HTTPS URLs or local file paths (Replicate will handle validation)
          if (args.image_path.startsWith("http://")) {
            throw new Error("HTTP URLs not allowed for security reasons. Use HTTPS.");
          }
          input.image = args.image_path;
        }
    
        // Handle mask for Fill model
        if (modelId.endsWith("/flux-fill-pro") && args.mask_path) {
          // Same validation for mask paths
          if (args.mask_path.startsWith("http://")) {
            throw new Error("HTTP URLs not allowed for security reasons. Use HTTPS.");
          }
          input.mask = args.mask_path;
        }
    
        // Run the model
        const output = await replicate.run(modelId, { input });
    
        // Download results - VALIDATE PATH FIRST
        const downloadPath = validateDownloadPath(args.download_path);
        await fs.mkdir(downloadPath, { recursive: true });
    
        const timestamp = new Date()
          .toISOString()
          .replace(/[:.]/g, "-")
          .slice(0, 19);
        const baseName = `${meta.display.replace(/[^a-z0-9]/gi, "").toLowerCase()}_${timestamp}`;
    
        const savedFiles = [];
        const urls = Array.isArray(output) ? output : [output];
    
        for (let i = 0; i < urls.length; i++) {
          const urlObj = urls[i];
          // Convert to string if it's a URL object
          const url = typeof urlObj === 'string' ? urlObj : String(urlObj);
    
          // Use the requested output format for file extension
          const ext = outputFormat === "jpeg" ? ".jpg" : `.${outputFormat}`;
          const filepath = path.join(downloadPath, `${baseName}_${i + 1}${ext}`);
    
          await downloadFile(url, filepath);
          savedFiles.push(filepath);
        }
    
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(
                {
                  model: modelId,
                  saved: savedFiles,
                  urls: urls,
                },
                null,
                2
              ),
            },
          ],
        };
      } catch (error) {
        // Sanitize error message to avoid leaking sensitive information
        let safeMessage = "An error occurred while generating the image.";
    
        // Only expose safe, user-actionable error messages
        if (error.message.includes("REPLICATE_API_TOKEN")) {
          safeMessage = "API token is not configured. Please set REPLICATE_API_TOKEN.";
        } else if (error.message.includes("Unknown model")) {
          safeMessage = error.message; // Safe to expose model validation errors
        } else if (error.message.includes("requires image_path")) {
          safeMessage = error.message; // Safe to expose parameter validation errors
        } else if (error.message.includes("Download path must be")) {
          safeMessage = "Invalid download path. Path must be within home directory or /tmp.";
        } else if (error.message.includes("HTTP URLs not allowed")) {
          safeMessage = "Only HTTPS URLs are allowed for security reasons.";
        } else if (error.message.includes("NSFW")) {
          safeMessage = "Content was flagged by safety filters. Please try a different prompt.";
        } else if (error.message.includes("Only Replicate CDN")) {
          safeMessage = "Invalid image source. Only Replicate CDN URLs are allowed.";
        }
    
        // Log full error server-side for debugging (not sent to client)
        console.error("FLUX MCP Error:", error);
    
        return {
          content: [
            {
              type: "text",
              text: `Error: ${safeMessage}`,
            },
          ],
          isError: true,
        };
      }
    }
  • index.js:214-288 (registration)
    Registration of the 'flux_generate' tool in the ListTools response, including name, description, and detailed input schema with properties, enums, defaults, and requirements.
    {
      name: "flux_generate",
      description:
        "Generate an image with a FLUX model via Replicate and save files to download_path",
      inputSchema: {
        type: "object",
        properties: {
          prompt: {
            type: "string",
            description: "Text prompt describing the image",
          },
          download_path: {
            type: "string",
            description: "Directory to save generated images",
          },
          model: {
            type: "string",
            description: "FLUX model to use",
            enum: Object.keys(FLUX_MODELS),
            default: "black-forest-labs/flux-1.1-pro-ultra",
          },
          image_path: {
            type: "string",
            description: "Local path or URL to input image (for image-accepting models)",
          },
          mask_path: {
            type: "string",
            description: "Local path or URL to mask for inpainting (Fill model)",
          },
          aspect_ratio: {
            type: "string",
            description: "Aspect ratio (e.g., '1:1', '16:9', '3:4')",
          },
          seed: {
            type: "number",
            description: "Random seed for reproducibility",
          },
          raw: {
            type: "boolean",
            description: "Enable raw realism mode (Ultra model)",
          },
          num_outputs: {
            type: "number",
            description: "Number of images to generate",
          },
          output_quality: {
            type: "number",
            description: "Quality setting (model-dependent)",
          },
          go_fast: {
            type: "boolean",
            description: "Speed vs quality tradeoff",
          },
          strength: {
            type: "number",
            description: "Variation strength (Redux model)",
          },
          num_inference_steps: {
            type: "number",
            description: "Inference steps (Fill model)",
          },
          guidance: {
            type: "number",
            description: "Guidance scale (Fill model)",
          },
          output_format: {
            type: "string",
            description: "Output image format (png, jpeg, or webp)",
            enum: ["png", "jpeg", "webp"],
            default: "png",
          },
        },
        required: ["prompt", "download_path"],
      },
    },
  • FLUX_MODELS configuration object defining all supported models, their display names, kinds, notes, input schemas, and whether they accept images. Used by flux_generate for validation and metadata.
    const FLUX_MODELS = {
      "black-forest-labs/flux-1.1-pro-ultra": {
        display: "FLUX1.1 Pro Ultra",
        kind: "text-to-image",
        notes: [
          "Highest quality, up to ~4MP; 'raw' mode for realism.",
          "Use when you need best composition/large output.",
        ],
        inputs: {
          prompt: { required: true, type: "string" },
          raw: { required: false, type: "boolean" },
          aspect_ratio: { required: false, type: "string" },
          seed: { required: false, type: "integer" },
          output_quality: { required: false, type: "number" },
          go_fast: { required: false, type: "boolean" },
        },
        accepts_image: false,
      },
      "black-forest-labs/flux-pro": {
        display: "FLUX1.1 Pro",
        kind: "text-to-image",
        notes: [
          "Fast, reliable, commercial-grade default when Ultra not required.",
        ],
        inputs: {
          prompt: { required: true, type: "string" },
          aspect_ratio: { required: false, type: "string" },
          seed: { required: false, type: "integer" },
        },
        accepts_image: false,
      },
      "black-forest-labs/flux-redux-dev": {
        display: "FLUX.1 Redux [dev]",
        kind: "image-variation",
        notes: [
          "Variations/restyling while preserving key elements; mix image + text.",
        ],
        inputs: {
          image: { required: true, type: "file_or_url" },
          prompt: { required: true, type: "string" },
          strength: { required: false, type: "number" },
          seed: { required: false, type: "integer" },
          num_outputs: { required: false, type: "integer" },
        },
        accepts_image: true,
      },
      "black-forest-labs/flux-fill-pro": {
        display: "FLUX.1 Fill [pro]",
        kind: "inpainting/outpainting",
        notes: ["Professional in/outpainting; provide mask for areas to change."],
        inputs: {
          image: { required: true, type: "file_or_url" },
          mask: { required: false, type: "file_or_url" },
          prompt: { required: true, type: "string" },
          num_inference_steps: { required: false, type: "integer" },
          guidance: { required: false, type: "number" },
          seed: { required: false, type: "integer" },
        },
        accepts_image: true,
      },
      "black-forest-labs/flux-depth-dev": {
        display: "FLUX.1 Depth [dev]",
        kind: "depth-guided editing",
        notes: [
          "Structure-preserving edits/style transfer using depth; supply an image.",
        ],
        inputs: {
          image: { required: true, type: "file_or_url" },
          prompt: { required: true, type: "string" },
          seed: { required: false, type: "integer" },
        },
        accepts_image: true,
      },
      "black-forest-labs/flux-canny-pro": {
        display: "FLUX.1 Canny [pro]",
        kind: "edge-guided generation",
        notes: [
          "Control structure/composition with edges; ideal for sketches/wireframes → detailed images.",
        ],
        inputs: {
          image: { required: true, type: "file_or_url" },
          prompt: { required: true, type: "string" },
          seed: { required: false, type: "integer" },
        },
        accepts_image: true,
      },
    };
  • validateDownloadPath helper function used by flux_generate to securely validate and normalize the download directory path, preventing directory traversal attacks.
    function validateDownloadPath(userPath) {
      // Expand ~ to home directory
      const expandedPath = userPath.replace(/^~/, process.env.HOME || "");
    
      // Resolve to absolute path and normalize
      const absolutePath = path.resolve(expandedPath);
    
      // Security check: Ensure path doesn't escape to parent directories
      const homePath = process.env.HOME || "";
      const allowedPaths = [
        homePath,
        "/tmp",
        path.join(process.cwd(), "downloads"),
      ];
    
      // Check if the resolved path is within allowed directories
      const isAllowed = allowedPaths.some(allowedPath => {
        return absolutePath.startsWith(path.resolve(allowedPath));
      });
    
      if (!isAllowed) {
        throw new Error(`Download path must be within home directory, /tmp, or project downloads folder. Got: ${absolutePath}`);
      }
    
      return absolutePath;
    }
  • downloadFile helper function used by flux_generate to securely download generated images from Replicate CDN URLs to local paths.
    async function downloadFile(url, filepath) {
      // Validate URL before downloading
      validateReplicateUrl(url);
    
      return new Promise((resolve, reject) => {
        const file = fsSync.createWriteStream(filepath);
    
        https
          .get(url, (response) => {
            // Check for redirects to non-Replicate domains
            if (response.statusCode === 301 || response.statusCode === 302) {
              const redirectUrl = response.headers.location;
              try {
                validateReplicateUrl(redirectUrl);
              } catch (error) {
                file.close();
                fsSync.unlink(filepath, () => {});
                reject(new Error("Redirect to unsafe domain detected"));
                return;
              }
            }
    
            response.pipe(file);
            file.on("finish", () => {
              file.close(resolve);
            });
          })
          .on("error", (err) => {
            fsSync.unlink(filepath, () => {});
            reject(err);
          });
      });
    }
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions 'save files to download_path' which indicates file system writing, but doesn't disclose important behaviors like: whether this is a long-running operation, rate limits, authentication requirements, error handling, or what happens if download_path doesn't exist. For a complex 15-parameter image generation tool, this is inadequate.

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 front-loads the core functionality. Every word earns its place: 'Generate an image' (action), 'with a FLUX model' (technology), 'via Replicate' (service), 'and save files to download_path' (output behavior). No wasted words or redundancy.

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 generation tool with 15 parameters and no annotations or output schema, the description is insufficient. It doesn't explain what the tool returns (file paths? success status?), doesn't mention error conditions, and provides no context about model-specific behaviors. The 100% schema coverage helps, but the description should do more to guide usage of such a feature-rich tool.

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 15 parameters thoroughly. The description mentions 'download_path' but adds no additional semantic context beyond what's in the schema. It doesn't explain relationships between parameters (e.g., which models accept image_path) or provide usage examples. Baseline 3 is appropriate when schema does the heavy lifting.

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 resource ('with a FLUX model via Replicate'), specifying the service provider. It distinguishes from the sibling tool 'flux_models' by focusing on image generation rather than model listing. However, it doesn't explicitly contrast with the sibling tool in the description text itself.

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. There's no mention of when to choose specific models, when to use image_path or mask_path parameters, or any prerequisites for usage. The sibling tool 'flux_models' exists but isn't referenced in usage context.

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/kmaurinjones/flux-mcp'

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