Skip to main content
Glama
tndfame
by tndfame

push_gemini_flex

Generate and send LINE Flex messages using natural language prompts. Describe the card you want, and it creates and pushes it to users via the LINE Bot MCP Server.

Instructions

Generate a LINE Flex message (bubble/carousel) from a natural language prompt using Gemini, then push it to a user.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
userIdNoThe user ID to receive a message. Defaults to DESTINATION_USER_ID.U1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p
promptYesDescribe the Flex card you want.
modelNoGemini model name, e.g., gemini-2.0-flashgemini-2.0-flash
altTextNoAlternative text for Flex message.Generated card

Implementation Reference

  • The main handler function that executes the tool. It uses Gemini to generate a LINE Flex message from a prompt, parses and validates the JSON output, and pushes the message to the specified user ID via LINE Messaging API.
    async ({ userId, prompt, model, altText }) => {
      if (!userId) return createErrorResponse(NO_USER_ID_ERROR);
    
      const apiKey = process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY;
      if (!apiKey) {
        return createErrorResponse(
          "Please set GEMINI_API_KEY (or GOOGLE_API_KEY) in environment variables.",
        );
      }
    
      try {
        async function callGeminiOnce(
          modelName: string,
          apiVersion: "v1" | "v1beta",
        ) {
          const endpoint = `https://generativelanguage.googleapis.com/${apiVersion}/models/${encodeURIComponent(
            modelName,
          )}:generateContent`;
          const body = {
            contents: [
              {
                role: "user",
                parts: [
                  {
                    text:
                      `You are an assistant that outputs only JSON for LINE Flex Message 'contents'.\n` +
                      `Return a valid 'contents' object (type: 'bubble' or 'carousel'). Do not include markdown or explanations.\n` +
                      `Keep text short. Avoid unsupported fields.\n\n` +
                      `Requirement: ${prompt}`,
                  },
                ],
              },
            ],
          };
          const res = await fetch(endpoint, {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              "X-goog-api-key": apiKey,
            },
            body: JSON.stringify(body),
          });
          return res;
        }
    
        const tryModels: string[] = [model];
        if (!model.endsWith("-latest")) tryModels.push(`${model}-latest`);
        for (const m of [
          "gemini-2.0-flash",
          "gemini-2.0-flash-latest",
          "gemini-1.5-flash-latest",
        ]) {
          if (!tryModels.includes(m)) tryModels.push(m);
        }
    
        let res: Response | undefined;
        let lastErr = "";
        for (const m of tryModels) {
          for (const ver of ["v1", "v1beta"] as const) {
            res = await callGeminiOnce(m, ver);
            if (res.ok) break;
            lastErr = await res.text();
            if (res.status !== 404) break;
          }
          if (res?.ok) break;
        }
        if (!res || !res.ok) {
          return createErrorResponse(
            `Gemini API error: HTTP ${res?.status} ${res?.statusText} - ${lastErr}`,
          );
        }
    
        const data = (await res.json()) as GenerateContentResponse;
        const raw =
          data?.candidates?.[0]?.content?.parts
            ?.map(p => p.text || "")
            .join("") || "";
        if (!raw)
          return createErrorResponse(
            data?.error?.message || "Empty result from Gemini",
          );
    
        // Extract plain JSON even if wrapped with ```json fences or extra text
        const fence = raw.match(/```(?:json)?\s*([\s\S]*?)```/i);
        let jsonText = fence ? fence[1].trim() : raw;
        if (!fence) {
          const s = raw.indexOf("{");
          const e = raw.lastIndexOf("}");
          if (s !== -1 && e !== -1 && e > s) jsonText = raw.slice(s, e + 1);
        }
    
        let contents: unknown;
        try {
          contents = JSON.parse(jsonText);
        } catch (e1: any) {
          // Attempt a light sanitization (remove trailing commas) then parse again
          try {
            const sanitized = jsonText.replace(/,\s*([}\]])/g, "$1");
            contents = JSON.parse(sanitized);
          } catch (e2: any) {
            return createErrorResponse(
              `Failed to parse Flex contents JSON from Gemini: ${e1?.message || e1}`,
            );
          }
        }
    
        const msg = { type: "flex", altText, contents };
        const parsed = flexMessageSchema.safeParse(msg);
        if (!parsed.success) {
          return createErrorResponse(
            `Generated Flex invalid: ${parsed.error.issues.map(i => i.message).join(", ")}`,
          );
        }
    
        const response = await this.client.pushMessage({
          to: userId,
          messages: [parsed.data as unknown as messagingApi.Message],
        });
        return createSuccessResponse(response);
      } catch (error: any) {
        return createErrorResponse(
          `Failed to push Gemini Flex: ${error.message}`,
        );
      }
    },
  • Zod schemas defining the input parameters for the tool: userId, prompt, model, altText. Used in server.tool call for input validation.
    register(server: McpServer) {
      const userIdSchema = z
        .string()
        .default(this.destinationId)
        .describe(
          "The user ID to receive a message. Defaults to DESTINATION_USER_ID.",
        );
    
      const modelSchema = z
        .string()
        .default("gemini-2.0-flash")
        .describe("Gemini model name, e.g., gemini-2.0-flash");
    
      const promptSchema = z
        .string()
        .min(1)
        .describe("Describe the Flex card you want.");
    
      const altTextSchema = z
        .string()
        .default("Generated card")
        .describe("Alternative text for Flex message.");
    
      server.tool(
        "push_gemini_flex",
        "Generate a LINE Flex message (bubble/carousel) from a natural language prompt using Gemini, then push it to a user.",
        {
          userId: userIdSchema,
          prompt: promptSchema,
          model: modelSchema,
          altText: altTextSchema,
        },
  • The server.tool call within the register method that registers the 'push_gemini_flex' tool with name, description, schema, and handler.
    server.tool(
      "push_gemini_flex",
      "Generate a LINE Flex message (bubble/carousel) from a natural language prompt using Gemini, then push it to a user.",
      {
        userId: userIdSchema,
        prompt: promptSchema,
        model: modelSchema,
        altText: altTextSchema,
      },
      async ({ userId, prompt, model, altText }) => {
        if (!userId) return createErrorResponse(NO_USER_ID_ERROR);
    
        const apiKey = process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY;
        if (!apiKey) {
          return createErrorResponse(
            "Please set GEMINI_API_KEY (or GOOGLE_API_KEY) in environment variables.",
          );
        }
    
        try {
          async function callGeminiOnce(
            modelName: string,
            apiVersion: "v1" | "v1beta",
          ) {
            const endpoint = `https://generativelanguage.googleapis.com/${apiVersion}/models/${encodeURIComponent(
              modelName,
            )}:generateContent`;
            const body = {
              contents: [
                {
                  role: "user",
                  parts: [
                    {
                      text:
                        `You are an assistant that outputs only JSON for LINE Flex Message 'contents'.\n` +
                        `Return a valid 'contents' object (type: 'bubble' or 'carousel'). Do not include markdown or explanations.\n` +
                        `Keep text short. Avoid unsupported fields.\n\n` +
                        `Requirement: ${prompt}`,
                    },
                  ],
                },
              ],
            };
            const res = await fetch(endpoint, {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
                "X-goog-api-key": apiKey,
              },
              body: JSON.stringify(body),
            });
            return res;
          }
    
          const tryModels: string[] = [model];
          if (!model.endsWith("-latest")) tryModels.push(`${model}-latest`);
          for (const m of [
            "gemini-2.0-flash",
            "gemini-2.0-flash-latest",
            "gemini-1.5-flash-latest",
          ]) {
            if (!tryModels.includes(m)) tryModels.push(m);
          }
    
          let res: Response | undefined;
          let lastErr = "";
          for (const m of tryModels) {
            for (const ver of ["v1", "v1beta"] as const) {
              res = await callGeminiOnce(m, ver);
              if (res.ok) break;
              lastErr = await res.text();
              if (res.status !== 404) break;
            }
            if (res?.ok) break;
          }
          if (!res || !res.ok) {
            return createErrorResponse(
              `Gemini API error: HTTP ${res?.status} ${res?.statusText} - ${lastErr}`,
            );
          }
    
          const data = (await res.json()) as GenerateContentResponse;
          const raw =
            data?.candidates?.[0]?.content?.parts
              ?.map(p => p.text || "")
              .join("") || "";
          if (!raw)
            return createErrorResponse(
              data?.error?.message || "Empty result from Gemini",
            );
    
          // Extract plain JSON even if wrapped with ```json fences or extra text
          const fence = raw.match(/```(?:json)?\s*([\s\S]*?)```/i);
          let jsonText = fence ? fence[1].trim() : raw;
          if (!fence) {
            const s = raw.indexOf("{");
            const e = raw.lastIndexOf("}");
            if (s !== -1 && e !== -1 && e > s) jsonText = raw.slice(s, e + 1);
          }
    
          let contents: unknown;
          try {
            contents = JSON.parse(jsonText);
          } catch (e1: any) {
            // Attempt a light sanitization (remove trailing commas) then parse again
            try {
              const sanitized = jsonText.replace(/,\s*([}\]])/g, "$1");
              contents = JSON.parse(sanitized);
            } catch (e2: any) {
              return createErrorResponse(
                `Failed to parse Flex contents JSON from Gemini: ${e1?.message || e1}`,
              );
            }
          }
    
          const msg = { type: "flex", altText, contents };
          const parsed = flexMessageSchema.safeParse(msg);
          if (!parsed.success) {
            return createErrorResponse(
              `Generated Flex invalid: ${parsed.error.issues.map(i => i.message).join(", ")}`,
            );
          }
    
          const response = await this.client.pushMessage({
            to: userId,
            messages: [parsed.data as unknown as messagingApi.Message],
          });
          return createSuccessResponse(response);
        } catch (error: any) {
          return createErrorResponse(
            `Failed to push Gemini Flex: ${error.message}`,
          );
        }
      },
    );
  • src/index.ts:72-72 (registration)
    Instantiation and registration of the PushGeminiFlex tool instance on the MCP server in the main entry point.
    new PushGeminiFlex(messagingApiClient, destinationId).register(server);
