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