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,
    }

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