Skip to main content
Glama
nanameru

Gemini 2.5 Flash Image MCP

by nanameru

generate_image

Create images from text prompts using Google's Gemini 2.5 Flash Image technology. Generate photorealistic visuals with detailed scene descriptions and optional file saving.

Instructions

Generate an image from a text prompt using Gemini 2.5 Flash Image

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
promptYesDetailed scene description. Use photographic terms for photorealism.
saveToFilePathNoOptional path to save the image (png/jpeg by extension)

Implementation Reference

  • The inline handler function that processes the tool arguments, invokes the Gemini API via callGeminiGenerate, optionally saves the image, and returns a structured content response with text description, image data, and data URL.
    async (args) => {
      const { prompt, saveToFilePath } = args;
      const results = await callGeminiGenerate({ prompt, saveToFilePath });
      const first = results[0];
      const savedPath = await maybeSaveImage(first.imageBase64, first.mimeType, saveToFilePath);
      const dataUrl = `data:${first.mimeType};base64,${first.imageBase64}`;
      return {
        content: [
          { type: 'text', text: `Generated image${savedPath ? ` saved to ${savedPath}` : ''}` },
          { type: 'image', mimeType: first.mimeType, data: first.imageBase64 },
          { type: 'text', text: dataUrl },
        ],
      };
    }
  • Zod schema defining the input parameters for the generate_image tool: a required 'prompt' string and an optional 'saveToFilePath' string.
    {
      prompt: z.string().describe('Detailed scene description. Use photographic terms for photorealism.'),
      saveToFilePath: z.string().optional().describe('Optional path to save the image (png/jpeg by extension)'),
    },
  • src/index.ts:128-149 (registration)
    Registration of the generate_image tool with the MCP server using mcp.tool(), specifying name, description, input schema, and handler function.
    mcp.tool(
      'generate_image',
      'Generate an image from a text prompt using Gemini 2.5 Flash Image',
      {
        prompt: z.string().describe('Detailed scene description. Use photographic terms for photorealism.'),
        saveToFilePath: z.string().optional().describe('Optional path to save the image (png/jpeg by extension)'),
      },
      async (args) => {
        const { prompt, saveToFilePath } = args;
        const results = await callGeminiGenerate({ prompt, saveToFilePath });
        const first = results[0];
        const savedPath = await maybeSaveImage(first.imageBase64, first.mimeType, saveToFilePath);
        const dataUrl = `data:${first.mimeType};base64,${first.imageBase64}`;
        return {
          content: [
            { type: 'text', text: `Generated image${savedPath ? ` saved to ${savedPath}` : ''}` },
            { type: 'image', mimeType: first.mimeType, data: first.imageBase64 },
            { type: 'text', text: dataUrl },
          ],
        };
      }
    );
  • Key helper function that performs the HTTP POST request to the Gemini API to generate images based on the prompt and optional input images, parsing the response to extract base64 image data.
    async function callGeminiGenerate(request: GenerateRequest): Promise<{ imageBase64: string; mimeType: string }[]> {
      const textPart = { text: request.prompt };
      const imageParts = await toInlineDataParts(request.images);
      const parts = [textPart as any, ...imageParts];
    
      const fetchResponse = await fetch(`${GEMINI_ENDPOINT}?key=${encodeURIComponent(GEMINI_API_KEY)}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          contents: [
            {
              parts,
            },
          ],
        }),
      });
    
      if (!fetchResponse.ok) {
        const text = await fetchResponse.text();
        throw new Error(`Gemini API error ${fetchResponse.status}: ${text}`);
      }
    
      const json = (await fetchResponse.json()) as GeminiGenerateResponse;
      const images: { imageBase64: string; mimeType: string }[] = [];
      const first = json.candidates?.[0]?.content?.parts ?? [];
      for (const part of first) {
        if (part.inlineData?.data) {
          images.push({ imageBase64: part.inlineData.data, mimeType: part.inlineData.mimeType ?? 'image/png' });
        }
      }
    
      if (images.length === 0) {
        // Fallback: if API returns interleaved text etc.
        throw new Error('No image data returned by Gemini API');
      }
    
      return images;
    }
  • Helper function to optionally save the generated base64 image to a file path, determining extension from mimeType if needed.
    async function maybeSaveImage(base64: string, mimeType: string, targetPath?: string): Promise<string | undefined> {
      if (!targetPath) return undefined;
      const { writeFile } = await import('node:fs/promises');
      const { extname } = await import('node:path');
      const extension = extname(targetPath) || (mimeType === 'image/jpeg' ? '.jpg' : '.png');
      const resolved = resolve(targetPath.endsWith(extension) ? targetPath : `${targetPath}${extension}`);
      const buffer = Buffer.from(base64, 'base64');
      await writeFile(resolved, buffer);
      return resolved;
    }
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 method ('using Gemini 2.5 Flash Image') but doesn't cover key traits like rate limits, authentication needs, output format, error handling, or whether it's a read/write operation. For a generative tool with zero annotation coverage, this leaves critical behavioral aspects unspecified.

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 any fluff or redundancy. It's appropriately sized and front-loaded, making it easy for an agent to parse quickly. Every word earns its place, contributing to clarity.

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, lack of annotations, and no output schema, the description is incomplete. It doesn't explain what the tool returns (e.g., image data, file path, errors), behavioral aspects like costs or limitations, or how it differs from siblings. This leaves significant gaps for an agent to understand the tool fully.

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 both parameters ('prompt' and 'saveToFilePath') with descriptions. The tool description adds no additional parameter semantics beyond what's in the schema, such as examples or constraints. 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 tool's purpose: 'Generate an image from a text prompt using Gemini 2.5 Flash Image'. It specifies the verb ('generate'), resource ('image'), and method ('from a text prompt'), but doesn't explicitly differentiate from sibling tools like 'compose_images' or 'edit_image', which might also generate or modify images. This makes it clear but not fully sibling-distinctive.

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 like 'compose_images', 'edit_image', or 'style_transfer'. It doesn't mention any prerequisites, exclusions, or specific contexts for usage, leaving the agent to infer based on tool names alone. This lack of explicit guidance is a significant gap.

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/nanameru/Gemini-2.5-Flash-Image-MCP'

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