快速、Pythonic的方式构建MCP服务器和客户端的开源框架

Apache-2.0Pythonfastmcpjlowin 15.8k Last Updated: August 06, 2025

FastMCP - 快速构建MCP服务器和客户端的Python框架

项目概述

FastMCP是一个用于构建Model Context Protocol (MCP)服务器和客户端的高级Python框架,旨在让开发者能够快速、简洁地创建工具、暴露资源、定义提示并连接组件。该项目由GitHub用户jlowin开发维护,已经成为MCP生态系统中的重要组成部分。

为什么选择FastMCP?

虽然MCP协议功能强大,但实现它需要大量样板代码 - 服务器设置、协议处理程序、内容类型、错误管理等。FastMCP处理所有复杂的协议细节和服务器管理,让您专注于构建优秀的工具。

FastMCP的设计目标:

  • 🚀 快速:高级接口意味着更少的代码和更快的开发
  • 🍀 简单:用最少的样板代码构建MCP服务器
  • 🐍 Pythonic:对Python开发者感觉自然
  • 🔍 完整:提供MCP核心规范的完整实现,支持服务器和客户端

核心功能特性

基础功能

  • 使用直观装饰器创建服务器,样板代码最少
  • 代理现有服务器来修改配置或传输方式
  • 将服务器组合成复杂应用
  • 从OpenAPI规范或FastAPI对象生成服务器
  • 以编程方式与MCP服务器交互
  • 使用任何传输协议连接到任何MCP服务器
  • 无需手动干预即可测试服务器
  • 利用核心MCP功能,如LLM采样

版本演进

FastMCP 1.0使构建MCP服务器变得如此简单,以至于它现在已经成为官方Model Context Protocol Python SDK的一部分!

FastMCP 2.0在此基础上引入了多种新功能:

  • 代理和组合MCP服务器等高级功能
  • 从OpenAPI规范或FastAPI对象自动生成服务器
  • 引入客户端功能,如LLM采样

安装方法

推荐使用uv安装FastMCP:

uv pip install fastmcp

开发安装:


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()

安装到Claude Desktop:

fastmcp install server.py

核心概念详解

1. FastMCP实例

代表MCP应用的中心对象,处理连接、协议细节和路由:

from fastmcp import FastMCP


mcp = FastMCP("My App")


mcp = FastMCP("My App", dependencies=["pandas", "numpy"])

2. 工具(Tools)

允许LLM通过执行Python函数来执行操作,适用于计算、外部API调用或副作用:

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)

向LLM暴露数据,主要提供信息而不进行重大计算或副作用:


@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)

定义可重用的模板或交互模式:

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?")
    ]

高级功能

1. 代理服务器

创建充当中介的FastMCP服务器,代理对另一个MCP端点的请求:

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. 服务器组合

通过创建模块化FastMCP服务器并将它们"挂载"到父服务器上来构建大型MCP应用:

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. 从API生成服务器

从现有Web API自动生成FastMCP服务器:

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. 客户端功能

与任何MCP服务器进行交互:

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()

示例项目

项目包含多个示例文件:

  • simple_echo.py: 基本工具、资源和提示
  • complex_inputs.py: 使用Pydantic模型作为工具输入
  • mount_example.py: 挂载多个FastMCP服务器
  • sampling.py: 在MCP服务器中使用LLM完成
  • screenshot.py: 返回Image对象的工具
  • text_me.py: 与外部API交互的工具
  • memory.py: 带数据库交互的复杂示例

贡献指南

FastMCP欢迎社区贡献:

环境要求

  • Python 3.10+
  • uv包管理器

开发设置

git clone https://github.com/jlowin/fastmcp.git && cd fastmcp
uv venv && uv sync

测试

uv run pytest -vv

代码质量

使用ruffpre-commit

pre-commit install
pre-commit run --all-files

项目意义

FastMCP填补了MCP协议实现和实际应用开发之间的空白,让开发者能够:

  1. 快速原型化和部署MCP服务器
  2. 轻松集成现有API和数据源
  3. 构建模块化、可扩展的AI应用架构
  4. 专注于业务逻辑而不是协议实现细节

Star History Chart