Skip to main content
Glama
kuai0901

iRAG MCP Server

by kuai0901

generate_image

Generate custom images using Baidu's iRAG API by inputting descriptive prompts and optional parameters like size, quantity, and reference images. Ideal for creating visuals tailored to specific needs or ideas.

Instructions

使用百度iRAG API生成图片

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
guidanceNo指导密度值(仅flux.1-schnell模型支持),默认为3.5
nNo生成图片数量,默认为1
promptYes图片生成提示词,描述要生成的图片内容
refer_imageNo参考图片URL(可选)
seedNo随机种子(仅flux.1-schnell模型支持)
sizeNo图片尺寸,默认为1024x10241024x1024
stepsNo采样步数(仅flux.1-schnell模型支持)

Implementation Reference

  • Main MCP tool handler for 'generate_image': validates params with Zod schema, maps to Irag API request, calls IragClient.generateImage, processes image URLs with image-saver utility, constructs CallToolResult with text descriptions of generated/saved images.
    private async handleGenerateImage(params: GenerateImageParams): Promise<CallToolResult> {
      // 验证参数
      const validatedParams = generateImageParamsSchema.parse(params);
      
      logger.info('开始处理图片生成请求', validatedParams);
    
      try {
        // 调用百度iRAG API
        const requestParams: IragGenerationRequest = {
          model: this.config.defaultModel,
          prompt: validatedParams.prompt,
          n: validatedParams.n || 1,
          size: validatedParams.size || '1024x1024',
        };
    
        // 只有当参数存在时才添加可选参数
        if (validatedParams.refer_image !== undefined) {
          requestParams.refer_image = validatedParams.refer_image;
        }
        if (validatedParams.steps !== undefined) {
          requestParams.steps = validatedParams.steps;
        }
        if (validatedParams.seed !== undefined) {
          requestParams.seed = validatedParams.seed;
        }
        if (validatedParams.guidance !== undefined) {
          requestParams.guidance = validatedParams.guidance;
        }
    
        const response = await this.iragClient.generateImage(requestParams);
    
        // 构建响应内容
        const content: TextContent[] = [
          {
            type: 'text',
            text: `成功生成${response.data.length}张图片`,
          } as TextContent,
        ];
    
        // 处理图片
        const imageUrls = response.data.map(item => item.url);
        const imageResults = await processImages(
          imageUrls,
          this.config.resourceMode,
          this.config.basePath
        );
    
        // 添加图片处理结果
        for (const [index, result] of imageResults.entries()) {
          if (result.success) {
            // 添加文本说明
            let textMessage = `图片 ${index + 1} 生成成功`;
            if (result.localPath) {
              textMessage += `\n📁 已保存到: ${result.localPath}`;
            }
            if (this.config.resourceMode === 'url') {
              textMessage += `\n🔗 原始URL: ${result.url}`;
            }
    
            content.push({
              type: 'text',
              text: textMessage,
            } as TextContent);
          } else {
            // 处理失败的情况
            logger.error(`图片 ${index + 1} 处理失败`, result.error);
            content.push({
              type: 'text',
              text: `图片 ${index + 1} 处理失败: ${result.error || '未知错误'}\n🔗 原始URL: ${result.url}`,
            } as TextContent);
          }
        }
    
        logger.info('图片生成成功', {
          requestId: response.id,
          imageCount: response.data.length,
        });
    
        return { content };
      } catch (error) {
        logger.error('图片生成失败', error);
        throw error;
      }
    }
  • Tool registration in ListToolsRequestHandler: defines 'generate_image' tool with detailed inputSchema matching GenerateImageParams.
    {
      name: 'generate_image',
      description: '使用百度iRAG API生成图片',
      inputSchema: {
        type: 'object',
        properties: {
          prompt: {
            type: 'string',
            description: '图片生成提示词,描述要生成的图片内容',
          },
    
          refer_image: {
            type: 'string',
            format: 'uri',
            description: '参考图片URL(可选)',
          },
          n: {
            type: 'integer',
            minimum: 1,
            maximum: 4,
            description: '生成图片数量,默认为1',
            default: 1,
          },
          size: {
            type: 'string',
            enum: [
              '512x512', '768x768', '1024x768', '1024x1024'
            ],
            description: '图片尺寸,默认为1024x1024',
            default: '1024x1024',
          },
          steps: {
            type: 'integer',
            minimum: 1,
            maximum: 50,
            description: '采样步数(仅flux.1-schnell模型支持)',
          },
          seed: {
            type: 'integer',
            minimum: 0,
            maximum: 4294967295,
            description: '随机种子(仅flux.1-schnell模型支持)',
          },
          guidance: {
            type: 'number',
            minimum: 0,
            maximum: 30,
            description: '指导密度值(仅flux.1-schnell模型支持),默认为3.5',
            default: 3.5,
          },
        },
        required: ['prompt'],
      },
    },
  • Zod validation schema for GenerateImageParams used in the tool handler.
    const generateImageParamsSchema = z.object({
      prompt: z.string().min(1, '提示词不能为空'),
      refer_image: z.string().url().optional(),
      n: z.number().int().min(1).max(4).optional(),
      size: z.enum([
        '512x512', '768x768', '1024x768', '1024x1024'
      ]).optional(),
      steps: z.number().int().min(1).max(50).optional(),
      seed: z.number().int().min(0).max(4294967295).optional(),
      guidance: z.number().min(0).max(30).optional(),
    });
  • Core helper function in IragClient that performs the HTTP POST to Baidu Qianfan iRAG API endpoint '/v2/images/generations', includes param validation, retry logic with exponential backoff, and detailed error handling.
    async generateImage(params: IragGenerationRequest): Promise<IragGenerationResponse> {
      const validatedParams = this.validateRequest(params);
      
      logger.info('开始生成图片', { params: validatedParams });
    
      return this.withRetry(async () => {
        try {
          const response = await this.client.post<IragGenerationResponse>(
            '/v2/images/generations',
            validatedParams
          );
    
          logger.info('图片生成成功', {
            id: response.data.id,
            imageCount: response.data.data.length,
          });
    
          return response.data;
        } catch (error) {
          if (error instanceof AxiosError && error.response) {
            const errorData = error.response.data as IragErrorResponse;
            const errorMessage = `API错误 (${error.response.status}): ${errorData.message || error.message}`;
            logger.error(errorMessage, errorData);
            throw new Error(errorMessage);
          }
          throw error;
        }
      });
    }
  • TypeScript interface defining the input parameters for the generate_image tool.
    export interface GenerateImageParams {
      prompt: string;
      refer_image?: string | undefined;
      n?: number | undefined;
      size?: ImageSize | undefined;
      steps?: number | undefined;
      seed?: number | undefined;
      guidance?: number | undefined;
    }
