### Setup Source: https://github.com/prefecthq/fastmcp/blob/main/examples/tasks/README.md Commands to set up the FastMCP environment and start the server. ```bash # From the fastmcp root directory uv sync # Start Redis cd examples/tasks docker compose up -d # Load environment (or source .envrc manually) direnv allow # Run the server fastmcp run server.py ``` -------------------------------- ### Start the server Source: https://github.com/prefecthq/fastmcp/blob/main/examples/skills/README.md Command to start the MCP server. ```bash uv run python examples/skills/server.py ``` -------------------------------- ### Install Optional Dependencies Source: https://github.com/prefecthq/fastmcp/blob/main/docs/getting-started/installation.mdx Example of installing an optional extra, such as for background tasks. ```bash pip install "fastmcp[tasks]" ``` -------------------------------- ### Comprehensive `fastmcp install` examples Source: https://github.com/prefecthq/fastmcp/blob/main/docs/cli/install-mcp.mdx Various examples showcasing different `fastmcp install` options, including basic installation, using `fastmcp.json`, specifying entrypoints, server names, dependencies, environment variables, Python versions, and custom config paths. ```bash # Basic install with auto-detected server instance fastmcp install claude-desktop server.py # Install from fastmcp.json with auto-detection fastmcp install claude-desktop # Explicit entrypoint with dependencies fastmcp install claude-desktop server.py:my_server \ --server-name "My Analysis Server" \ --with pandas # With environment variables fastmcp install claude-code server.py \ --env API_KEY=secret \ --env DEBUG=true # With env file fastmcp install cursor server.py --env-file .env # Specific Python version and requirements file fastmcp install claude-desktop server.py \ --python 3.11 \ --with-requirements requirements.txt # With custom config path (claude-desktop only) fastmcp install claude-desktop server.py \ --config-path "C:\Users\username\AppData\Local\Packages\Claude_xyz\LocalCache\Roaming\Claude" ``` -------------------------------- ### fastmcp install command examples with options Source: https://github.com/prefecthq/fastmcp/blob/main/docs/patterns/cli.mdx Examples demonstrating how to use `fastmcp install` with various options like custom server names, dependencies, environment variables, and different entrypoint configurations. ```bash # Auto-detects server entrypoint (looks for 'mcp', 'server', or 'app') fastmcp install claude-desktop server.py # Install with fastmcp.json configuration (auto-detects) fastmcp install claude-desktop # Install with explicit fastmcp.json file fastmcp install claude-desktop my-config.fastmcp.json # Uses specific server entrypoint fastmcp install claude-desktop server.py:my_server # With custom name and dependencies fastmcp install claude-desktop server.py:my_server --server-name "My Analysis Server" --with pandas # Install in Claude Code with environment variables fastmcp install claude-code server.py --env API_KEY=secret --env DEBUG=true # Install in Cursor with environment variables fastmcp install cursor server.py --env API_KEY=secret --env DEBUG=true ``` -------------------------------- ### Installing with `fastmcp.json` Source: https://github.com/prefecthq/fastmcp/blob/main/docs/cli/install-mcp.mdx Examples demonstrating how to install a server using a `fastmcp.json` configuration file, either by explicitly providing the path or by auto-detection. ```bash fastmcp install claude-desktop fastmcp.json fastmcp install claude-desktop # auto-detects fastmcp.json in current directory ``` -------------------------------- ### Starting a Server Source: https://github.com/prefecthq/fastmcp/blob/main/docs/cli/running.mdx Examples of how to start a FastMCP server, pointing it at a Python file, factory function, remote URL, or config file. ```bash fastmcp run server.py fastmcp run server.py:create_server fastmcp run https://example.com/mcp fastmcp run fastmcp.json ``` -------------------------------- ### Install Smart Home MCP Server Source: https://github.com/prefecthq/fastmcp/blob/main/examples/smart_home/README.md Navigate to the example directory and install the smart home hub using the 'mcp install' command, specifying the hub script and environment file. ```bash cd examples/smart_home mcp install src/smart_home/hub.py:hub_mcp -f .env ``` -------------------------------- ### server.py Source: https://github.com/prefecthq/fastmcp/blob/main/docs/apps/quickstart.mdx Example demonstrating how to add imports, define members with additional fields, wire up a click handler, and render a detail card when a row is selected in a reactive team directory. ```python from collections import Counter from prefab_ui.actions import SetState from prefab_ui.app import PrefabApp from prefab_ui.components import ( Badge, Card, CardContent, CardHeader, Column, DataTable, DataTableColumn, Grid, H3, Row, Small, Text, ) from prefab_ui.components.charts import PieChart from prefab_ui.components.control_flow import If from prefab_ui.rx import Rx, STATE from fastmcp import FastMCP mcp = FastMCP("My First App") MEMBERS = [ {"name": "Alice Chen", "role": "Staff Engineer", "office": "San Francisco", "email": "alice@company.com", "projects": 3}, {"name": "Bob Martinez", "role": "Lead Designer", "office": "New York", "email": "bob@company.com", "projects": 5}, # ... more members ... ] OFFICE_COUNTS = [ {"office": o, "count": c} for o, c in Counter(m["office"] for m in MEMBERS).items() ] @mcp.tool(app=True) def team_directory() -> PrefabApp: """Browse the team directory.""" with PrefabApp(state={"selected": None}) as app: with Column(gap=4, css_class="p-6"): with Grid(columns=[1, 2], gap=4): PieChart( data=OFFICE_COUNTS, data_key="count", name_key="office", show_legend=True, ) DataTable( columns=[ DataTableColumn(key="name", header="Name", sortable=True), DataTableColumn(key="role", header="Role", sortable=True), DataTableColumn(key="office", header="Office", sortable=True), ], rows=MEMBERS, search=True, on_row_click=SetState("selected", Rx("$event")), ) with If(STATE.selected): with Card(): with CardHeader(): with Row(gap=2, align="center"): H3(Rx("selected.name")) Badge(Rx("selected.office")) with CardContent(): with Grid(columns=3, gap=4): with Column(gap=0): Small("Role") Text(Rx("selected.role")) with Column(gap=0): Small("Email") Text(Rx("selected.email")) with Column(gap=0): Small("Active Projects") Text(Rx("selected.projects")) return app ``` -------------------------------- ### Running the examples Source: https://github.com/prefecthq/fastmcp/blob/main/docs/apps/examples.mdx Preview any example in your browser with the dev server: ```bash pip install "fastmcp[apps]" fastmcp dev apps examples/apps/sales_dashboard/sales_dashboard_server.py ``` -------------------------------- ### Basic `fastmcp install` commands Source: https://github.com/prefecthq/fastmcp/blob/main/docs/cli/install-mcp.mdx Examples of installing a server with `fastmcp` for different clients, including specifying dependencies and editable mode. ```bash fastmcp install claude-desktop server.py fastmcp install claude-code server.py --with pandas --with matplotlib fastmcp install cursor server.py -e . ``` -------------------------------- ### Setup Source: https://github.com/prefecthq/fastmcp/blob/main/examples/apps/qr_server/README.md Commands to set up the QR server example. ```bash cd examples/apps/qr_server uv sync ``` -------------------------------- ### What You Get - CLI Usage Example Source: https://github.com/prefecthq/fastmcp/blob/main/docs/cli/generate-cli.mdx Example showing the help output for the generated CLI script, demonstrating subcommands. ```bash $ python cli.py call-tool --help Usage: weather-cli call-tool COMMAND Call a tool on the server Commands: get_forecast Get the weather forecast for a city. search_city Search for a city by name. ``` -------------------------------- ### Run the client Source: https://github.com/prefecthq/fastmcp/blob/main/examples/skills/README.md Command to run the example client. ```bash uv run python examples/skills/client.py ``` -------------------------------- ### Run the client Source: https://github.com/prefecthq/fastmcp/blob/main/examples/auth/authkit/README.md Executes the client.py script to start the client, initiating AuthKit authentication in the browser. ```python python client.py ``` -------------------------------- ### Example MCP JSON output Source: https://github.com/prefecthq/fastmcp/blob/main/docs/cli/install-mcp.mdx An example of the standard MCP configuration JSON generated by the `mcp-json` target. ```json { "server-name": { "command": "uv", "args": ["run", "--with", "fastmcp", "fastmcp", "run", "/path/to/server.py"], "env": { "API_KEY": "value" } } } ``` -------------------------------- ### Start the server Source: https://github.com/prefecthq/fastmcp/blob/main/examples/auth/propelauth_oauth/README.md Command to run the FastMCP server with PropelAuth OAuth authentication. ```bash # From this directory uv run python server.py ``` -------------------------------- ### Run Example with `uv` Source: https://github.com/prefecthq/fastmcp/blob/main/examples/sampling/README.md Demonstrates how to execute a FastMCP example script directly using the `uv` tool. ```bash uv run examples/sampling/text.py ``` -------------------------------- ### Starting a Server with HTTP Transport Source: https://github.com/prefecthq/fastmcp/blob/main/docs/cli/running.mdx Examples of how to start a FastMCP server using HTTP transport, including specifying host and port. ```bash fastmcp run server.py --transport http fastmcp run server.py --transport http --host 0.0.0.0 --port 9000 ``` -------------------------------- ### Example Version Output Source: https://github.com/prefecthq/fastmcp/blob/main/docs/getting-started/installation.mdx Expected output when running the FastMCP version command, showing details like FastMCP, MCP, and Python versions. ```bash $ fastmcp version FastMCP version: 3.0.0 MCP version: 1.25.0 Python version: 3.12.2 Platform: macOS-15.3.1-arm64-arm-64bit FastMCP root path: ~/Developer/fastmcp ``` -------------------------------- ### Basic FastMCP Server with run() Source: https://github.com/prefecthq/fastmcp/blob/main/docs/deployment/running-server.mdx This example demonstrates the simplest way to run a FastMCP server using the run() method, ensuring it starts only when the script is executed directly. ```python from fastmcp import FastMCP mcp = FastMCP(name="MyServer") @mcp.tool def hello(name: str) -> str: return f"Hello, {name}!" if __name__ == "__main__": mcp.run() ``` -------------------------------- ### What You Get - Tool Parameter Help Source: https://github.com/prefecthq/fastmcp/blob/main/docs/cli/generate-cli.mdx Example showing the help output for a specific tool command, demonstrating typed parameters and help text. ```bash $ python cli.py call-tool get_forecast --help Usage: weather-cli call-tool get_forecast [OPTIONS] Get the weather forecast for a city. Options: --city [str] City name (required) --days [int] Number of forecast days (default: 3) ``` -------------------------------- ### Factory Function Entrypoint Source: https://github.com/prefecthq/fastmcp/blob/main/docs/cli/running.mdx Example of running a server by calling a function that returns the server instance, useful for async setup or configuration. ```bash fastmcp run server.py:create_server ``` -------------------------------- ### Run Structured Output Example Source: https://github.com/prefecthq/fastmcp/blob/main/examples/sampling/README.md Executes the `structured_output.py` example, demonstrating how to obtain validated Pydantic models from the LLM. ```bash uv run examples/sampling/structured_output.py ``` -------------------------------- ### Complete Mounted FastMCP Example Source: https://github.com/prefecthq/fastmcp/blob/main/docs/deployment/http.mdx A full implementation demonstrating a protected FastMCP server with tools, OAuth, and path-prefixed mounting. ```python from fastmcp import FastMCP from fastmcp.server.auth.providers.github import GitHubProvider from starlette.applications import Starlette from starlette.routing import Mount import uvicorn # Define routing structure ROOT_URL = "http://localhost:8000" MOUNT_PREFIX = "/api" MCP_PATH = "/mcp" # Create OAuth provider auth = GitHubProvider( client_id="your-client-id", client_secret="your-client-secret", base_url=f"{ROOT_URL}{MOUNT_PREFIX}", # issuer_url defaults to base_url - path-aware discovery works automatically ) # Create MCP server mcp = FastMCP("Protected Server", auth=auth) @mcp.tool def analyze(data: str) -> dict: return {"result": f"Analyzed: {data}"} # Create MCP app mcp_app = mcp.http_app(path=MCP_PATH) # Get discovery routes for root level well_known_routes = auth.get_well_known_routes(mcp_path=MCP_PATH) # Assemble the application app = Starlette( routes=[ *well_known_routes, Mount(MOUNT_PREFIX, app=mcp_app), ], lifespan=mcp_app.lifespan, ) if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000) ``` -------------------------------- ### Run Tool Use Example Source: https://github.com/prefecthq/fastmcp/blob/main/examples/sampling/README.md Executes the `tool_use.py` example, illustrating how to provide the LLM with tools like a calculator, time, or dice during sampling. ```bash uv run examples/sampling/tool_use.py ``` -------------------------------- ### Example editable package paths Source: https://github.com/prefecthq/fastmcp/blob/main/docs/deployment/server-configuration.mdx List of paths to packages to install in editable/development mode. Useful for local development when you want changes to be reflected immediately. Supports multiple packages for monorepo setups or shared libraries. ```json "editable": ["."] ``` ```json "editable": [".", "../shared-lib", "/path/to/another-package"] ``` -------------------------------- ### Using the FastMCP CLI Source: https://github.com/prefecthq/fastmcp/blob/main/docs/getting-started/quickstart.mdx Run the server with the HTTP transport using the FastMCP CLI. ```bash fastmcp run my_server.py:mcp --transport http --port 8000 ``` -------------------------------- ### Enable and start the FastMCP service Source: https://github.com/prefecthq/fastmcp/blob/main/docs/deployment/http.mdx Execute these commands to register the new service with systemd and start the server. This ensures the application persists across system reboots. ```bash sudo systemctl daemon-reload sudo systemctl enable fastmcp sudo systemctl start fastmcp ``` -------------------------------- ### Using the FastMCP CLI Source: https://github.com/prefecthq/fastmcp/blob/main/docs/getting-started/quickstart.mdx Run the server with the default stdio transport using the FastMCP CLI. ```bash fastmcp run my_server.py:mcp ``` -------------------------------- ### Create a FastMCP Server Source: https://github.com/prefecthq/fastmcp/blob/main/docs/getting-started/quickstart.mdx Instantiate the `FastMCP` class to create a server. ```python from fastmcp import FastMCP mcp = FastMCP("My MCP Server") ``` -------------------------------- ### Run the Server Source: https://github.com/prefecthq/fastmcp/blob/main/docs/getting-started/quickstart.mdx Run the FastMCP server using its `run()` method with different transports. ```python from fastmcp import FastMCP mcp = FastMCP("My MCP Server") @mcp.tool def greet(name: str) -> str: return f"Hello, {name}!" if __name__ == "__main__": mcp.run() ``` ```python from fastmcp import FastMCP mcp = FastMCP("My MCP Server") @mcp.tool def greet(name: str) -> str: return f"Hello, {name}!" if __name__ == "__main__": mcp.run(transport="http", port=8000) ``` -------------------------------- ### Deploying FastMCP with Uvicorn Source: https://github.com/prefecthq/fastmcp/blob/main/docs/deployment/http.mdx Use Uvicorn to serve FastMCP with basic settings or multiple workers for increased performance. Multi-worker setups require stateless mode for proper operation. ```bash # Run with basic configuration uvicorn app:app --host 0.0.0.0 --port 8000 # Run with multiple workers for production (requires stateless mode - see below) uvicorn app:app --host 0.0.0.0 --port 8000 --workers 4 ``` -------------------------------- ### Basic Server Installation Source: https://github.com/prefecthq/fastmcp/blob/main/docs/integrations/mcp-json-configuration.mdx Example of installing a basic FastMCP server. ```bash fastmcp install mcp-json dice_server.py ``` -------------------------------- ### Call Your Server Source: https://github.com/prefecthq/fastmcp/blob/main/docs/getting-started/quickstart.mdx Connect to a running FastMCP server with an asynchronous client and call a tool. ```python import asyncio from fastmcp import Client client = Client("http://localhost:8000/mcp") async def call_tool(name: str): async with client: result = await client.call_tool("greet", {"name": name}) print(result) asyncio.run(call_tool("Ford")) ``` -------------------------------- ### Create a systemd service for FastMCP Source: https://github.com/prefecthq/fastmcp/blob/main/docs/deployment/http.mdx Use this systemd unit file to manage FastMCP as a background service on Linux. Ensure the User, Group, and path variables match your specific environment setup. ```ini [Unit] Description=FastMCP Server After=network.target [Service] User=www-data Group=www-data WorkingDirectory=/opt/fastmcp ExecStart=/opt/fastmcp/.venv/bin/uvicorn app:app --host 127.0.0.1 --port 8000 Restart=always RestartSec=5 Environment="PATH=/opt/fastmcp/.venv/bin" [Install] WantedBy=multi-user.target ``` -------------------------------- ### server.py Source: https://github.com/prefecthq/fastmcp/blob/main/docs/apps/quickstart.mdx A Python tool that renders a UI using Prefab components. It includes a PieChart and a DataTable. ```python from collections import Counter from prefab_ui.app import PrefabApp from prefab_ui.components import Column, DataTable, DataTableColumn, Grid from prefab_ui.components.charts import PieChart from fastmcp import FastMCP mcp = FastMCP("My First App") @mcp.tool(app=True) def team_directory() -> PrefabApp: """Browse the team directory.""" members = [ {"name": "Alice Chen", "role": "Staff Engineer", "office": "San Francisco"}, {"name": "Bob Martinez", "role": "Lead Designer", "office": "New York"}, {"name": "Carol Johnson", "role": "Senior Engineer", "office": "London"}, {"name": "David Kim", "role": "Product Manager", "office": "San Francisco"}, {"name": "Eva Mueller", "role": "Engineer", "office": "Berlin"}, {"name": "Frank Lee", "role": "Data Scientist", "office": "San Francisco"}, {"name": "Grace Park", "role": "Engineering Manager", "office": "New York"}, ] office_counts = [ {"office": office, "count": count} for office, count in Counter(m["office"] for m in members).items() ] with PrefabApp() as app: with Column(gap=4, css_class="p-6"): with Grid(columns=[1, 2], gap=4): PieChart( data=office_counts, data_key="count", name_key="office", show_legend=True, ) DataTable( columns=[ DataTableColumn(key="name", header="Name", sortable=True), DataTableColumn(key="role", header="Role", sortable=True), DataTableColumn(key="office", header="Office", sortable=True), ], rows=members, search=True, ) return app ``` -------------------------------- ### Basic fastmcp install commands for various clients Source: https://github.com/prefecthq/fastmcp/blob/main/docs/patterns/cli.mdx Examples of using `fastmcp install` with different supported MCP clients. ```bash fastmcp install claude-code server.py fastmcp install claude-desktop server.py fastmcp install cursor server.py fastmcp install gemini-cli server.py fastmcp install goose server.py fastmcp install mcp-json server.py fastmcp install stdio server.py ``` -------------------------------- ### Add a Tool Source: https://github.com/prefecthq/fastmcp/blob/main/docs/getting-started/quickstart.mdx Register a function as a tool with the server using `@mcp.tool`. ```python from fastmcp import FastMCP mcp = FastMCP("My MCP Server") @mcp.tool def greet(name: str) -> str: return f"Hello, {name}!" ``` -------------------------------- ### FastMCP Tool with Interactive UI Source: https://github.com/prefecthq/fastmcp/blob/main/docs/getting-started/quickstart.mdx Defines a FastMCP tool named `greet` that returns a `PrefabApp` component tree, which is rendered as a visual card in the conversation. ```python from prefab_ui.app import PrefabApp from prefab_ui.components import Column, Heading, Text, Badge, Row from fastmcp import FastMCP mcp = FastMCP("My MCP Server") @mcp.tool(app=True) def greet(name: str) -> PrefabApp: """Greet someone with a visual card.""" with Column(gap=4, css_class="p-6") as view: Heading(f"Hello, {name}!") with Row(gap=2, align="center"): Text("Status") Badge("Greeted", variant="success") return PrefabApp(view=view) ``` -------------------------------- ### Start server with HTTP transport (Python) Source: https://github.com/prefecthq/fastmcp/blob/main/docs/patterns/cli.mdx Example of starting a server manually with Streamable HTTP transport by setting it in code. ```python python server.py # Assuming your __main__ block sets Streamable HTTP transport ``` -------------------------------- ### Start server with HTTP transport Source: https://github.com/prefecthq/fastmcp/blob/main/docs/patterns/cli.mdx Example of starting a server manually with Streamable HTTP transport for testing with MCP Inspector. ```bash fastmcp run server.py --transport http ``` -------------------------------- ### Install FastMCP with Anthropic and Set API Key Source: https://github.com/prefecthq/fastmcp/blob/main/examples/sampling/README.md Installs the `fastmcp` library with Anthropic dependencies and sets the `ANTHROPIC_API_KEY` environment variable for authentication. ```bash pip install fastmcp[anthropic] export ANTHROPIC_API_KEY=your-key ``` -------------------------------- ### Starting Additional Workers Source: https://github.com/prefecthq/fastmcp/blob/main/examples/tasks/README.md Commands to start additional workers for parallel task processing with Redis, including environment variable configuration. ```bash fastmcp tasks worker server.py # Configure via environment: export FASTMCP_DOCKET_CONCURRENCY=20 fastmcp tasks worker server.py ``` -------------------------------- ### Complete Background Task Example Source: https://github.com/prefecthq/fastmcp/blob/main/docs/clients/tasks.mdx A full asynchronous example demonstrating starting a background task, subscribing to updates, doing other work, and then awaiting the result. ```python import asyncio from fastmcp import Client async def main(): async with Client(server) as client: # Start background task task = await client.call_tool( "slow_computation", {"duration": 10}, task=True, ) # Subscribe to updates def on_update(status): print(f"Progress: {status.statusMessage}") task.on_status_change(on_update) # Do other work while task runs print("Doing other work...") await asyncio.sleep(2) # Wait for completion and get result result = await task.result() print(f"Result: {result.content}") asyncio.run(main()) ``` -------------------------------- ### Quick start command Source: https://github.com/prefecthq/fastmcp/blob/main/docs/apps/development.mdx Starts the development server for your app tools. ```bash fastmcp dev apps server.py ``` -------------------------------- ### Example FastAPI Application Source: https://github.com/prefecthq/fastmcp/blob/main/docs/integrations/fastapi.mdx An example e-commerce FastAPI application used throughout this guide, defining models and API endpoints for products. ```python # Copy this FastAPI server into other code blocks in this guide from fastapi import FastAPI, HTTPException from pydantic import BaseModel # Models class Product(BaseModel): name: str price: float category: str description: str | None = None class ProductResponse(BaseModel): id: int name: str price: float category: str description: str | None = None # Create FastAPI app app = FastAPI(title="E-commerce API", version="1.0.0") # In-memory database products_db = { 1: ProductResponse( id=1, name="Laptop", price=999.99, category="Electronics" ), 2: ProductResponse( id=2, name="Mouse", price=29.99, category="Electronics" ), 3: ProductResponse( id=3, name="Desk Chair", price=299.99, category="Furniture" ) } next_id = 4 @app.get("/products", response_model=list[ProductResponse]) def list_products( category: str | None = None, max_price: float | None = None ) -> list[ProductResponse]: """List all products with optional filtering.""" products = list(products_db.values()) if category: products = [p for p in products if p.category == category] if max_price: products = [p for p in products if p.price <= max_price] return products @app.get("/products/{product_id}", response_model=ProductResponse) def get_product(product_id: int): """Get a specific product by ID.""" if product_id not in products_db: raise HTTPException(status_code=404, detail="Product not found") return products_db[product_id] @app.post("/products", response_model=ProductResponse) def create_product(product: Product): """Create a new product.""" global next_id product_response = ProductResponse(id=next_id, **product.model_dump()) products_db[next_id] = product_response next_id += 1 return product_response @app.put("/products/{product_id}", response_model=ProductResponse) def update_product(product_id: int, product: Product): """Update an existing product.""" if product_id not in products_db: raise HTTPException(status_code=404, detail="Product not found") products_db[product_id] = ProductResponse( id=product_id, **product.model_dump() ) return products_db[product_id] @app.delete("/products/{product_id}") def delete_product(product_id: int): """Delete a product.""" if product_id not in products_db: raise HTTPException(status_code=404, detail="Product not found") del products_db[product_id] return {"message": "Product deleted"} ``` -------------------------------- ### Command-line arguments example Source: https://github.com/prefecthq/fastmcp/blob/main/docs/deployment/server-configuration.mdx Example of passing command-line arguments to the server. ```json "args": ["--config", "server-config.json"] ``` -------------------------------- ### Install with Explicit Object Name Source: https://github.com/prefecthq/fastmcp/blob/main/docs/integrations/claude-desktop.mdx Examples of `fastmcp install` command using `file.py:object` notation to specify the server object. ```bash # These are equivalent if your server object is named 'mcp' fastmcp install claude-desktop server.py fastmcp install claude-desktop server.py:mcp # Use explicit object name if your server has a different name fastmcp install claude-desktop server.py:my_custom_server ``` -------------------------------- ### Migrating from CLI Arguments Source: https://github.com/prefecthq/fastmcp/blob/main/docs/deployment/server-configuration.mdx An example CLI command for running a server. ```bash uv run --with pandas --with requests \ fastmcp run server.py \ --transport http \ --port 8000 \ --log-level INFO ``` -------------------------------- ### Pre-Building Environments with fastmcp project prepare Source: https://github.com/prefecthq/fastmcp/blob/main/docs/cli/running.mdx Steps to build a persistent uv project environment and then run a server using that environment. ```bash # Step 1: Build the environment (slow, does dependency resolution) fastmcp project prepare fastmcp.json --output-dir ./env # Step 2: Run using the prepared environment (fast, no install step) fastmcp run fastmcp.json --project ./env ``` -------------------------------- ### Restore pre-2.8.0 semantic mapping Source: https://github.com/prefecthq/fastmcp/blob/main/docs/integrations/openapi.mdx Example demonstrating how to define custom route maps to restore pre-2.8.0 semantic mapping for GET requests, making path parameter GET requests into ResourceTemplates and other GET requests into Resources. ```python semantic_maps = [ # GET requests with path parameters become ResourceTemplates RouteMap(methods=["GET"], pattern=r".*\{.*\}.*", mcp_type=MCPType.RESOURCE_TEMPLATE), # All other GET requests become Resources RouteMap(methods=["GET"], pattern=r".*", mcp_type=MCPType.RESOURCE), ] mcp = FastMCP.from_openapi( openapi_spec=spec, client=client, route_maps=semantic_maps, ) ``` -------------------------------- ### Manage Client Connection with Automatic Initialization Source: https://github.com/prefecthq/fastmcp/blob/main/docs/clients/client.mdx This example shows how to use a client context manager for automatic connection establishment and MCP initialization handshake, exchanging server capabilities and instructions. ```python from fastmcp import Client, FastMCP mcp = FastMCP(name="MyServer", instructions="Use the greet tool to say hello!") @mcp.tool def greet(name: str) -> str: """Greet a user by name.""" return f"Hello, {name}!" async with Client(mcp) as client: # Initialization already happened automatically print(f"Server: {client.initialize_result.server_info.name}") print(f"Instructions: {client.initialize_result.instructions}") print(f"Capabilities: {client.initialize_result.capabilities.tools}") ``` -------------------------------- ### Basic Server Setup Source: https://github.com/prefecthq/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/openapi/README.md Example demonstrating how to set up a FastMCP OpenAPI server. ```python import httpx from fastmcp.server.openapi import FastMCPOpenAPI # OpenAPI spec (can be loaded from file/URL) openapi_spec = {...} # Create HTTP client async with httpx.AsyncClient() as client: # Create server with stateless request building server = FastMCPOpenAPI( openapi_spec=openapi_spec, client=client, name="My API Server" ) # Server automatically creates RequestDirector and pre-calculates schemas ``` -------------------------------- ### FastMCP: Full Server Implementation Source: https://github.com/prefecthq/fastmcp/blob/main/docs/getting-started/upgrading/from-low-level-sdk.mdx This example demonstrates a complete server implementation using FastMCP, showcasing simplified tool, resource, and prompt definitions, and running the server directly. ```python import json from fastmcp import FastMCP mcp = FastMCP("demo") @mcp.tool def greet(name: str) -> str: """Greet someone by name""" return f"Hello, {name}!" @mcp.resource("info://version") def version() -> str: """Server version""" return json.dumps({"version": "1.0.0"}) @mcp.prompt def summarize(text: str) -> str: """Summarize text""" return f"Summarize:\n\n{text}" if __name__ == "__main__": mcp.run() ``` -------------------------------- ### Advanced Configuration Installation Source: https://github.com/prefecthq/fastmcp/blob/main/docs/integrations/mcp-json-configuration.mdx Example of installing an ML analysis server with specific Python version, requirements file, project directory, and environment variable. ```bash fastmcp install mcp-json ml_server.py \ --name "ML Analysis Server" \ --python 3.11 \ --with-requirements requirements.txt \ --project /home/user/ml-project \ --env GPU_DEVICE=0 ``` -------------------------------- ### Composition and namespacing Source: https://github.com/prefecthq/fastmcp/blob/main/docs/apps/fastmcp-app.mdx Example of mounting a server under a namespace, showing how tool names get prefixed. ```python platform = FastMCP("Platform") platform.mount("contacts", contacts_server) ``` -------------------------------- ### MCP SDK: Full Server Implementation Source: https://github.com/prefecthq/fastmcp/blob/main/docs/getting-started/upgrading/from-low-level-sdk.mdx This example shows a complete server implementation using the low-level MCP SDK, defining tools, resources, and prompts, and running the server via stdio. ```python import asyncio import json import mcp.types as types from mcp.server import Server from mcp.server.stdio import stdio_server from pydantic import AnyUrl server = Server("demo") @server.list_tools() async def list_tools() -> list[types.Tool]: return [ types.Tool( name="greet", description="Greet someone by name", inputSchema={ "type": "object", "properties": { "name": {"type": "string"} }, "required": ["name"] } ) ] @server.call_tool() async def call_tool(name: str, arguments: dict) -> list[types.TextContent]: if name == "greet": return [types.TextContent(type="text", text=f"Hello, {arguments['name']}!")] raise ValueError(f"Unknown tool: {name}") @server.list_resources() async def list_resources() -> list[types.Resource]: return [ types.Resource( uri=AnyUrl("info://version"), name="version", description="Server version" ) ] @server.read_resource() async def read_resource(uri: AnyUrl) -> str: if str(uri) == "info://version": return json.dumps({"version": "1.0.0"}) raise ValueError(f"Unknown resource: {uri}") @server.list_prompts() async def list_prompts() -> list[types.Prompt]: return [ types.Prompt( name="summarize", description="Summarize text", arguments=[ types.PromptArgument(name="text", required=True) ] ) ] @server.get_prompt() async def get_prompt( name: str, arguments: dict[str, str] | None ) -> types.GetPromptResult: if name == "summarize": return types.GetPromptResult( description="Summarize text", messages=[ types.PromptMessage( role="user", content=types.TextContent( type="text", text=f"Summarize:\n\n{(arguments or {}).get('text', '')}" ) ) ] ) raise ValueError(f"Unknown prompt: {name}") async def main(): async with stdio_server() as (read_stream, write_stream): await server.run( read_stream, write_stream, server.create_initialization_options(), ) asyncio.run(main()) ``` -------------------------------- ### Example output of `fastmcp install mcp-json` Source: https://github.com/prefecthq/fastmcp/blob/main/docs/integrations/mcp-json-configuration.mdx JSON output generated by `fastmcp install mcp-json server.py`, showing the server configuration with the server name as the root key. ```json { "My Server": { "command": "uv", "args": [ "run", "--with", "fastmcp", "fastmcp", "run", "/absolute/path/to/server.py" ] } } ``` -------------------------------- ### Development server options Source: https://github.com/prefecthq/fastmcp/blob/main/docs/apps/development.mdx Example command demonstrating various options for the development server. ```bash fastmcp dev apps server.py:mcp --mcp-port 9000 --dev-port 9090 --no-reload ``` -------------------------------- ### Getting Prompts (no arguments) Source: https://github.com/prefecthq/fastmcp/blob/main/docs/servers/transforms/prompts-as-tools.mdx Example showing how to call the `get_prompt` tool for a prompt that requires no arguments. ```python result = await client.call_tool( "get_prompt", {"name": "simple_prompt"} ) ``` -------------------------------- ### Initialize HTML App and Connect to Host Source: https://github.com/prefecthq/fastmcp/blob/main/docs/apps/low-level.mdx This JavaScript snippet shows how to initialize an HTML application using the "@modelcontextprotocol/ext-apps" SDK, set up a callback for receiving tool results, and establish a connection with the host. ```javascript ``` -------------------------------- ### Run Local Mintlify Documentation Server Source: https://github.com/prefecthq/fastmcp/blob/main/docs/development/tests.mdx Start a local Mintlify server to preview documentation changes with hot reload, ensuring accurate rendering before publication. ```bash # Start local documentation server with hot reload just docs # Or run Mintlify directly mintlify dev ``` -------------------------------- ### Remote URL Entrypoint Source: https://github.com/prefecthq/fastmcp/blob/main/docs/cli/running.mdx Example of running a server by starting a local proxy that bridges to a remote server. ```bash fastmcp run https://example.com/mcp ``` -------------------------------- ### Previewing Apps Source: https://github.com/prefecthq/fastmcp/blob/main/docs/cli/running.mdx Examples of launching a browser-based preview UI for servers with Prefab App tools, including specifying MCP and dev ports. ```bash fastmcp dev apps server.py fastmcp dev apps server.py:mcp --mcp-port 9000 --dev-port 9090 ``` -------------------------------- ### Basic Setup Source: https://github.com/prefecthq/fastmcp/blob/main/fastmcp_slim/fastmcp/contrib/component_manager/README.md Example of setting up the Component Manager with a FastMCP server. ```python from fastmcp import FastMCP from fastmcp.contrib.component_manager import set_up_component_manager mcp = FastMCP(name="Component Manager", instructions="This is a test server with component manager.") set_up_component_manager(server=mcp) ``` -------------------------------- ### Pinning FastMCP Version Source: https://github.com/prefecthq/fastmcp/blob/main/docs/getting-started/installation.mdx Example of how to pin FastMCP to an exact version for production use to prevent unintended breaking changes. ```python fastmcp==3.0.0 # Good fastmcp>=3.0.0 # Bad - may install breaking changes ``` -------------------------------- ### Requesting Background Execution Source: https://github.com/prefecthq/fastmcp/blob/main/docs/clients/tasks.mdx Demonstrates how to start a background task using client.call_tool with task=True and then track its progress and get the result. ```python from fastmcp import Client async with Client(server) as client: # Start a background task task = await client.call_tool("slow_computation", {"duration": 10}, task=True) print(f"Task started: {task.task_id}") # Do other work while it runs... # Get the result when ready result = await task.result() ``` -------------------------------- ### Initializing Generative UI Source: https://github.com/prefecthq/fastmcp/blob/main/docs/apps/generative.mdx Example showing how to initialize FastMCP and add the GenerativeUI provider. ```python from fastmcp import FastMCP from fastmcp.apps.generative import GenerativeUI mcp = FastMCP("Prefab Studio") mcp.add_provider(GenerativeUI()) ``` -------------------------------- ### Configure supporting files visibility Source: https://github.com/prefecthq/fastmcp/blob/main/examples/skills/README.md Example of setting `supporting_files` to 'resources' for `SkillsDirectoryProvider`. ```python SkillsDirectoryProvider(roots=skills_dir, supporting_files="resources") ```