FastMCP Overview
FastMCP is a popular MCP server framework in the Python ecosystem. It builds on the mcp package and provides a simple decorator API. Install with pip install mcp fastmcp to get started.
Basic Structure
from fastmcp import FastMCP
mcp = FastMCP("my-server")
@mcp.tool()
def search(query: str) -> str:
"""Search documents by keyword"""
return do_search(query)
@mcp.resource("doc://readme")
def readme() -> str:
"""Return project README content"""
return open("README.md").read()
FastMCP(name)creates the server instance@mcp.tool()registers tools; function signatures are converted to parameter schemas@mcp.resource(uri)registers resources; supports dynamic URI templates
Decorator Details
@mcp.tool()
- Supports
nameanddescriptionoverrides - Parameters use type hints (str, int, bool, list, etc.) or Pydantic models
- Return values are serialized to JSON for the client
- URI can include parameters, e.g.,
"doc://{filename}" - The function receives URI parameters and returns text or binary content
- Registers reusable prompt templates
- Supports parameters; client fills variables to get the final prompt
Transport Configuration
# stdio (default, for Claude Desktop etc.)
mcp.run(transport="stdio")
or as HTTP/SSE service
mcp.run(transport="sse", host="0.0.0.0", port=8000)
Error Handling
- Raise
ValueError("clear error message")in tools; it becomes MCP error responses - Avoid exposing internal details; return user-friendly messages
Testing Strategy
mcp package Client to connect and send List/Call; assert responsesBest Practices
- Use clear names and descriptions for tools and resources so the model chooses correctly
- Add strict validation with Pydantic
- Add timeout and cancellation support for long-running operations
- Add permission checks for sensitive operations to avoid unauthorized access
Summary
FastMCP simplifies Python MCP server development with decorators. Once you master tool, resource, and prompt registration and transport configuration, you can build stable MCP services quickly with unit and protocol tests.