### Install FastMCP and Run Dev Server
Source: https://gofastmcp.com/apps/examples
Install the FastMCP library with app support and start the development server to preview examples.
```bash
pip install "fastmcp[apps]"
fastmcp dev apps examples/apps/sales_dashboard/sales_dashboard_server.py
```
--------------------------------
### Install psutil and Run System Monitor
Source: https://gofastmcp.com/apps/examples
Install the psutil library and run the system monitor example to view live CPU, memory, and disk statistics.
```bash
pip install psutil
fastmcp dev apps examples/apps/system_monitor/system_monitor_server.py
```
--------------------------------
### Run Sales Dashboard Example
Source: https://gofastmcp.com/apps/examples
Start the development server for the sales dashboard example to visualize KPI metrics, revenue trends, and deal pipelines.
```bash
fastmcp dev apps examples/apps/sales_dashboard/sales_dashboard_server.py
```
--------------------------------
### Run Quiz Example
Source: https://gofastmcp.com/apps/examples
Start the development server for the quiz example, which demonstrates an LLM-generated trivia game with multi-turn client-side state management.
```bash
fastmcp dev apps examples/apps/quiz/quiz_server.py
```
--------------------------------
### Example Project Structure for FileSystemProvider
Source: https://gofastmcp.com/servers/providers/filesystem
Demonstrates a recommended organization for components, including tools, resources, and prompts, within a filesystem provider setup.
```text
examples/filesystem-provider/
├── server.py # Server entry point
└── components/
├── tools/
│ ├── greeting.py # greet, farewell tools
│ └── calculator.py # add, multiply tools
├── resources/
│ └── config.py # Static and templated resources
└── prompts/
└── assistant.py # code_review, explain prompts
```
--------------------------------
### FastMCP version output example
Source: https://gofastmcp.com/getting-started/installation
Example output when verifying the FastMCP installation.
```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
```
--------------------------------
### Complete UVEnvironment Configuration Example
Source: https://gofastmcp.com/deployment/server-configuration
An example demonstrating the full configuration for a Python environment using uv, including version constraints, dependencies, and editable installs.
```json
"environment": {
"type": "uv",
"python": ">=3.10",
"dependencies": ["pandas", "numpy"],
"editable": ["./"]
}
```
--------------------------------
### Complete Server Authentication Example
Source: https://gofastmcp.com/integrations/anthropic
A full example demonstrating server-side authentication setup, including key generation, JWT verification, and running the MCP server. It prints the access token to the console, which should not be done in production.
```python
from fastmcp import FastMCP
from fastmcp.server.auth import JWTVerifier
from fastmcp.server.auth.providers.jwt import RSAKeyPair
import random
key_pair = RSAKeyPair.generate()
access_token = key_pair.create_token(audience="dice-server")
auth = JWTVerifier(
public_key=key_pair.public_key,
audience="dice-server",
)
mcp = FastMCP(name="Dice Roller", auth=auth)
@mcp.tool
def roll_dice(n_dice: int) -> list[int]:
"""Roll `n_dice` 6-sided dice and return the results."""
return [random.randint(1, 6) for _ in range(n_dice)]
if __name__ == "__main__":
print(f"\n---\n\n🔑 Dice Roller access token:\n\n{access_token}\n\n---\n")
mcp.run(transport="http", port=8000)
```
--------------------------------
### Complete FastMCP HTTP Server Example
Source: https://gofastmcp.com/deployment/http
A full example demonstrating the setup of a FastMCP server with OAuth authentication, mounted under a path prefix. Includes defining routes, creating the auth provider and MCP app, and running the server with uvicorn.
```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 Interactive Map Example
Source: https://gofastmcp.com/apps/examples
Start the development server for the interactive map example, which geocodes addresses and displays them on a Leaflet map using Prefab's Embed component.
```bash
fastmcp dev apps examples/apps/map/map_server.py
```
--------------------------------
### FastMCP Install with Explicit Entrypoint and Dependencies
Source: https://gofastmcp.com/cli/install-mcp
Install a server instance specifying an explicit entrypoint and including additional Python dependencies. Use this for custom server setups or when specific libraries are required.
```bash
# Explicit entrypoint with dependencies
fastmcp install claude-desktop server.py:my_server \
--server-name "My Analysis Server" \
--with pandas
```
--------------------------------
### Basic FastMCP Installation
Source: https://gofastmcp.com/cli/install-mcp
Install a server instance with automatic server detection. Use this for straightforward installations.
```bash
# Basic install with auto-detected server instance
fastmcp install claude-desktop server.py
```
--------------------------------
### Install Server with Requirements File
Source: https://gofastmcp.com/integrations/claude-desktop
Install all dependencies listed in a requirements.txt file using the --with-requirements flag.
```bash
fastmcp install claude-desktop server.py --with-requirements requirements.txt
```
--------------------------------
### Full Background Task Example
Source: https://gofastmcp.com/clients/tasks
Demonstrates starting a background task, subscribing to its progress updates, performing concurrent work, and awaiting the final result. Ensure the server has background task support enabled for this functionality.
```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())
```
--------------------------------
### Running FastMCP Examples
Source: https://gofastmcp.com/apps/examples
Instructions on how to run the example FastMCP applications. Examples can be run using the 'fastmcp dev apps' command.
```bash
fastmcp dev apps
```
--------------------------------
### Create Proxy Server
Source: https://gofastmcp.com/servers/providers/proxy
Quick start example for creating a proxy server using `create_proxy()`. This function accepts various source types like URLs, file paths, and transports.
```python
from fastmcp.server import create_proxy
# create_proxy() accepts URLs, file paths, and transports directly
proxy = create_proxy("http://example.com/mcp", name="MyProxy")
if __name__ == "__main__":
proxy.run()
```
--------------------------------
### Install Basic MCP Server
Source: https://gofastmcp.com/integrations/mcp-json-configuration
Installs an MCP server and generates a basic `uv run` configuration.
```bash
fastmcp install mcp-json dice_server.py
```
--------------------------------
### Install otel-desktop-viewer
Source: https://gofastmcp.com/servers/telemetry
Install otel-desktop-viewer using Homebrew or download from GitHub releases for local trace visualization.
```bash
# macOS
brew install nico-barbas/brew/otel-desktop-viewer
# Or download from GitHub releases
```
--------------------------------
### Install uv on Linux/Windows
Source: https://gofastmcp.com/integrations/mcp-json-configuration
Installs the uv package manager on Linux and Windows by downloading and executing an installation script.
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```
--------------------------------
### Run FastMCP Server with `run()` Method
Source: https://gofastmcp.com/deployment/running-server
This snippet demonstrates the basic setup for running a FastMCP server. It's recommended to place the `mcp.run()` call within an `if __name__ == "__main__":` block to ensure the server only starts 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()
```
--------------------------------
### Install Server with Requirements File
Source: https://gofastmcp.com/integrations/claude-code
Installs a FastMCP server and its dependencies from a requirements.txt file using the --with-requirements flag.
```bash
fastmcp install claude-code server.py --with-requirements requirements.txt
```
--------------------------------
### Install Server with Environment File
Source: https://gofastmcp.com/integrations/claude-code
Installs a FastMCP server and loads environment variables from a .env file using the --env-file flag.
```bash
fastmcp install claude-code server.py --server-name "Weather Server" --env-file .env
```
--------------------------------
### Install Production Server with Dependencies
Source: https://gofastmcp.com/integrations/mcp-json-configuration
Installs an MCP server with specified dependencies and environment variables for production use.
```bash
fastmcp install mcp-json api_server.py \
--name "Production API Server" \
--with requests \
--with python-dotenv \
--env API_BASE_URL=https://api.example.com \
--env TIMEOUT=30
```
--------------------------------
### Install Server using fastmcp.json Configuration
Source: https://gofastmcp.com/cli/install-mcp
Install a server by referencing its `fastmcp.json` configuration file. Dependencies declared in the file are automatically included.
```bash
fastmcp install claude-desktop fastmcp.json
```
--------------------------------
### Specify Server Object for Installation
Source: https://gofastmcp.com/integrations/goose
When installing, you can specify the server object name if it's not the default ('mcp', 'server', or 'app').
```bash
# These are equivalent if your server object is named 'mcp'
fastmcp install goose server.py
fastmcp install goose server.py:mcp
# Use explicit object name if your server has a different name
fastmcp install goose server.py:my_custom_server
```
--------------------------------
### Specify Dependencies for Installation
Source: https://gofastmcp.com/integrations/goose
Use the `--with` flag to include additional Python packages required by your server during installation.
```bash
fastmcp install goose server.py --with pandas --with requests
```
--------------------------------
### Minimal FastMCP Server Example
Source: https://gofastmcp.com/deployment/prefect-horizon
This is a basic example of a FastMCP server file that can be used with Horizon. It defines a simple 'hello' tool.
```python
from fastmcp import FastMCP
mcp = FastMCP("MyServer")
@mcp.tool
def hello(name: str) -> str:
return f"Hello, {name}!"
```
--------------------------------
### Install Server with Editable Packages
Source: https://gofastmcp.com/integrations/claude-desktop
Install local Python packages in editable mode for development using the --with-editable flag.
```bash
fastmcp install claude-desktop server.py --with-editable ./my-local-package
```
--------------------------------
### Start Local Documentation Server
Source: https://gofastmcp.com/development/tests
Launch a local Mintlify server to preview documentation as users will see it, with hot reloading for automatic refreshes. This helps catch formatting issues.
```bash
# Start local documentation server with hot reload
just docs
# Or run Mintlify directly
mintlify dev
```
--------------------------------
### Filesystem Source Configuration Example
Source: https://gofastmcp.com/deployment/server-configuration
This example configures the server source to be a local Python file. Specify the 'path' to your server file and optionally the 'entrypoint' function or instance name.
```json
"source": {
"type": "filesystem",
"path": "src/server.py",
"entrypoint": "mcp"
}
```
--------------------------------
### Prepare and Run FastMCP Project with Pre-built Environment
Source: https://gofastmcp.com/deployment/server-configuration
Pre-build a persistent uv environment for faster server startup. Use `fastmcp project prepare` to create the environment and then `fastmcp run` to execute the server using the prepared environment.
```bash
# Create a persistent environment
fastmcp project prepare fastmcp.json --output-dir ./env
# Use the pre-built environment to run the server
fastmcp run fastmcp.json --project ./env
```
--------------------------------
### Specify Server Entrypoint
Source: https://gofastmcp.com/integrations/cursor
The install command supports the `file.py:object` notation to specify the server entrypoint. If no object is specified, it defaults to common names like `mcp`, `server`, or `app`.
```bash
# These are equivalent if your server object is named 'mcp'
fastmcp install cursor server.py
fastmcp install cursor server.py:mcp
```
```bash
# Use explicit object name if your server has a different name
fastmcp install cursor server.py:my_custom_server
```
--------------------------------
### Example Server Configuration JSON
Source: https://gofastmcp.com/integrations/mcp-json-configuration
This is the JSON output generated by the `fastmcp install mcp-json` command, with the server name as the root key.
```json
{
"My Server": {
"command": "uv",
"args": [
"run",
"--with",
"fastmcp",
"fastmcp",
"run",
"/absolute/path/to/server.py"
]
}
}
```
--------------------------------
### Start Server with Different Entrypoints
Source: https://gofastmcp.com/cli/running
Use `fastmcp run` with various arguments to specify how to start your server. This includes pointing to a Python file, a specific factory function, a remote URL, or a configuration file.
```bash
fastmcp run server.py
```
```bash
fastmcp run server.py:create_server
```
```bash
fastmcp run https://example.com/mcp
```
```bash
fastmcp run fastmcp.json
```
--------------------------------
### Run Generated Script with FastMCP Dependency
Source: https://gofastmcp.com/cli/generate-cli
Example of running a generated CLI script when 'fastmcp' is not globally installed, using 'uv run'.
```bash
uv run --with fastmcp python cli.py call-tool get_forecast --city London
```
--------------------------------
### Preview Documentation Locally
Source: https://gofastmcp.com/development/contributing
Run this command to preview the project's documentation locally. Ensure you have 'just' installed.
```bash
# Preview documentation locally
just docs
```
--------------------------------
### Starting the Development Server
Source: https://gofastmcp.com/apps/development
Use this command to start the local development server for your app tools. It launches the server and the development UI, allowing you to test your tools.
```bash
fastmcp dev apps server.py
```
--------------------------------
### Run FastMCP Server Skipping Environment Setup
Source: https://gofastmcp.com/deployment/server-configuration
Use this command when you already have a suitable Python environment with all dependencies installed. It tells FastMCP to skip the environment creation process.
```bash
fastmcp run fastmcp.json --skip-env
```
--------------------------------
### Complete Server Upgrade Example
Source: https://gofastmcp.com/getting-started/upgrading/from-low-level-sdk
This snippet shows a full server implementation using the low-level SDK before the upgrade, including tools, resources, and prompts. It then presents the equivalent implementation using the higher-level FastMCP framework after the upgrade.
```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())
```
```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()
```
--------------------------------
### Custom Route Mapping for FastAPI to MCP Conversion
Source: https://gofastmcp.com/integrations/fastapi
Customize how FastAPI endpoints are converted to MCP components using RouteMap. This example maps GET requests to Resources and others to Tools.
```python
# Assumes the FastAPI app from above is already defined
from fastmcp import FastMCP
from fastmcp.server.providers.openapi import RouteMap, MCPType
# Custom mapping rules
mcp = FastMCP.from_fastapi(
app=app,
route_maps=[
# GET with path params → ResourceTemplates
RouteMap(
methods=["GET"],
pattern=r".*\{.*\}.*",
mcp_type=MCPType.RESOURCE_TEMPLATE
),
# Other GETs → Resources
RouteMap(
methods=["GET"],
pattern=r".*",
mcp_type=MCPType.RESOURCE
),
# POST/PUT/DELETE → Tools (default)
],
)
# Now:
# - GET /products → Resource
# - GET /products/{id} → ResourceTemplate
# - POST/PUT/DELETE → Tools
```
--------------------------------
### Define a Basic Lifespan with @lifespan
Source: https://gofastmcp.com/servers/lifespan
Use the @lifespan decorator to define a function that runs setup code when the server starts and teardown code when it stops. Ensure cleanup code is within a try/finally block.
```python
from fastmcp import FastMCP
from fastmcp.server.lifespan import lifespan
@lifespan
async def app_lifespan(server):
# Setup: runs once when server starts
print("Starting up...")
try:
yield {"started_at": "2024-01-01"}
finally:
# Teardown: runs when server stops
print("Shutting down...")
mcp = FastMCP("MyServer", lifespan=app_lifespan)
```
--------------------------------
### Create a FastMCP Server with Instructions
Source: https://gofastmcp.com/servers/server
Provide instructions to guide clients and LLMs on the server's purpose and usage.
```python
mcp = FastMCP(
"DataAnalysis",
instructions="Provides tools for analyzing numerical datasets. Start with get_summary() for an overview.",
)
```
--------------------------------
### Configure FastMCP with Static Token Authentication
Source: https://gofastmcp.com/deployment/http
Set up FastMCP with static token authentication by reading the token from an environment variable. This example demonstrates a basic security setup for development or specific internal uses.
```python
import os
from fastmcp import FastMCP
from fastmcp.server.auth import StaticTokenVerifier
# Read configuration from environment
auth_token = os.environ.get("MCP_AUTH_TOKEN")
if auth_token:
auth = StaticTokenVerifier(tokens={auth_token: {"sub": "admin", "client_id": "cli"}})
mcp = FastMCP("Production Server", auth=auth)
else:
mcp = FastMCP("Production Server")
app = mcp.http_app()
```
--------------------------------
### Namespace Activation Pattern Example
Source: https://gofastmcp.com/servers/visibility
Organizes tools into namespaces with tag prefixes, disables them globally, and provides activation tools to unlock namespaces on demand for specific sessions. Sessions start with only activation tools visible.
```python
from fastmcp import FastMCP
from fastmcp.server.context import Context
server = FastMCP("Multi-Domain Assistant")
# Finance namespace
@server.tool(tags={"namespace:finance"})
def analyze_portfolio(symbols: list[str]) -> str:
return f"Analysis for: {', '.join(symbols)}"
@server.tool(tags={"namespace:finance"})
def get_market_data(symbol: str) -> dict:
return {"symbol": symbol, "price": 150.25}
# Admin namespace
@server.tool(tags={"namespace:admin"})
def list_users() -> list[str]:
return ["alice", "bob", "charlie"]
# Activation tools - always visible
@server.tool
async def activate_finance(ctx: Context) -> str:
await ctx.enable_components(tags={"namespace:finance"})
return "Finance tools activated"
@server.tool
async def activate_admin(ctx: Context) -> str:
await ctx.enable_components(tags={"namespace:admin"})
return "Admin tools activated"
@server.tool
async def deactivate_all(ctx: Context) -> str:
await ctx.reset_visibility()
return "All namespaces deactivated"
# Disable namespace tools globally
server.disable(tags={"namespace:finance", "namespace:admin"})
```
--------------------------------
### Full Contact Manager App Example
Source: https://gofastmcp.com/apps/fastmcp-app
This Python script defines a complete contact manager application using FastMCP. It includes tools for saving, searching, and listing contacts, along with a UI for managing them. Ensure all necessary libraries are installed.
```python
from __future__ import annotations
from typing import Literal
from prefab_ui.actions import SetState, ShowToast
from prefab_ui.actions.mcp import CallTool
from prefab_ui.app import PrefabApp
from prefab_ui.components import (
Badge, Button, Column, ForEach,
Form,
Heading, Input, Muted, Row, Separator, Text,
)
from prefab_ui.rx import RESULT, Rx
from pydantic import BaseModel, Field
from fastmcp import FastMCP, FastMCPApp
contacts_db: list[dict] = [
{"name": "Arthur Dent", "email": "arthur@earth.com", "category": "Customer"},
{"name": "Ford Prefect", "email": "ford@betelgeuse.org", "category": "Partner"},
]
class ContactModel(BaseModel):
name: str = Field(title="Full Name", min_length=1)
email: str = Field(title="Email")
category: Literal["Customer", "Vendor", "Partner", "Other"] = "Other"
app = FastMCPApp("Contacts")
@app.tool()
def save_contact(data: ContactModel) -> list[dict]:
"""Save a new contact and return the updated list."""
contacts_db.append(data.model_dump())
return list(contacts_db)
@app.tool()
def search_contacts(query: str) -> list[dict]:
"""Filter contacts by name or email."""
q = query.lower()
return [
c for c in contacts_db
if q in c["name"].lower() or q in c["email"].lower()
]
@app.tool(model=True)
def list_contacts() -> list[dict]:
"""Return all contacts. Visible to both the model and the UI."""
return list(contacts_db)
@app.ui()
def contact_manager() -> PrefabApp:
"""Open the contact manager."""
with Column(gap=6, css_class="p-6") as view:
Heading("Contacts")
with ForEach("contacts") as contact:
with Row(gap=2, align="center"):
Text(contact.name, css_class="font-medium")
Muted(contact.email)
Badge(contact.category)
Separator()
Heading("Add Contact", level=3)
Form.from_model(
ContactModel,
on_submit=CallTool(
"save_contact",
on_success=[
SetState("contacts", RESULT),
ShowToast("Contact saved!", variant="success"),
],
on_error=ShowToast("Failed to save", variant="error"),
),
)
Separator()
Heading("Search", level=3)
with Form(
on_submit=CallTool(
"search_contacts",
arguments={"query": Rx("query")},
on_success=SetState("contacts", RESULT),
)
):
Input(name="query", placeholder="Search by name or email...")
Button("Search")
return PrefabApp(view=view, state={"contacts": list(contacts_db)})
mcp = FastMCP("Contacts Server", providers=[app])
if __name__ == "__main__":
mcp.run()
```
--------------------------------
### Initialize FastMCP Server with FileSystemProvider
Source: https://gofastmcp.com/servers/providers/filesystem
Set up a FastMCP server instance, providing a FileSystemProvider that points to a directory containing server components. The path is made relative to the server file's location.
```python
from pathlib import Path
from fastmcp import FastMCP
from fastmcp.server.providers import FileSystemProvider
mcp = FastMCP("MyServer", providers=[FileSystemProvider(Path(__file__).parent / "components")])
```
--------------------------------
### Running Multi-Environment Configurations
Source: https://gofastmcp.com/deployment/server-configuration
Command-line examples for running the fastmcp server with different configuration files for development and production.
```bash
fastmcp run dev.fastmcp.json # Development
fastmcp run prod.fastmcp.json # Production
```
--------------------------------
### Install and Verify FastMCP
Source: https://gofastmcp.com/getting-started/upgrading/from-mcp-sdk
Install the latest FastMCP version using pip, check the installed version, and run your server. Ensure you have Python installed and pip is available.
```bash
# Install
pip install --upgrade fastmcp
# Check version
fastmcp version
# Run your server
python my_server.py
```
--------------------------------
### Install or Upgrade FastMCP
Source: https://gofastmcp.com/changelog
Use this command to install the latest version of FastMCP or upgrade an existing installation.
```bash
pip install fastmcp -U
```
--------------------------------
### Install Server within a Project Directory
Source: https://gofastmcp.com/integrations/claude-desktop
Use the --project flag to specify a project directory. This ensures correct resolution of project files and virtual environments.
```bash
fastmcp install claude-desktop server.py --project /path/to/my-project
```
--------------------------------
### FastMCP Install from JSON
Source: https://gofastmcp.com/cli/install-mcp
Install a server instance using settings defined in a fastmcp.json file, with automatic server detection. Useful when configurations are managed centrally.
```bash
# Install from fastmcp.json with auto-detection
fastmcp install claude-desktop
```
--------------------------------
### Install FastMCP Server in Goose
Source: https://gofastmcp.com/integrations/goose
Use this command to install a FastMCP server in Goose. It generates a `goose://` deeplink to prompt Goose for installation.
```bash
fastmcp install goose server.py
```
--------------------------------
### Enable and Start FastMCP systemd Service
Source: https://gofastmcp.com/deployment/http
Commands to reload the systemd daemon, enable the FastMCP service to start on boot, and start the service immediately.
```bash
sudo systemctl daemon-reload
sudo systemctl enable fastmcp
sudo systemctl start fastmcp
```
--------------------------------
### CLI Command Example
Source: https://gofastmcp.com/deployment/server-configuration
This bash command demonstrates how to run a server with specific dependencies, transport, port, and log level using command-line arguments.
```bash
uv run --with pandas --with requests \
fastmcp run server.py \
--transport http \
--port 8000 \
--log-level INFO
```
--------------------------------
### Install fastmcp-remote with uv
Source: https://gofastmcp.com/clients/fastmcp-remote
Install the fastmcp-remote package using the 'uv tool install' command if your host requires an already-installed command. This method uses a Python package manager.
```bash
uv tool install fastmcp-remote
```
--------------------------------
### Clone Repository and Install Dependencies
Source: https://gofastmcp.com/development/contributing
Clone the FastMCP repository and install all necessary dependencies, including development tools, using uv sync. Then, install prek hooks for automated checks.
```bash
git clone https://github.com/PrefectHQ/fastmcp.git
cd fastmcp
uv sync
uv run prek install
```
--------------------------------
### Install Server with Editable Package and Requirements
Source: https://gofastmcp.com/cli/install-mcp
Install a local package in editable mode using `-e` and include dependencies from a `requirements.txt` file with `--with-requirements`.
```bash
fastmcp install cursor server.py -e . --with-requirements requirements.txt
```
--------------------------------
### Creating and Using FastMCPApp
Source: https://gofastmcp.com/python-sdk/fastmcp-apps-app
Demonstrates how to instantiate FastMCPApp, define UI and tool components, and add the app to a FastMCP server. Ensure FastMCP and FastMCPApp are imported.
```python
from fastmcp import FastMCP, FastMCPApp
app = FastMCPApp("Dashboard")
@app.ui()
def show_dashboard() -> Component:
return Column(...)
@app.tool()
def save_contact(name: str, email: str) -> str:
return name
server = FastMCP("Platform")
server.add_provider(app)
```
--------------------------------
### Install uv on macOS
Source: https://gofastmcp.com/integrations/mcp-json-configuration
Installs the uv package manager on macOS using Homebrew.
```bash
brew install uv
```
--------------------------------
### Install eunomia-mcp Package
Source: https://gofastmcp.com/integrations/eunomia-authorization
Install the necessary package for Eunomia MCP middleware integration.
```bash
pip install eunomia-mcp
```
--------------------------------
### Install pytest-asyncio
Source: https://gofastmcp.com/servers/testing
Install pytest-asyncio as a development dependency to handle asynchronous test functions and fixtures.
```bash
pip install pytest-asyncio
```
--------------------------------
### Example Usage of VersionBadge
Source: https://gofastmcp.com/apps/quickstart
This is an example of how to use the VersionBadge component, specifying the version number as a prop.
```javascript
```
--------------------------------
### Prepare and Run Project Environment
Source: https://gofastmcp.com/cli/running
Use `fastmcp project prepare` to build a persistent environment and `fastmcp run` to execute using that environment. This separates environment setup from server execution.
```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
```
--------------------------------
### Install OpenTelemetry Dependencies
Source: https://gofastmcp.com/servers/telemetry
Install the necessary OpenTelemetry packages for instrumentation. This includes the distribution and an OTLP exporter.
```bash
pip install opentelemetry-distro opentelemetry-exporter-otlp
opentelemetry-bootstrap -a install
```
--------------------------------
### Example MCP Server Configuration
Source: https://gofastmcp.com/python-sdk/fastmcp-mcp_config
This JSON object demonstrates the structure for configuring MCP servers, including command, arguments, environment variables, timeout, and description.
```json
{
"mcpServers": {
"my-server": {
"command": "npx",
"args": ["-y", "@my/mcp-server"],
"env": {"API_KEY": "secret"},
"timeout": 30000,
"description": "My MCP server"
}
}
}
```
--------------------------------
### Demonstrate Conflict Resolution with Server Mounting
Source: https://gofastmcp.com/servers/composition
This example shows how the last mounted server's tool overrides previous ones with the same name. Ensure FastMCP is imported.
```python
server_a = FastMCP("A")
server_b = FastMCP("B")
@server_a.tool
def shared_tool() -> str:
return "From A"
@server_b.tool
def shared_tool() -> str:
return "From B"
main = FastMCP("Main")
main.mount(server_a)
main.mount(server_b)
# shared_tool returns "From B" (most recently mounted)
```
--------------------------------
### Install FastMCP Toolset
Source: https://gofastmcp.com/integrations/pydantic-ai
Install the pydantic-ai-slim package with the fastmcp optional group to use the FastMCP Toolset.
```bash
pip install "pydantic-ai-slim[fastmcp]"
```
--------------------------------
### Complete fastmcp.json Configuration Example
Source: https://gofastmcp.com/deployment/server-configuration
This example shows a full `fastmcp.json` configuration, including source, environment, and deployment settings. The 'source' field is mandatory, while 'environment' and 'deployment' are optional.
```json
{
"$schema": "https://gofastmcp.com/public/schemas/fastmcp.json/v1.json",
"source": {
"type": "filesystem",
"path": "server.py",
"entrypoint": "mcp"
},
"environment": {
"type": "uv",
"python": ">=3.10",
"dependencies": ["pandas", "numpy"]
},
"deployment": {
"transport": "stdio",
"log_level": "INFO"
}
}
```
--------------------------------
### Verify FastMCP installation
Source: https://gofastmcp.com/getting-started/installation
Run this command to check if FastMCP has been installed correctly and display its version information.
```bash
fastmcp version
```
--------------------------------
### React Example Usage of VersionBadge
Source: https://gofastmcp.com/servers/authorization
Example of how to use the VersionBadge component, passing a version string as a prop.
```javascript
```
--------------------------------
### MCPServerConfig.prepare
Source: https://gofastmcp.com/python-sdk/fastmcp-utilities-mcp_server_config-v1-mcp_server_config
Prepares the environment and source for execution.
```APIDOC
## MCPServerConfig.prepare
### Description
Prepares the environment and source for execution. Creates a persistent uv project if `output_dir` is provided, otherwise uses ephemeral caching.
### Method Signature
```python
prepare(self, skip_source: bool = False, output_dir: Path | None = None) -> None
```
### Parameters
#### Path Parameters
- **skip_source** (bool) - Optional - If True, skips source preparation.
- **output_dir** (Path | None) - Optional - Directory to create the persistent uv project in.
### Returns
- None
```
--------------------------------
### Example Usage of Version Badge
Source: https://gofastmcp.com/integrations/azure
An example of how to use the VersionBadge component, passing a specific version number.
```javascript
```
--------------------------------
### Multi-Environment Setup Configurations
Source: https://gofastmcp.com/deployment/server-configuration
Defines separate configuration files for development and production environments, demonstrating how to manage different settings.
```json
{
"$schema": "https://gofastmcp.com/public/schemas/fastmcp.json/v1.json",
"source": {
"path": "server.py",
"entrypoint": "mcp"
},
"deployment": {
"transport": "http",
"log_level": "DEBUG"
}
}
```
```json
{
"$schema": "https://gofastmcp.com/public/schemas/fastmcp.json/v1.json",
"source": {
"path": "server.py",
"entrypoint": "mcp"
},
"environment": {
"requirements": "requirements/production.txt"
},
"deployment": {
"transport": "http",
"host": "0.0.0.0",
"log_level": "WARNING"
}
}
```