An open-source framework for building MCP servers and clients in a fast, Pythonic way.
FastMCP - Python Framework for Rapidly Building MCP Servers and Clients
Project Overview
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.
Why Choose FastMCP?
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:
- 🚀 Fast: High-level interface means less code and faster development
- 🍀 Simple: Build MCP servers with minimal boilerplate
- 🐍 Pythonic: Feels natural to Python developers
- 🔍 Complete: Provides a complete implementation of the MCP core specification, supporting both servers and clients
Core Features
Basic Features
- Create servers with intuitive decorators, with minimal boilerplate code
- Proxy existing servers to modify configurations or transport methods
- Combine servers into complex applications
- Generate servers from OpenAPI specifications or FastAPI objects
- Interact with MCP servers programmatically
- Connect to any MCP server using any transport protocol
- Test servers without manual intervention
- Leverage core MCP features such as LLM sampling
Version Evolution
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:
- Advanced features such as proxying and combining MCP servers
- Automatically generate servers from OpenAPI specifications or FastAPI objects
- Introduced client functionality, such as LLM sampling
Installation
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
Quick Start Example
Basic Server Example
# 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
Core Concepts Explained
1. FastMCP Instance
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"])
2. Tools
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)
3. Resources
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")
4. Prompts
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?")
]
Advanced Features
1. Proxy Servers
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')
2. Server Composition
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)
3. Generate Servers from APIs
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)
4. Client Functionality
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)
Running Servers
Development Mode
fastmcp dev your_server_file.py
Production Installation
fastmcp install your_server_file.py
Direct Run
if __name__ == "__main__":
mcp.run()
Example Projects
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 interaction
Contribution Guide
FastMCP welcomes community contributions:
Environment Requirements
- Python 3.10+
- uv package manager
Development Setup
git clone https://github.com/jlowin/fastmcp.git && cd fastmcp
uv venv && uv sync
Testing
uv run pytest -vv
Code Quality
Use ruff
and pre-commit
:
pre-commit install
pre-commit run --all-files
Project Significance
FastMCP bridges the gap between MCP protocol implementation and practical application development, enabling developers to:
- Quickly prototype and deploy MCP servers
- Easily integrate existing APIs and data sources
- Build modular, scalable AI application architectures
- Focus on business logic rather than protocol implementation details