Skip to main content
Glama

remove_background

Remove image backgrounds to create transparent PNGs for product photos, portraits, and composite images.

Instructions

Remove the background from an image, creating a transparent PNG. Great for product photos, portraits, and creating composites.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
image_urlYesURL of the image to remove background from (use upload_file for local images)
modelNoBackground removal model. Options: fal-ai/birefnet/v2 (recommended), fal-ai/birefnetfal-ai/birefnet/v2
output_formatNoOutput format (PNG recommended for transparency)png

Implementation Reference

  • The handler function that implements the core logic for the remove_background tool. It resolves the model, calls the fal.ai API via queue_strategy, handles errors, extracts the output image URL, and returns a formatted response.
    async def handle_remove_background(
        arguments: Dict[str, Any],
        registry: ModelRegistry,
        queue_strategy: QueueStrategy,
    ) -> List[TextContent]:
        """Handle the remove_background tool."""
        model_input = arguments.get("model", "fal-ai/birefnet/v2")
        try:
            model_id = await registry.resolve_model_id(model_input)
        except ValueError as e:
            return [
                TextContent(
                    type="text",
                    text=f"❌ {e}. Use list_models to see available options.",
                )
            ]
    
        fal_args: Dict[str, Any] = {
            "image_url": arguments["image_url"],
        }
    
        # Add output format if specified (default is PNG)
        if "output_format" in arguments:
            fal_args["output_format"] = arguments["output_format"]
    
        logger.info("Starting background removal with %s", model_id)
    
        try:
            result = await asyncio.wait_for(
                queue_strategy.execute_fast(model_id, fal_args),
                timeout=60,
            )
        except asyncio.TimeoutError:
            logger.error("Background removal timed out for %s", model_id)
            return [
                TextContent(
                    type="text",
                    text="❌ Background removal timed out after 60 seconds. Please try again.",
                )
            ]
        except Exception as e:
            logger.exception("Background removal failed: %s", e)
            return [
                TextContent(
                    type="text",
                    text=f"❌ Background removal failed: {e}",
                )
            ]
    
        # Check for error in response
        if "error" in result:
            error_msg = result.get("error", "Unknown error")
            logger.error("Background removal failed for %s: %s", model_id, error_msg)
            return [
                TextContent(
                    type="text",
                    text=f"❌ Background removal failed: {error_msg}",
                )
            ]
    
        # Extract the result image URL
        # BiRefNet returns {"image": {"url": "..."}}
        image_data = result.get("image", {})
        if isinstance(image_data, dict):
            output_url = image_data.get("url")
        else:
            output_url = result.get("image_url")
    
        if not output_url:
            logger.warning("Background removal returned no image. Result: %s", result)
            return [
                TextContent(
                    type="text",
                    text="❌ Background removal completed but no image was returned.",
                )
            ]
    
        response = "✂️ Background removed successfully!\n\n"
        response += f"**Result**: {output_url}\n\n"
        response += "The image now has a transparent background (PNG format)."
        return [TextContent(type="text", text=response)]
  • The Tool schema definition specifying the input parameters, description, and validation for the remove_background tool.
        name="remove_background",
        description="Remove the background from an image, creating a transparent PNG. Great for product photos, portraits, and creating composites.",
        inputSchema={
            "type": "object",
            "properties": {
                "image_url": {
                    "type": "string",
                    "description": "URL of the image to remove background from (use upload_file for local images)",
                },
                "model": {
                    "type": "string",
                    "default": "fal-ai/birefnet/v2",
                    "description": "Background removal model. Options: fal-ai/birefnet/v2 (recommended), fal-ai/birefnet",
                },
                "output_format": {
                    "type": "string",
                    "enum": ["png", "webp"],
                    "default": "png",
                    "description": "Output format (PNG recommended for transparency)",
                },
            },
            "required": ["image_url"],
        },
    ),
  • The TOOL_HANDLERS dictionary that registers the handle_remove_background function for the 'remove_background' tool name, used by the MCP server to route tool calls.
    TOOL_HANDLERS = {
        # Utility tools (no queue needed)
        "list_models": handle_list_models,
        "recommend_model": handle_recommend_model,
        "get_pricing": handle_get_pricing,
        "get_usage": handle_get_usage,
        "upload_file": handle_upload_file,
        # Image generation tools
        "generate_image": handle_generate_image,
        "generate_image_structured": handle_generate_image_structured,
        "generate_image_from_image": handle_generate_image_from_image,
        # Image editing tools
        "remove_background": handle_remove_background,
        "upscale_image": handle_upscale_image,
        "edit_image": handle_edit_image,
        "inpaint_image": handle_inpaint_image,
        "resize_image": handle_resize_image,
        "compose_images": handle_compose_images,
        # Video tools
        "generate_video": handle_generate_video,
        "generate_video_from_image": handle_generate_video_from_image,
        "generate_video_from_video": handle_generate_video_from_video,
        # Audio tools
        "generate_music": handle_generate_music,
    }
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. It mentions the output format ('transparent PNG') and use cases, but lacks details on permissions, rate limits, error conditions, or what happens if the image_url is invalid. For a tool that modifies images, this is a significant gap in behavioral disclosure.

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 front-loaded with the core purpose in the first sentence, followed by a concise use-case example. Every sentence earns its place by adding value without redundancy, making it efficient and well-structured.

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?

Given no annotations and no output schema, the description is adequate for a simple tool but lacks completeness. It covers the basic purpose and use cases but misses details on behavioral traits, error handling, and output specifics, which are important for an image-processing tool with no structured support.

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 does not add any parameter-specific details beyond what's in the schema, such as explaining why PNG is recommended or model differences. Baseline 3 is appropriate when the 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 specific action ('Remove the background from an image') and the outcome ('creating a transparent PNG'), distinguishing it from siblings like edit_image or inpaint_image. It provides concrete use cases ('product photos, portraits, and creating composites') that help differentiate its purpose.

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 through the examples ('Great for product photos, portraits, and creating composites'), but does not explicitly state when to use this tool versus alternatives like edit_image or inpaint_image. No exclusions or prerequisites are mentioned, leaving some ambiguity about optimal use cases.

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/raveenb/fal-mcp-server'

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