Behavior1/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. However, it only states the basic action without any behavioral traits such as rate limits, authentication needs, cost implications, output format, or error handling. This is inadequate for a tool with 7 parameters and no output schema.

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 with no wasted words. It is appropriately sized and front-loaded, directly stating the tool's function. Every part of the description earns its place by conveying the essential action and API source.

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 tool's complexity (7 parameters, no output schema, no annotations), the description is incomplete. It lacks crucial context such as behavioral traits, usage guidelines, and output details. Without annotations or an output schema, the description should provide more information to help the agent understand how to use the tool effectively, but it falls short.

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?

The schema description coverage is 100%, meaning all parameters are documented in the input schema. The description adds no additional meaning beyond what the schema provides, as it doesn't mention any parameters. With high schema coverage, the baseline score is 3, reflecting that the description doesn't compensate but also doesn't need to given the schema's completeness.

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

Purpose2/5

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

The description '使用百度iRAG API生成图片' (Use Baidu iRAG API to generate images) states the general action but is vague. It specifies the API provider (Baidu iRAG) and the outcome (generate images), but lacks a specific verb+resource combination and doesn't differentiate from potential siblings (though none exist). The purpose is clear at a high level but lacks detail about what type of image generation this is.

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?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention any context, prerequisites, or exclusions. With no sibling tools, this is less critical, but the description still fails to offer any usage instructions or scenarios, leaving the agent without direction.

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

Related 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/kuai0901/irag-mcp-server'

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