1 Star 3 Fork 2

Gitee 极速下载/fastmcp

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
此仓库是为了提升国内下载速度的镜像仓库,每日同步一次。 原始仓库: https://github.com/jlowin/fastmcp
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

FastMCP v2 🚀

The fast, Pythonic way to build MCP servers and clients.

Docs PyPI - Version Tests License

jlowin%2Ffastmcp | Trendshift

[!NOTE]

FastMCP 2.0 & The Official MCP SDK

FastMCP is the standard framework for building MCP servers and clients. FastMCP 1.0 was incorporated into the official MCP Python SDK.

This is FastMCP 2.0, the actively maintained version that significantly expands on 1.0's basic server-building capabilities by introducing full client support, server composition, OpenAPI/FastAPI integration, remote server proxying, built-in testing tools, and more.

FastMCP 2.0 is the complete toolkit for modern AI applications. Ready to upgrade or get started? Follow the installation instructions, which include specific steps for upgrading from the official MCP SDK.


The Model Context Protocol (MCP) is a new, standardized way to provide context and tools to your LLMs, and FastMCP makes building MCP servers and clients simple and intuitive. Create tools, expose resources, define prompts, and connect components with clean, Pythonic code.

# server.py
from fastmcp import FastMCP

mcp = FastMCP("Demo 🚀")

@mcp.tool()
def add(a: int, b: int) -> int:
    """Add two numbers"""
    return a + b

if __name__ == "__main__":
    mcp.run()

Run the server locally:

fastmcp run server.py

📚 Documentation

FastMCP's complete documentation is available at gofastmcp.com, including detailed guides, API references, and advanced patterns. This readme provides only a high-level overview.

Documentation is also available in llms.txt format, which is a simple markdown standard that LLMs can consume easily.

There are two ways to access the LLM-friendly documentation:

  • llms.txt is essentially a sitemap, listing all the pages in the documentation.
  • llms-full.txt contains the entire documentation. Note this may exceed the context window of your LLM.

Table of Contents


What is MCP?

The Model Context Protocol (MCP) lets you build servers that expose data and functionality to LLM applications in a secure, standardized way. Think of it like a web API, but specifically designed for LLM interactions. MCP servers can:

  • Expose data through Resources (similar to GET requests; load info into context)
  • Provide functionality through Tools (similar to POST/PUT requests; execute actions)
  • Define interaction patterns through Prompts (reusable templates)
  • And more!

FastMCP provides a high-level, Pythonic interface for building and interacting with these servers.

Why FastMCP?

The MCP protocol is powerful but implementing it involves a lot of boilerplate - server setup, protocol handlers, content types, error management. FastMCP handles all the complex protocol details and server management, so you can focus on building great tools. It's designed to be high-level and Pythonic; in most cases, decorating a function is all you need.

While the core server concepts of FastMCP 1.0 laid the groundwork and were contributed to the official MCP SDK, FastMCP 2.0 (this project) is the actively developed successor, adding significant enhancements and entirely new capabilities like a powerful client library, server proxying, composition patterns, OpenAPI/FastAPI integration, and much more.

FastMCP aims to be:

🚀 Fast: High-level interface means less code and faster development

🍀 Simple: Build MCP servers with minimal boilerplate

🐍 Pythonic: Feels natural to Python developers

🔍 Complete: FastMCP aims to provide a full implementation of the core MCP specification for both servers and clients

Installation

We recommend installing FastMCP with uv:

uv pip install fastmcp

For full installation instructions, including verification, upgrading from the official MCPSDK, and developer setup, see the Installation Guide.

Core Concepts

These are the building blocks for creating MCP servers and clients with FastMCP.

The FastMCP Server

The central object representing your MCP application. It holds your tools, resources, and prompts, manages connections, and can be configured with settings like authentication providers.

from fastmcp import FastMCP

# Create a server instance
mcp = FastMCP(name="MyAssistantServer")

Learn more in the FastMCP Server Documentation.

Tools

Tools allow LLMs to perform actions by executing your Python functions (sync or async). Ideal for computations, API calls, or side effects (like POST/PUT). FastMCP handles schema generation from type hints and docstrings. Tools can return various types, including text, JSON-serializable objects, and even images using the fastmcp.Image helper.

@mcp.tool()
def multiply(a: float, b: float) -> float:
    """Multiplies two numbers."""
    return a * b

Learn more in the Tools Documentation.

Resources & Templates

