Skip to main content
Glama
t0ster
by t0ster

generate_meme

Create custom memes with text overlays using pre-configured templates. Fill specific text placeholders for each meme type to generate shareable content.

Instructions

Generate a meme with custom text overlays.

Each meme type has specific named text placeholders that must be filled. Use the 'get_meme_info' tool to see available memes and their placeholder requirements.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
meme_nameYesThe type of meme to generate
textsYesDictionary like {"placeholder_name": "Your text here"}. To skip a placeholder, use an empty string explicitly.

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Primary handler function for the 'generate_meme' MCP tool. Includes registration via @mcp.tool(), input schema via Annotated/Field, validation logic, delegation to image generation helper, and response formatting.
    @mcp.tool()
    async def generate_meme(
        meme_name: Annotated[str, Field(description="The type of meme to generate")],
        texts: Annotated[
            dict[str, str],
            Field(
                description=(
                    'Dictionary like {"placeholder_name": "Your text here"}. '
                    "To skip a placeholder, use an empty string explicitly."
                )
            ),
        ],
    ) -> dict:
        """
        Generate a meme with custom text overlays.
    
        Each meme type has specific named text placeholders that must be filled.
        Use the 'get_meme_info' tool to see available memes and their placeholder requirements.
        """
        try:
            meme_configs = get_meme_configs()
            if meme_name not in meme_configs:
                return {
                    "status": "error",
                    "message": f"Unknown meme type: {meme_name}",
                    "available_memes": list(meme_configs.keys()),
                }
    
            config = meme_configs[meme_name]
            expected_keys = set(config.placeholders.keys())
            provided_keys = set(texts.keys())
    
            if provided_keys != expected_keys:
                missing = expected_keys - provided_keys
                extra = provided_keys - expected_keys
                error_parts = []
                if missing:
                    error_parts.append(f"missing: {', '.join(missing)}")
                if extra:
                    error_parts.append(f"unexpected: {', '.join(extra)}")
                msg = f"Meme '{meme_name}' placeholder mismatch. {'; '.join(error_parts)}."
                if missing:
                    msg += " To skip a placeholder, use an empty string explicitly."
                raise ValueError(msg)
    
            saved_path = generate_meme_image(meme_name, texts, get_output_dir())
    
            return {
                "status": "success",
                "message": "Meme generated successfully",
                "output_path": str(saved_path.resolve()),
                "meme_type": meme_name,
                "texts_used": texts,
            }
    
        except Exception as e:
            return {
                "status": "error",
                "message": f"Error generating meme: {str(e)}",
                "meme_type": meme_name,
            }
  • Pydantic-based input schema definition for the generate_meme tool parameters: meme_name (str) and texts (dict[str,str]) with descriptions.
    meme_name: Annotated[str, Field(description="The type of meme to generate")],
    texts: Annotated[
        dict[str, str],
        Field(
            description=(
                'Dictionary like {"placeholder_name": "Your text here"}. '
                "To skip a placeholder, use an empty string explicitly."
            )
        ),
    ],
  • app/server.py:96-96 (registration)
    FastMCP tool registration decorator applied to the generate_meme handler.
    @mcp.tool()
  • Core helper function that performs the actual meme image generation using PIL: loads template, handles fonts, text wrapping, drawing with strokes, and saves to file.
    def generate_meme_image(
        meme_type: str, texts: dict[str, str], output_dir: Path
    ) -> Path:
        """Generate a meme image with the given texts."""
        config = get_meme_configs()[meme_type]
        template_path = get_templates_dir() / config.template_file
    
        if not template_path.exists():
            raise FileNotFoundError(f"Template not found: {config.template_file}")
    
        img = Image.open(template_path)
        draw = ImageDraw.Draw(img)
    
        for name, text in texts.items():
            placeholder = config.placeholders[name]
            try:
                font = ImageFont.truetype("Impact", placeholder.font_size)
            except OSError:
                try:
                    font = ImageFont.truetype(str(get_fallback_font_path()), placeholder.font_size)
                except OSError:
                    font = ImageFont.load_default(placeholder.font_size)
    
            lines = wrap_text(draw, text, font, placeholder.max_width)
    
            anchor_map = {"left": "la", "center": "ma", "right": "ra"}
            anchor = anchor_map[placeholder.align]
    
            y_offset = placeholder.y
            for line in lines:
                bbox = draw.textbbox((0, 0), line, font=font)
                line_height = bbox[3] - bbox[1]
    
                draw.text(
                    (placeholder.x, y_offset),
                    line,
                    font=font,
                    fill=placeholder.fill,
                    stroke_width=placeholder.stroke_width,
                    stroke_fill=placeholder.stroke_fill,
                    anchor=anchor,
                )
                y_offset += line_height + int(placeholder.font_size * 0.2)
    
        output_path = output_dir / f"{int(time.time())}_{meme_type}.jpg"
        img.save(output_path, "JPEG")
        return output_path
  • Utility helper for wrapping meme text to fit within specified pixel width, used by generate_meme_image.
    def wrap_text(
        draw: ImageDraw.ImageDraw,
        text: str,
        font: ImageFont.FreeTypeFont | ImageFont.ImageFont,
        max_width: int,
    ) -> list[str]:
        """Wrap text to fit within max_width pixels."""
        lines: list[str] = []
        current_line: list[str] = []
    
        for word in text.upper().split():
            current_line.append(word)
            test_line = " ".join(current_line)
            bbox = draw.textbbox((0, 0), test_line, font=font)
            if bbox[2] - bbox[0] > max_width:
                if len(current_line) > 1:
                    current_line.pop()
                    lines.append(" ".join(current_line))
                    current_line = [word]
                else:
                    lines.append(test_line)
                    current_line = []
    
        if current_line:
            lines.append(" ".join(current_line))
    
        return lines
Behavior3/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 explains that 'Each meme type has specific named text placeholders that must be filled,' which adds context about required inputs. However, it doesn't describe what the tool returns (e.g., image URL, binary data), error conditions, or performance characteristics like rate limits or processing time.

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 appropriately sized and front-loaded: the first sentence states the core purpose, and the second provides essential usage guidance. Every sentence earns its place by adding critical information without redundancy or fluff.

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

Completeness4/5

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

Given the tool has an output schema (which handles return values), 100% schema coverage, and no annotations, the description is reasonably complete. It covers the purpose, workflow dependency, and input constraints. However, for a creation tool with no annotations, it could better address behavioral aspects like what happens on success/failure or response format hints.

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 thoroughly. The description adds some value by explaining that 'texts' is a 'Dictionary like {"placeholder_name": "Your text here"}' and mentions placeholder requirements, but this largely reiterates schema information. It doesn't provide additional syntax or format details beyond what the schema specifies.

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 a meme with custom text overlays.' It specifies the verb ('Generate') and resource ('meme'), and distinguishes it from its sibling 'get_meme_info' by focusing on creation rather than information retrieval. However, it doesn't explicitly differentiate beyond the functional contrast implied by the sibling tool name.

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

Usage Guidelines5/5

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

The description provides explicit guidance on when to use this tool versus alternatives: it directs users to 'Use the 'get_meme_info' tool to see available memes and their placeholder requirements' before invoking this tool. This creates a clear workflow dependency and distinguishes it from the sibling tool.

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/t0ster/meme-generator-mcp'

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