Skip to main content
Glama
andylee20014

MCP Replicate FLUX

by andylee20014

generate-image

Generate images from text prompts using Replicate's FLUX model and store them with accessible URLs in Cloudflare R2.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
promptYes
filenameYes

Implementation Reference

  • index.js:17-33 (handler)
    Inline handler function for the 'generate-image' tool that calls the generateImage helper, handles errors, and returns MCP-formatted response content.
    async ({ prompt, filename }) => {
      try {
        const imageUrl = await generateImage({ prompt, filename })
        return {
          content: [
            { type: 'text', text: `Image successfully generated and uploaded to Cloudflare R2: ${imageUrl}` }
          ]
        }
      } catch (error) {
        console.error('Image generation failed:', error)
        return {
          content: [
            { type: 'text', text: `Image generation failed: ${error.message}` }
          ]
        }
      }
    }
  • Zod input schema defining 'prompt' and 'filename' parameters for the generate-image tool.
    { prompt: z.string(), filename: z.string() },
  • index.js:14-34 (registration)
    Registration of the 'generate-image' tool on the McpServer instance.
    server.tool(
      'generate-image',
      { prompt: z.string(), filename: z.string() },
      async ({ prompt, filename }) => {
        try {
          const imageUrl = await generateImage({ prompt, filename })
          return {
            content: [
              { type: 'text', text: `Image successfully generated and uploaded to Cloudflare R2: ${imageUrl}` }
            ]
          }
        } catch (error) {
          console.error('Image generation failed:', error)
          return {
            content: [
              { type: 'text', text: `Image generation failed: ${error.message}` }
            ]
          }
        }
      }
    )
  • Helper function implementing the core logic: generates image using Replicate Flux model, fetches the image, generates unique dated filename, and uploads to Cloudflare R2 via S3Client.
    module.exports = async ({ prompt, filename }) => {
      const replicate = new Replicate({
        auth: process.env.REPLICATE_API_TOKEN
      })
    
      try {
        // 生成唯一文件名,避免覆盖
        const timestamp = Date.now()
        const fileNameWithoutExt = path.basename(filename, path.extname(filename))
        const fileExt = path.extname(filename) || '.jpg'
        const uniqueFilename = `${fileNameWithoutExt}-${timestamp}${fileExt}`
        
        // 创建基于日期的文件夹结构
        const date = new Date()
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从0开始,需要+1
        const day = String(date.getDate()).padStart(2, '0')
        const folderPath = `${year}/${month}/${day}`
        
        // 完整的文件路径,包含日期文件夹
        const fullFilePath = `${folderPath}/${uniqueFilename}`
    
        // 使用 Replicate 生成图片
        const output = await replicate.run('black-forest-labs/flux-schnell', {
          input: {
            prompt,
            go_fast: true,
            num_outputs: 1,
            megapixels: '1',
            output_quality: 80,
            aspect_ratio: '16:9',
            output_format: 'jpg',
            num_inference_steps: 4
          }
        })
    
        if (!output || !output[0]) {
          throw new Error('No image generated')
        }
    
        const imageUrl = output[0]
        
        // 获取图片数据
        const response = await fetch(imageUrl)
        if (!response.ok) {
          throw new Error('Failed to fetch generated image')
        }
        const imageBuffer = await response.arrayBuffer()
    
        // 上传到 R2,使用包含日期文件夹的路径
        await s3Client.send(new PutObjectCommand({
          Bucket: process.env.STORAGE_BUCKET,
          Key: fullFilePath,
          Body: Buffer.from(imageBuffer),
          ContentType: 'image/jpeg'
        }))
    
        // 返回可访问的图片链接
        const r2ImageUrl = `https://${process.env.STORAGE_DOMAIN}/${fullFilePath}`
        return r2ImageUrl
      } catch (error) {
        console.error('Error in generateImage:', error)
        throw error
      }
    }
Behavior1/5

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

Tool has no description.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness1/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Tool has no description.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness1/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Tool has no description.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Tool has no description.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose1/5

Does the description clearly state what the tool does and how it differs from similar tools?

Tool has no description.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines1/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Tool has no description.

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

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