Resources expose read-only data sources (like GET 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")
def get_version(): 
    return "2.0.1"

# Dynamic resource template
@mcp.resource("users://{user_id}/profile")
def get_profile(user_id: int):
    # Fetch profile for user_id...
    return {"name": f"User {user_id}", "status": "active"}

Learn more in the Resources & Templates Documentation.

Prompts

Prompts define reusable message templates to guide LLM interactions. Decorate functions with @mcp.prompt(). Return strings or Message objects.

@mcp.prompt()
def summarize_request(text: str) -> str:
    """Generate a prompt asking for a summary."""
    return f"Please summarize the following text:\n\n{text}"

Learn more in the Prompts Documentation.

Context

Access MCP session capabilities within your tools, resources, or prompts by adding a ctx: 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.
  • HTTP Request: Use ctx.http_request() to make HTTP requests to other servers.
  • 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 as Context to any mcp-decorated function. FastMCP will automatically inject the correct context object when the function is called.

from fastmcp import FastMCP, Context

mcp = FastMCP("My MCP Server")

@mcp.tool()
async def process_data(uri: str, ctx: Context):
    # Log a message to the client
    await ctx.info(f"Processing {uri}...")

    # Read a resource from the server
    data = await ctx.read_resource(uri)

    # Ask client LLM to summarize the data
    summary = await ctx.sample(f"Summarize: {data.content[:500]}")

    # Return the summary
    return summary.text

Learn more in the Context Documentation.

MCP Clients

Interact with any MCP server programmatically using the fastmcp.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-initiated LLM sampling requests if you provide an appropriate handler.

Critically, the client allows for efficient in-memory testing of your servers by connecting directly to a FastMCP server instance via the FastMCPTransport, eliminating the need for process management or network calls during tests.

from fastmcp import Client

async def main():
    # Connect via stdio to a local script
    async with Client("my_server.py") as client:
        tools = await client.list_tools()
        print(f"Available tools: {tools}")
        result = await client.call_tool("add", {"a": 5, "b": 3})
        print(f"Result: {result.text}")

    # Connect via SSE
    async with Client("http://localhost:8000/sse") as client:
        # ... use the client
        pass

To use clients to test servers, use the following pattern:

from fastmcp import FastMCP, Client

mcp = FastMCP("My MCP Server")

async def main():
    # Connect via in-memory transport
    async with Client(mcp) as client:
        # ... use the client

FastMCP also supports connecting to multiple servers through a single unified client using the standard MCP configuration format:

from fastmcp import Client

# Standard MCP configuration with multiple servers
config = {
    "mcpServers": {
        "weather": {"url": "https://weather-api.example.com/mcp"},
        "assistant": {"command": "python", "args": ["./assistant_server.py"]}
    }
}

# Create a client that connects to all servers
client = Client(config)

async def main():
    async with client:
        # Access tools and resources with server prefixes
        forecast = await client.call_tool("weather_get_forecast", {"city": "London"})
        answer = await client.call_tool("assistant_answer_question", {"query": "What is MCP?"})

Learn more in the Client Documentation and Transports Documentation.

Advanced Features

FastMCP introduces powerful ways to structure and deploy your MCP applications.

Proxy Servers

Create a FastMCP server that acts as an intermediary for another local or remote MCP server using FastMCP.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 the Proxying Documentation.

Composing MCP Servers

Build modular applications by mounting multiple FastMCP instances onto a parent server using mcp.mount() (live link) or mcp.import_server() (static copy).

Learn more in the Composition Documentation.

OpenAPI & FastAPI Generation

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.

Running Your Server

The main way to run a FastMCP server is by calling the run() method on your server instance:

# server.py
from fastmcp import FastMCP

mcp = FastMCP("Demo 🚀")

@mcp.tool()
def hello(name: str) -> str:
    return f"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="streamable-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 the Running Server Documentation for more details.

Contributing

Contributions are the core of open source! We welcome improvements and features.

Prerequisites

  • Python 3.10+
  • uv (Recommended for environment management)

Setup

  1. Clone the repository:

    git clone https://github.com/jlowin/fastmcp.git 
    cd fastmcp
    
  2. Create and sync the environment:

    uv sync
    

    This installs all dependencies, including dev tools.

  3. Activate the virtual environment (e.g., source .venv/bin/activate or via your IDE).

Unit Tests

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

Static Checks

FastMCP uses pre-commit for code formatting, linting, and type-checking. All PRs must pass these checks (they run automatically in CI).

Install the hooks locally:

uv run pre-commit install

The hooks will now run automatically on git commit. You can also run them manually at any time:

pre-commit run --all-files
# or via uv
uv run pre-commit run --all-files

Pull Requests

  1. Fork the repository on GitHub.
  2. Create a feature branch from main.
  3. Make your changes, including tests and documentation updates.
  4. Ensure tests and pre-commit hooks pass.
  5. Commit your changes and push to your fork.
  6. Open a pull request against the main branch of jlowin/fastmcp.

Please open an issue or discussion for questions or suggestions before starting significant work!

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

FastMCP 使构建 MCP 服务器变得简单而直观 展开 收起
README
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

语言

近期动态

不能加载更多了
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/mirrors/fastmcp.git
git@gitee.com:mirrors/fastmcp.git
mirrors
fastmcp
fastmcp
main

搜索帮助