FastMCP is a high-level Python framework for building Model Context Protocol (MCP) servers and clients, designed to enable developers to quickly and concisely create tools, expose resources, define prompts, and connect components. Developed and maintained by GitHub user jlowin, this project has become an important part of the MCP ecosystem.
While the MCP protocol is powerful, implementing it requires a lot of boilerplate code - server setup, protocol handlers, content types, error management, etc. FastMCP handles all the complex protocol details and server management, allowing you to focus on building great tools.
FastMCP's design goals:
FastMCP 1.0 made building MCP servers so easy that it has now become part of the official Model Context Protocol Python SDK!
FastMCP 2.0 builds on this by introducing several new features:
It is recommended to install FastMCP using uv:
uv pip install fastmcp
Development Installation:
git clone https://github.com/jlowin/fastmcp.git
cd fastmcp
uv sync
# server.py
from fastmcp import FastMCP
mcp = FastMCP("Demo")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers"""
return a + b
@mcp.resource("greeting://{name}")
def get_greeting(name: str) -> str:
"""Get a personalized greeting"""
return f"Hello, {name}!"
if __name__ == "__main__":
mcp.run()
Install to Claude Desktop:
fastmcp install server.py
Represents the central object of an MCP application, handling connections, protocol details, and routing:
from fastmcp import FastMCP
mcp = FastMCP("My App")
mcp = FastMCP("My App", dependencies=["pandas", "numpy"])
Allow LLMs to perform actions by executing Python functions, suitable for calculations, external API calls, or side effects:
import httpx
from pydantic import BaseModel
class UserInfo(BaseModel):
user_id: int
notify: bool = False
@mcp.tool()
async def send_notification(user: UserInfo, message: str) -> dict:
"""Sends a notification to a user if requested."""
if user.notify:
print(f"Notifying user {user.user_id}: {message}")
return {"status": "sent", "user_id": user.user_id}
return {"status": "skipped", "user_id": user.user_id}
@mcp.tool()
def get_stock_price(ticker: str) -> float:
"""Gets the current price for a stock ticker."""
prices = {"AAPL": 180.50, "GOOG": 140.20}
return prices.get(ticker.upper(), 0.0)
Expose data to LLMs, primarily providing information without significant calculations or side effects:
@mcp.resource("config://app-version")
def get_app_version() -> str:
"""Returns the application version."""
return "v2.1.0"
@mcp.resource("db://users/{user_id}/email")
async def get_user_email(user_id: str) -> str:
"""Retrieves the email address for a given user ID."""
emails = {"123": "alice@example.com", "456": "bob@example.com"}
return emails.get(user_id, "not_found@example.com")
Define reusable templates or interaction patterns:
from fastmcp.prompts.base import UserMessage, AssistantMessage
@mcp.prompt()
def ask_review(code_snippet: str) -> str:
"""Generates a standard code review request."""
return f"Please review the following code snippet for potential bugs and style issues:\n```python\n{code_snippet}\n```"
@mcp.prompt()
def debug_session_start(error_message: str) -> list[Message]:
"""Initiates a debugging help session."""
return [
UserMessage(f"I encountered an error:\n{error_message}"),
AssistantMessage("Okay, I can help with that. Can you provide the full traceback and tell me what you were trying to do?")
]
Create FastMCP servers that act as intermediaries, proxying requests to another MCP endpoint:
import asyncio
from fastmcp import FastMCP, Client
from fastmcp.client.transports import PythonStdioTransport
proxy_client = Client(
transport=PythonStdioTransport('path/to/original_stdio_server.py'),
)
proxy = FastMCP.from_client(proxy_client, name="Stdio-to-SSE Proxy")
if __name__ == "__main__":
proxy.run(transport='sse')
Build large MCP applications by creating modular FastMCP servers and "mounting" them onto a parent server:
from fastmcp import FastMCP
weather_mcp = FastMCP("Weather Service")
@weather_mcp.tool()
def get_forecast(city: str):
return f"Sunny in {city}"
news_mcp = FastMCP("News Service")
@news_mcp.tool()
def fetch_headlines():
return ["Big news!", "Other news"]
mcp = FastMCP("Composite")
mcp.mount("weather", weather_mcp)
mcp.mount("news", news_mcp)
Automatically generate FastMCP servers from existing Web APIs:
from fastapi import FastAPI
from fastmcp import FastMCP
fastapi_app = FastAPI(title="My Existing API")
@fastapi_app.get("/status")
def get_status():
return {"status": "running"}
mcp_server = FastMCP.from_fastapi(fastapi_app)
Interact with any MCP server:
from fastmcp import Client
async with Client("path/to/server") as client:
result = await client.call_tool("weather", {"location": "San Francisco"})
print(result)
res = await client.read_resource("db://users/123/profile")
print(res)
fastmcp dev your_server_file.py
fastmcp install your_server_file.py
if __name__ == "__main__":
mcp.run()
The project includes several example files:
simple_echo.py
: Basic tools, resources, and promptscomplex_inputs.py
: Using Pydantic models as tool inputsmount_example.py
: Mounting multiple FastMCP serverssampling.py
: Using LLM completion in an MCP serverscreenshot.py
: Tool returning an Image objecttext_me.py
: Tool interacting with an external APImemory.py
: Complex example with database interactionFastMCP welcomes community contributions:
git clone https://github.com/jlowin/fastmcp.git && cd fastmcp
uv venv && uv sync
uv run pytest -vv
Use ruff
and pre-commit
:
pre-commit install
pre-commit run --all-files
FastMCP bridges the gap between MCP protocol implementation and practical application development, enabling developers to: