- Notifications
You must be signed in to change notification settings - Fork1.5k
🚀 The fast, Pythonic way to build MCP servers and clients
License
jlowin/fastmcp
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Note
FastMCP pioneered Python MCP development, and FastMCP 1.0 was incorporated into theofficial MCP SDK in 2024.
This is FastMCP 2.0 — the actively maintained, production-ready framework that extends far beyond basic protocol implementation. While the SDK provides core functionality, FastMCP 2.0 delivers everything needed for production: advanced MCP patterns (server composition, proxying, OpenAPI/FastAPI generation, tool transformation), enterprise auth (Google, GitHub, WorkOS, Azure, Auth0, and more), deployment tools, testing utilities, and comprehensive client libraries.
For production MCP applications, install FastMCP:pip install fastmcp
FastMCP is the standard framework for building MCP applications, providing the fastest path from idea to production.
TheModel Context Protocol (MCP) is a standardized way to provide context and tools to LLMs. FastMCP makes building production-ready MCP servers simple, with enterprise auth, deployment tools, and a complete ecosystem built in.
# server.pyfromfastmcpimportFastMCPmcp=FastMCP("Demo 🚀")@mcp.tooldefadd(a:int,b:int)->int:"""Add two numbers"""returna+bif__name__=="__main__":mcp.run()
Run the server locally:
fastmcp run server.py
FastMCP's complete documentation is available atgofastmcp.com, including detailed guides, API references, and advanced patterns. This readme provides only a high-level overview.
Documentation is also available inllms.txt format, which is a simple markdown standard that LLMs can consume easily.
There are two ways to access the LLM-friendly documentation:
llms.txtis essentially a sitemap, listing all the pages in the documentation.llms-full.txtcontains the entire documentation. Note this may exceed the context window of your LLM.
Community: Join ourDiscord server to connect with other FastMCP developers and share what you're building.
- FastMCP v2 🚀
TheModel Context Protocol (MCP) lets you build servers that expose data and functionality to LLM applications in a secure, standardized way. It is often described as "the USB-C port for AI", providing a uniform way to connect LLMs to resources they can use. It may be easier to think of it as an API, but specifically designed for LLM interactions. MCP servers can:
- Expose data throughResources (think of these sort of like GET endpoints; they are used to load information into the LLM's context)
- Provide functionality throughTools (sort of like POST endpoints; they are used to execute code or otherwise produce a side effect)
- Define interaction patterns throughPrompts (reusable templates for LLM interactions)
- And more!
FastMCP provides a high-level, Pythonic interface for building, managing, and interacting with these servers.
FastMCP handles all the complex protocol details so you can focus on building. In most cases, decorating a Python function is all you need — FastMCP handles the rest.
🚀Fast: High-level interface means less code and faster development
🍀Simple: Build MCP servers with minimal boilerplate
🐍Pythonic: Feels natural to Python developers
🔍Complete: Everything for production — enterprise auth (Google, GitHub, Azure, Auth0, WorkOS), deployment tools, testing frameworks, client libraries, and more
FastMCP provides the shortest path from idea to production. Deploy locally, to the cloud withFastMCP Cloud, or to your own infrastructure.
We recommend installing FastMCP withuv:
uv pip install fastmcp
For full installation instructions, including verification, upgrading from the official MCPSDK, and developer setup, see theInstallation Guide.
Dependency Licensing: FastMCP depends on Cyclopts for CLI functionality. Cyclopts v4 includes docutils as a transitive dependency, which has complex licensing that may trigger compliance reviews in some organizations. If this is a concern, you can install Cyclopts v5 alpha (pip install "cyclopts>=5.0.0a1") which removes this dependency, or wait for the stable v5 release. Seethis issue for details.
These are the building blocks for creating MCP servers and clients with FastMCP.
The central object representing your MCP application. It holds your tools, resources, and prompts, manages connections, and can be configured with settings like authentication.
fromfastmcpimportFastMCP# Create a server instancemcp=FastMCP(name="MyAssistantServer")
Learn more in theFastMCP Server Documentation.
Tools allow LLMs to perform actions by executing your Python functions (sync or async). Ideal for computations, API calls, or side effects (likePOST/PUT). FastMCP handles schema generation from type hints and docstrings. Tools can return various types, including text, JSON-serializable objects, and even images or audio aided by the FastMCP media helper classes.
@mcp.tooldefmultiply(a:float,b:float)->float:"""Multiplies two numbers."""returna*b
Learn more in theTools Documentation.
Resources expose read-only data sources (likeGET requests). Use@mcp.resource("your://uri"). Use{placeholders} in the URI to create dynamic templates that accept parameters, allowing clients to request specific data subsets.
# Static resource@mcp.resource("config://version")defget_version():return"2.0.1"# Dynamic resource template@mcp.resource("users://{user_id}/profile")defget_profile(user_id:int):# Fetch profile for user_id...return {"name":f"User{user_id}","status":"active"}
Learn more in theResources & Templates Documentation.
Prompts define reusable message templates to guide LLM interactions. Decorate functions with@mcp.prompt. Return strings orMessage objects.
@mcp.promptdefsummarize_request(text:str)->str:"""Generate a prompt asking for a summary."""returnf"Please summarize the following text:\n\n{text}"
Learn more in thePrompts Documentation.
Access MCP session capabilities within your tools, resources, or prompts by adding actx: Context parameter. Context provides methods for:
- Logging: Log messages to MCP clients with
ctx.info(),ctx.error(), etc. - LLM Sampling: Use
ctx.sample()to request completions from the client's LLM. - Resource Access: Use
ctx.read_resource()to access resources on the server - Progress Reporting: Use
ctx.report_progress()to report progress to the client. - and more...
To access the context, add a parameter annotated asContext to any mcp-decorated function. FastMCP will automatically inject the correct context object when the function is called.
fromfastmcpimportFastMCP,Contextmcp=FastMCP("My MCP Server")@mcp.toolasyncdefprocess_data(uri:str,ctx:Context):# Log a message to the clientawaitctx.info(f"Processing{uri}...")# Read a resource from the serverdata=awaitctx.read_resource(uri)# Ask client LLM to summarize the datasummary=awaitctx.sample(f"Summarize:{data.content[:500]}")# Return the summaryreturnsummary.text
Learn more in theContext Documentation.
Interact withany MCP server programmatically using thefastmcp.Client. It supports various transports (Stdio, SSE, In-Memory) and often auto-detects the correct one. The client can also handle advanced patterns like server-initiatedLLM sampling requests if you provide an appropriate handler.
Critically, the client allows for efficientin-memory testing of your servers by connecting directly to aFastMCP server instance via theFastMCPTransport, eliminating the need for process management or network calls during tests.
fromfastmcpimportClientasyncdefmain():# Connect via stdio to a local scriptasyncwithClient("my_server.py")asclient:tools=awaitclient.list_tools()print(f"Available tools:{tools}")result=awaitclient.call_tool("add", {"a":5,"b":3})print(f"Result:{result.content[0].text}")# Connect via SSEasyncwithClient("http://localhost:8000/sse")asclient:# ... use the clientpass
To use clients to test servers, use the following pattern:
fromfastmcpimportFastMCP,Clientmcp=FastMCP("My MCP Server")asyncdefmain():# Connect via in-memory transportasyncwithClient(mcp)asclient:# ... use the client
FastMCP also supports connecting to multiple servers through a single unified client using the standard MCP configuration format:
fromfastmcpimportClient# Standard MCP configuration with multiple serversconfig= {"mcpServers": {"weather": {"url":"https://weather-api.example.com/mcp"},"assistant": {"command":"python","args": ["./assistant_server.py"]} }}# Create a client that connects to all serversclient=Client(config)asyncdefmain():asyncwithclient:# Access tools and resources with server prefixesforecast=awaitclient.call_tool("weather_get_forecast", {"city":"London"})answer=awaitclient.call_tool("assistant_answer_question", {"query":"What is MCP?"})
Learn more in theClient Documentation andTransports Documentation.
FastMCP provides comprehensive authentication support that sets it apart from basic MCP implementations. Secure your servers and authenticate your clients with the same enterprise-grade providers used by major corporations.
Built-in OAuth Providers:
- GitHub
- Microsoft Azure
- Auth0
- WorkOS
- Descope
- JWT/Custom
- API Keys
Protecting a server takes just two lines:
fromfastmcp.server.auth.providers.googleimportGoogleProviderauth=GoogleProvider(client_id="...",client_secret="...",base_url="https://myserver.com")mcp=FastMCP("Protected Server",auth=auth)
Connecting to protected servers is even simpler:
asyncwithClient("https://protected-server.com/mcp",auth="oauth")asclient:# Automatic browser-based OAuth flowresult=awaitclient.call_tool("protected_tool")
Why FastMCP Auth Matters:
- Production-Ready: Persistent storage, token refresh, comprehensive error handling
- Zero-Config OAuth: Just pass
auth="oauth"for automatic setup - Enterprise Integration: WorkOS SSO, Azure Active Directory, Auth0 tenants
- Developer Experience: Automatic browser launch, local callback server, environment variable support
- Advanced Architecture: Full OIDC support, Dynamic Client Registration (DCR), and unique OAuth proxy pattern that enables DCR with any provider
Authentication this comprehensive is unique to FastMCP 2.0.
Learn more in theAuthentication Documentation forservers andclients.
FastMCP supports every deployment scenario from local development to global scale:
Development: Run locally with a single command
fastmcp run server.py
Production: Deploy toFastMCP Cloud — Remote MCP that just works
- Instant HTTPS endpoints
- Built-in authentication
- Zero configuration
- Free for personal servers
Self-Hosted: Use HTTP or SSE transports for your own infrastructure
mcp.run(transport="http",host="0.0.0.0",port=8000)
Learn more in theDeployment Documentation.
FastMCP introduces powerful ways to structure and compose your MCP applications.
Create a FastMCP server that acts as an intermediary for another local or remote MCP server usingFastMCP.as_proxy(). This is especially useful for bridging transports (e.g., remote SSE to local Stdio) or adding a layer of logic to a server you don't control.
Learn more in theProxying Documentation.
Build modular applications by mounting multipleFastMCP instances onto a parent server usingmcp.mount() (live link) ormcp.import_server() (static copy).
Learn more in theComposition Documentation.
Automatically generate FastMCP servers from existing OpenAPI specifications (FastMCP.from_openapi()) or FastAPI applications (FastMCP.from_fastapi()), instantly bringing your web APIs to the MCP ecosystem.
Learn more:OpenAPI Integration |FastAPI Integration.
The main way to run a FastMCP server is by calling therun() method on your server instance:
# server.pyfromfastmcpimportFastMCPmcp=FastMCP("Demo 🚀")@mcp.tooldefhello(name:str)->str:returnf"Hello,{name}!"if__name__=="__main__":mcp.run()# Default: uses STDIO transport
FastMCP supports three transport protocols:
STDIO (Default): Best for local tools and command-line scripts.
mcp.run(transport="stdio")# Default, so transport argument is optional
Streamable HTTP: Recommended for web deployments.
mcp.run(transport="http",host="127.0.0.1",port=8000,path="/mcp")
SSE: For compatibility with existing SSE clients.
mcp.run(transport="sse",host="127.0.0.1",port=8000)
See theRunning Server Documentation for more details.
Contributions are the core of open source! We welcome improvements and features.
- Python 3.10+
- uv (Recommended for environment management)
Clone the repository:
git clone https://github.com/jlowin/fastmcp.gitcd fastmcpCreate and sync the environment:
uv sync
This installs all dependencies, including dev tools.
Activate the virtual environment (e.g.,
source .venv/bin/activateor via your IDE).
FastMCP has a comprehensive unit test suite. All PRs must introduce or update tests as appropriate and pass the full suite.
Run tests using pytest:
pytest
or if you want an overview of the code coverage
uv run pytest --cov=src --cov=examples --cov-report=html
FastMCP usesprek for code formatting, linting, and type-checking. All PRs must pass these checks (they run automatically in CI).
Install the hooks locally:
uv run prek install
The hooks will now run automatically ongit commit. You can also run them manually at any time:
prek run --all-files# or via uvuv run prek run --all-files- Fork the repository on GitHub.
- Create a feature branch from
main. - Make your changes, including tests and documentation updates.
- Ensure tests and prek hooks pass.
- Commit your changes and push to your fork.
- Open a pull request against the
mainbranch ofjlowin/fastmcp.
Please open an issue or discussion for questions or suggestions before starting significant work!
About
🚀 The fast, Pythonic way to build MCP servers and clients
Topics
Resources
License
Code of conduct
Security policy
Uh oh!
There was an error while loading.Please reload this page.