Behavior2/5

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

With no annotations provided, the description carries full burden but lacks behavioral details. It mentions generation and pushing but doesn't disclose error handling, rate limits, authentication needs, whether messages are queued or sent immediately, or what happens if generation fails. The description doesn't contradict annotations (none exist), but provides minimal behavioral context.

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, well-structured sentence that efficiently conveys the core functionality: generation using Gemini from natural language, then pushing to a user. Every word earns its place with zero waste or redundancy.

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

Completeness3/5

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

For a 4-parameter tool with no annotations and no output schema, the description is minimally complete. It covers the what (generate+push) but lacks details about behavioral aspects, error cases, or output format. Given the complexity of a two-step operation (Gemini generation + LINE push), more context about how these integrate would be helpful.

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 parameters thoroughly. The description adds no additional parameter semantics beyond what's in the schema (e.g., doesn't explain prompt formatting best practices, model selection implications, or altText usage scenarios). 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.

Purpose5/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 with specific verbs ('Generate' and 'push') and resources ('LINE Flex message' and 'user'), distinguishing it from siblings like push_gemini_text (text only) and push_flex_message (no Gemini generation). It explicitly mentions using Gemini for generation from natural language, which is unique among push tools.

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

Usage Guidelines3/5

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

The description implies usage context (when you want to generate and push a Flex message using Gemini), but doesn't explicitly state when to use this vs alternatives like push_flex_message (manual Flex creation) or push_gemini_text (text-only Gemini output). No exclusions or prerequisites are mentioned.

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/tndfame/mcp_management'

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