### Docker Installation and Setup Source: https://github.com/am0y/mcp-fal/blob/master/README.md Instructions for setting up the MCP Fal.ai server using Docker. This involves cloning the repository, copying the environment template, and starting the server with docker-compose. ```bash git clone https://github.com/am0y/mcp-fal.git cd mcp-fal ``` ```bash cp .env.example .env # Edit .env and add your fal.ai API key ``` ```bash docker-compose up -d ``` -------------------------------- ### Install Dependencies and Run Server Source: https://context7.com/am0y/mcp-fal/llms.txt Instructions for setting up the project dependencies, configuring the API key, and running the MCP server. Ensure you are in a virtual environment before installation. ```bash python -m venv venv virtual/bin/pip install -r requirements.txt # Linux/Mac # venv/Scripts/pip install -r requirements.txt # Windows export FAL_KEY="your_fal_api_key_here" # OR create a .env file echo "FAL_KEY=your_fal_api_key_here" > .env virtual/bin/python main.py fastmcp dev main.py ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/am0y/mcp-fal/blob/master/README.md Clone the project repository and install necessary dependencies using pip within a virtual environment. Ensure you are using the correct pip command for your operating system. ```bash git clone https://github.com/am0y/mcp-fal.git cd mcp-fal ``` ```bash python -m venv venv virtual/Scripts/pip install -r requirements.txt # Windows # OR virtual/bin/pip install -r requirements.txt # Linux/Mac ``` -------------------------------- ### Run Docker Container (Experimental) Source: https://github.com/am0y/mcp-fal/blob/master/README.md Starts the Docker container in detached mode. Note that this setup is experimental and will exit immediately for MCP integration due to lack of stdin connection. ```bash docker-compose up -d ``` -------------------------------- ### Install Dependencies in Virtual Environment Source: https://github.com/am0y/mcp-fal/blob/master/README.md Install project dependencies using pip within the activated virtual environment. Use the correct path to pip based on your operating system. ```bash # Windows virtual\Scripts\pip install -r requirements.txt # Linux/Mac virtual/bin/pip install -r requirements.txt ``` -------------------------------- ### Build Docker Image Source: https://github.com/am0y/mcp-fal/blob/master/README.md Builds the Docker image using docker-compose. Ensure you have docker-compose installed. ```bash docker-compose build ``` -------------------------------- ### Claude Desktop MCP Server Configuration Source: https://context7.com/am0y/mcp-fal/llms.txt Configuration example for Claude Desktop to connect to the fal.ai MCP server. Replace placeholders with your actual paths and API key. ```json { "mcpServers": { "fal": { "command": "/absolute/path/to/mcp-fal/venv/bin/python", "args": ["/absolute/path/to/mcp-fal/main.py"], "env": { "FAL_KEY": "your_fal_api_key_here" } } } } ``` -------------------------------- ### Run FastMCP Dev Mode Source: https://github.com/am0y/mcp-fal/blob/master/README.md Launch the MCP Inspector web interface for interactive testing of tools. This command starts the server in development mode. ```bash fastmcp dev main.py ``` -------------------------------- ### Get Model OpenAPI Schema Source: https://context7.com/am0y/mcp-fal/llms.txt Fetches the OpenAPI schema for a specific model to understand its input parameters and output fields. This example demonstrates direct usage with `public_request`. ```python import asyncio from api.utils import public_request from api.config import FAL_BASE_URL async def example(): model_id = "fal-ai/flux/dev" url = f"{FAL_BASE_URL}/openapi/queue/openapi.json?endpoint_id={model_id}" schema = await public_request(url) # Inspect input properties input_props = schema["components"]["schemas"]["Input"]["properties"] for param, meta in input_props.items(): print(f"{param}: {meta.get('type', 'unknown')}" — {meta.get('description', '')}) asyncio.run(example()) ``` -------------------------------- ### List Available Models Source: https://context7.com/am0y/mcp-fal/llms.txt Fetches a paginated list of publicly available models on fal.ai. Use 'page' and 'total' parameters for pagination. This example demonstrates direct usage via `public_request`. ```python import asyncio from api.utils import public_request from api.config import FAL_BASE_URL async def example(): # Fetch page 1 with 10 models per page url = f"{FAL_BASE_URL}/models?page=1&total=10" result = await public_request(url) for model in result: print(model["model_id"], "- ", model.get("description", "")) asyncio.run(example()) ``` -------------------------------- ### Search Models by Keywords Source: https://context7.com/am0y/mcp-fal/llms.txt Searches the fal.ai model catalog using keywords. Returns a filtered list of models matching the query. This example shows direct usage with `public_request`. ```python import asyncio from api.utils import public_request from api.config import FAL_BASE_URL async def example(): keywords = "image generation flux" url = f"{FAL_BASE_URL}/models?keywords={keywords}" results = await public_request(url) print(f"Found {len(results)} models:") for model in results: print(" -", model["model_id"]) asyncio.run(example()) ``` -------------------------------- ### Get Model OpenAPI Schema Source: https://context7.com/am0y/mcp-fal/llms.txt Fetches the full OpenAPI schema for a specific model, describing all accepted input parameters and output fields. ```APIDOC ## GET /openapi/queue/openapi.json?endpoint_id={model_id} ### Description Fetches the full OpenAPI schema for a specific model, describing all accepted input parameters and output fields. ### Method GET ### Endpoint /openapi/queue/openapi.json #### Query Parameters - **endpoint_id** (string) - Required - The unique identifier of the model. ### Response #### Success Response (200) - **components.schemas.Input.properties** (object) - Describes the input parameters for the model. - **param_name** (type) - Description of the parameter. ### Request Example ```python import asyncio from api.utils import public_request from api.config import FAL_BASE_URL async def example(): model_id = "fal-ai/flux/dev" url = f"{FAL_BASE_URL}/openapi/queue/openapi.json?endpoint_id={model_id}" schema = await public_request(url) # Inspect input properties input_props = schema["components"]["schemas"]["Input"]["properties"] for param, meta in input_props.items(): print(f"{param}: {meta.get('type', 'unknown')}"  "  {meta.get('description', '')}) asyncio.run(example()) ``` ### Response Example ```json { "openapi": "3.0.0", "info": { "title": "fal-ai/flux/dev", "version": "1.0.0" }, "components": { "schemas": { "Input": { "type": "object", "properties": { "prompt": { "type": "string", "description": "The text prompt to generate an image from." }, "image_size": { "type": "string", "description": "The size of the generated image." }, "num_inference_steps": { "type": "integer", "description": "Number of denoising steps." }, "guidance_scale": { "type": "number", "description": "Classifier-free guidance scale." }, "num_images": { "type": "integer", "description": "Number of images to generate." }, "seed": { "type": "integer", "description": "Random seed for reproducibility." } } } } } } ``` ``` -------------------------------- ### Configure .env file for API Key Source: https://github.com/am0y/mcp-fal/blob/master/README.md Create a .env file in the project root and add your fal.ai API key. This file is used to load environment variables for the server. ```bash cp .env.example .env ``` ```dotenv FAL_KEY=your_actual_fal_api_key_here ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/am0y/mcp-fal/blob/master/README.md Steps to create a Python virtual environment and activate it. This isolates project dependencies. Use the appropriate activation command for your operating system. ```bash # Create virtual environment python -m venv venv # Activate it (optional, for manual testing) virtual\Scripts\activate # Windows source venv/bin/activate # Linux/Mac ``` -------------------------------- ### Upload a File to fal.ai CDN Source: https://context7.com/am0y/mcp-fal/llms.txt Uploads a local file to fal.ai's CDN using a two-step initiate-then-PUT process. Returns a `file_url` for use as model input. Ensure the file exists before attempting to upload. ```python import asyncio from api.utils import authenticated_request, FalAPIError from api.config import FAL_REST_URL import mimetypes, os import aiofiles, httpx async def example(): path = "/home/user/images/my_photo.jpg" if not os.path.exists(path): raise FileNotFoundError(f"File not found: {path}") filename = os.path.basename(path) file_size = os.path.getsize(path) content_type = mimetypes.guess_type(path)[0] or "application/octet-stream" # Step 1: Initiate upload initiate_url = f"{FAL_REST_URL}/storage/upload/initiate?storage_type=fal-cdn-v3" initiate_response = await authenticated_request( url=initiate_url, method="POST", json_data={"content_type": content_type, "file_name": filename} ) file_url = initiate_response["file_url"] upload_url = initiate_response["upload_url"] # Step 2: PUT the file bytes to the presigned URL async with aiofiles.open(path, "rb") as f: file_content = await f.read() async with httpx.AsyncClient() as client: resp = await client.put(upload_url, content=file_content, headers={"Content-Type": content_type}) resp.raise_for_status() print("Uploaded file URL:", file_url) print("File name:", filename) print("File size (bytes):", file_size) # Expected output: # Uploaded file URL: https://v3.fal.media/files/abc123/my_photo.jpg # File name: my_photo.jpg # File size (bytes): 204800 asyncio.run(example()) ``` -------------------------------- ### Configure Claude Desktop for MCP Server Source: https://github.com/am0y/mcp-fal/blob/master/README.md JSON configuration for Claude Desktop to connect to the fal.ai MCP server. Specify the command, arguments, and environment variables, including the API key. ```json { "mcpServers": { "fal": { "command": "d:/Projects/python/mcp-fal/venv/Scripts/python.exe", "args": ["d:/Projects/python/mcp-fal/main.py"], "env": { "FAL_KEY": "your_fal_api_key_here" } } } } ``` -------------------------------- ### Configure Linux/Mac MCP Clients Source: https://github.com/am0y/mcp-fal/blob/master/README.md JSON configuration for MCP clients on Linux or Mac to connect to the fal.ai MCP server. Ensure the paths to the Python interpreter and main script are correct for your system. ```json { "mcpServers": { "fal": { "command": "/absolute/path/to/mcp-fal/venv/bin/python", "args": ["/absolute/path/to/mcp-fal/main.py"], "env": { "FAL_KEY": "your_fal_api_key_here" } } } } ``` -------------------------------- ### upload — Upload a File to fal.ai CDN Source: https://context7.com/am0y/mcp-fal/llms.txt Uploads a local file to fal.ai's CDN (fal-cdn-v3) using a two-step initiate-then-PUT process. This returns a `file_url` that can be used as an input for models requiring file or image data. ```APIDOC ## `upload` — Upload a File to fal.ai CDN Uploads a local file to fal.ai's CDN (fal-cdn-v3) via a two-step initiate-then-PUT flow. Returns a `file_url` that can be passed as an input parameter to models requiring image or file inputs. ```python import asyncio from api.utils import authenticated_request, FalAPIError from api.config import FAL_REST_URL import mimetypes, os import aiofiles, httpx async def example(): path = "/home/user/images/my_photo.jpg" if not os.path.exists(path): raise FileNotFoundError(f"File not found: {path}") filename = os.path.basename(path) file_size = os.path.getsize(path) content_type = mimetypes.guess_type(path)[0] or "application/octet-stream" # Step 1: Initiate upload initiate_url = f"{FAL_REST_URL}/storage/upload/initiate?storage_type=fal-cdn-v3" initiate_response = await authenticated_request( url=initiate_url, method="POST", json_data={"content_type": content_type, "file_name": filename} ) file_url = initiate_response["file_url"] upload_url = initiate_response["upload_url"] # Step 2: PUT the file bytes to the presigned URL async with aiofiles.open(path, "rb") as f: file_content = await f.read() async with httpx.AsyncClient() as client: resp = await client.put(upload_url, content=file_content, headers={"Content-Type": content_type}) resp.raise_for_status() print("Uploaded file URL:", file_url) print("File name:", filename) print("File size (bytes):", file_size) # Expected output: # Uploaded file URL: https://v3.fal.media/files/abc123/my_photo.jpg # File name: my_photo.jpg # File size (bytes): 204800 asyncio.run(example()) ``` ``` -------------------------------- ### Set Fal.ai API Key Source: https://github.com/am0y/mcp-fal/blob/master/README.md Set your fal.ai API key as an environment variable. This is crucial for the server to authenticate with fal.ai services. ```bash export FAL_KEY="YOUR_FAL_API_KEY_HERE" ``` -------------------------------- ### List Available Models Source: https://context7.com/am0y/mcp-fal/llms.txt Retrieves a paginated list of all publicly available models on fal.ai. Use the `page` and `total` parameters to control pagination. ```APIDOC ## GET /models ### Description Retrieves a paginated list of all publicly available models on fal.ai. ### Method GET ### Endpoint /models #### Query Parameters - **page** (integer) - Optional - The page number to retrieve. - **total** (integer) - Optional - The number of models to return per page. ### Response #### Success Response (200) - **model_id** (string) - The unique identifier for the model. - **description** (string) - A brief description of the model. ### Request Example ```python import asyncio from api.utils import public_request from api.config import FAL_BASE_URL async def example(): # Fetch page 1 with 10 models per page url = f"{FAL_BASE_URL}/models?page=1&total=10" result = await public_request(url) for model in result: print(model["model_id"], "-", model.get("description", "")) asyncio.run(example()) ``` ### Response Example ```json [ { "model_id": "fal-ai/flux/dev", "description": "FLUX.1 [dev] is a 12B parameter flow transformer ..." }, { "model_id": "fal-ai/stable-diffusion-v3-medium", "description": "Stable Diffusion 3 Medium ..." } ] ``` ``` -------------------------------- ### Directly Execute MCP Server Source: https://github.com/am0y/mcp-fal/blob/master/README.md Run the MCP server directly. This mode is used for local testing and will wait for stdio input from MCP clients. Use the Python interpreter from your virtual environment. ```bash venv/Scripts/python main.py # Windows virtual/bin/python main.py # Linux/Mac ``` -------------------------------- ### Generate Content Directly or Queued Source: https://context7.com/am0y/mcp-fal/llms.txt Use this function to generate content with a model. Set `queue=False` for direct execution or `queue=True` for asynchronous processing. ```python import asyncio from api.utils import authenticated_request, sanitize_parameters from api.config import FAL_DIRECT_URL, FAL_QUEUE_URL async def example_direct(): model = "fal-ai/flux/schnell" parameters = { "prompt": "A photorealistic sunset over a mountain lake, cinematic lighting", "image_size": "landscape_16_9", "num_inference_steps": 4, "num_images": 1, "seed": 42 } url = f"{FAL_DIRECT_URL}/{model}" result = await authenticated_request(url, method="POST", json_data=sanitize_parameters(parameters)) print("Generated image URL:", result["images"][0]["url"]) # Expected output: # Generated image URL: https://fal.media/files/abc123/output.jpg async def example_queued(): model = "fal-ai/flux/dev" parameters = { "prompt": "An oil painting of a futuristic city at dawn", "image_size": "square_hd", "num_inference_steps": 28 } url = f"{FAL_QUEUE_URL}/{model}" result = await authenticated_request(url, method="POST", json_data=sanitize_parameters(parameters)) # Queue response contains management URLs print("Status URL:", result.get("status_url")) print("Result URL:", result.get("response_url")) print("Cancel URL:", result.get("cancel_url")) # Expected output: # Status URL: https://queue.fal.run/fal-ai/flux/dev/requests/req_xyz/status # Result URL: https://queue.fal.run/fal-ai/flux/dev/requests/req_xyz # Cancel URL: https://queue.fal.run/fal-ai/flux/dev/requests/req_xyz/cancel asyncio.run(example_direct()) asyncio.run(example_queued()) ``` -------------------------------- ### generate Source: https://context7.com/am0y/mcp-fal/llms.txt Generates content using a specified Fal.ai model. Supports both synchronous (direct execution) and asynchronous (queued) modes. For queued tasks, it returns management URLs for status checking, result retrieval, and cancellation. ```APIDOC ## `generate` — Generate Content with a Model Runs a fal.ai model either synchronously (direct execution) or asynchronously (queued). Set `queue=False` (default) for immediate results or `queue=True` for long-running tasks that return a set of queue management URLs. ### Request Body (Direct Execution) - **model** (string) - Required - The identifier of the Fal.ai model to use (e.g., "fal-ai/flux/schnell"). - **parameters** (object) - Required - A dictionary of parameters specific to the model. - **prompt** (string) - Required - The text prompt for content generation. - **image_size** (string) - Optional - The desired size of the generated image (e.g., "landscape_16_9", "square_hd"). - **num_inference_steps** (integer) - Optional - The number of inference steps to perform. - **num_images** (integer) - Optional - The number of images to generate. - **seed** (integer) - Optional - A seed for reproducible results. ### Request Body (Queued Execution) - **model** (string) - Required - The identifier of the Fal.ai model to use (e.g., "fal-ai/flux/dev"). - **parameters** (object) - Required - A dictionary of parameters specific to the model. - **prompt** (string) - Required - The text prompt for content generation. - **image_size** (string) - Optional - The desired size of the generated image (e.g., "landscape_16_9", "square_hd"). - **num_inference_steps** (integer) - Optional - The number of inference steps to perform. ### Response (Direct Execution) - **images** (array) - Contains a list of generated images. - **url** (string) - The URL of the generated image. ### Response (Queued Execution) - **status_url** (string) - URL to check the status of the queued request. - **response_url** (string) - URL to retrieve the result once the request is complete. - **cancel_url** (string) - URL to cancel the queued request. ``` -------------------------------- ### Search Models by Keywords Source: https://context7.com/am0y/mcp-fal/llms.txt Searches the fal.ai model catalog using one or more keywords. Returns a filtered list of models whose metadata matches the query. ```APIDOC ## GET /models?keywords={keywords} ### Description Searches the fal.ai model catalog using one or more keywords. Returns a filtered list of models whose metadata matches the query. ### Method GET ### Endpoint /models #### Query Parameters - **keywords** (string) - Required - One or more keywords to search for. ### Response #### Success Response (200) - **model_id** (string) - The unique identifier for the model. ### Request Example ```python import asyncio from api.utils import public_request from api.config import FAL_BASE_URL async def example(): keywords = "image generation flux" url = f"{FAL_BASE_URL}/models?keywords={keywords}" results = await public_request(url) print(f"Found {len(results)} models:") for model in results: print(" -", model["model_id"]) asyncio.run(example()) ``` ### Response Example ```json [ { "model_id": "fal-ai/flux/dev" }, { "model_id": "fal-ai/flux/schnell" } ] ``` ``` -------------------------------- ### Structured API Error Handling with FalAPIError Source: https://context7.com/am0y/mcp-fal/llms.txt Handles fal.ai API errors using a custom `FalAPIError` exception. This allows for fine-grained error management by accessing the HTTP status code, the error message, and detailed error information. ```python from api.utils import authenticated_request, FalAPIError import asyncio async def example(): try: # Attempt to use an invalid model ID result = await authenticated_request( "https://fal.run/fal-ai/nonexistent-model", method="POST", json_data={"prompt": "test"} ) except FalAPIError as e: print(f"Status code : {e.status_code}") # e.g. 404 print(f"Message : {e}") # e.g. [404] API error: {'detail': 'Not found'} print(f"Details : {e.details}") # e.g. {'detail': 'Not found'} except Exception as e: print(f"Unexpected error: {e}") asyncio.run(example()) ``` -------------------------------- ### result Source: https://context7.com/am0y/mcp-fal/llms.txt Fetches the final output of a completed queued request using the `response_url` obtained from a `generate` call with `queue=True`. This should only be called after the request status indicates completion. ```APIDOC ## `result` — Retrieve a Queued Result Fetches the final output of a completed queued request using the `response_url` returned by a queued `generate` call. Should be called only after `status` reports the request is complete. ### Endpoint `GET [response_url]` ### Parameters #### Path Parameters - **response_url** (string) - Required - The URL to retrieve the result of the completed queued request. ### Response - **images** (array) - Contains a list of generated images. - **url** (string) - The URL of the generated image. - **width** (integer) - The width of the generated image. - **height** (integer) - The height of the generated image. ``` -------------------------------- ### FalAPIError — Structured API Error Handling Source: https://context7.com/am0y/mcp-fal/llms.txt A custom exception class for handling fal.ai API errors. It includes the HTTP status code and parsed error details, allowing for specific error management in client applications. ```APIDOC ## `FalAPIError` — Structured API Error Handling A custom exception class used throughout the server to surface fal.ai API errors with an HTTP status code and a parsed error details dictionary, enabling fine-grained error handling in client code. ```python from api.utils import authenticated_request, FalAPIError import asyncio async def example(): try: # Attempt to use an invalid model ID result = await authenticated_request( "https://fal.run/fal-ai/nonexistent-model", method="POST", json_data={"prompt": "test"} ) except FalAPIError as e: print(f"Status code : {e.status_code}") # e.g. 404 print(f"Message : {e}") # e.g. [404] API error: {'detail': 'Not found'} print(f"Details : {e.details}") # e.g. {'detail': 'Not found'} except Exception as e: print(f"Unexpected error: {e}") asyncio.run(example()) ``` ``` -------------------------------- ### Retrieve a Queued Result Source: https://context7.com/am0y/mcp-fal/llms.txt Fetches the final output of a completed queued request using the `response_url`. Call this only after the `status` indicates completion. ```python import asyncio from api.utils import authenticated_request async def example(): response_url = "https://queue.fal.run/fal-ai/flux/dev/requests/req_xyz" result = await authenticated_request(response_url) for img in result.get("images", []): print("Image URL:", img["url"]) print("Dimensions:", img.get("width"), "x", img.get("height")) # Expected output: # Image URL: https://fal.media/files/req_xyz/output.jpg # Dimensions: 1024 x 1024 asyncio.run(example()) ``` -------------------------------- ### status Source: https://context7.com/am0y/mcp-fal/llms.txt Polls the current status of a queued generation request using the `status_url` obtained from a `generate` call with `queue=True`. ```APIDOC ## `status` — Check Queue Request Status Polls the current status of a queued generation request using the `status_url` returned by a queued `generate` call. ### Endpoint `GET [status_url]` ### Parameters #### Path Parameters - **status_url** (string) - Required - The URL to poll for the status of the queued request. ### Response - **status** (string) - The current status of the request (e.g., "IN_QUEUE", "IN_PROGRESS", "COMPLETED", "FAILED"). - **queue_position** (integer) - The current position of the request in the queue. 0 if actively processing. ``` -------------------------------- ### cancel Source: https://context7.com/am0y/mcp-fal/llms.txt Cancels a pending or in-progress queued request using the `cancel_url` obtained from a `generate` call with `queue=True`. This operation sends an HTTP PUT request. ```APIDOC ## `cancel` — Cancel a Queued Request Cancels an in-progress or pending queued request using the `cancel_url` returned by a queued `generate` call. Sends an HTTP PUT request. ### Endpoint `PUT [cancel_url]` ### Parameters #### Path Parameters - **cancel_url** (string) - Required - The URL to cancel the queued request. ### Response - **status** (string) - The result of the cancellation request (e.g., "CANCELLED"). ``` -------------------------------- ### Check Queue Request Status Source: https://context7.com/am0y/mcp-fal/llms.txt Polls the status of a queued generation request using the `status_url` from a `generate` call. Useful for monitoring long-running tasks. ```python import asyncio from api.utils import authenticated_request async def example(): status_url = "https://queue.fal.run/fal-ai/flux/dev/requests/req_xyz/status" status = await authenticated_request(status_url) print("Status:", status.get("status")) print("Queue position:", status.get("queue_position")) # Expected output (while pending): # Status: IN_QUEUE # Queue position: 3 # Expected output (when running): # Status: IN_PROGRESS # Queue position: 0 asyncio.run(example()) ``` -------------------------------- ### Cancel a Queued Request Source: https://context7.com/am0y/mcp-fal/llms.txt Cancels an in-progress or pending queued request using the `cancel_url`. This sends an HTTP PUT request to the specified URL. ```python import asyncio from api.utils import authenticated_request async def example(): cancel_url = "https://queue.fal.run/fal-ai/flux/dev/requests/req_xyz/cancel" result = await authenticated_request(cancel_url, method="PUT") print("Cancellation result:", result) # Expected output: # Cancellation result: {"status": "CANCELLED"} asyncio.run(example()) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.