fastmcp

2天前发布 8 0 0

FastMCP 是一个专门为开发 MCP 服务器和客户端设计的开源 Python 框架。

收录时间:
2025-06-11

主要特性

  • 简洁优雅的装饰器语法:使用简单 Python 装饰器定义 MCP 工具/资源/提示
  • 工具链支持:快速组合多个工具,支持单工具、多工具、组合式智能体
  • API 集成:内置 OpenAPI/FastAPI 支持,一键将现有 API 转为 MCP 服务
  • 图像处理原生支持:内置了图像处理模块,轻松搞定图像上传、压缩、转码等操作
  • LLM 客户端功能:支持连接任意 MCP 服务器,自动检测传输协议

快速上手

FastMCP 推荐使用 uv 安装,因为它是通过CLI部署服务器所必需的。安装环境支持 Python 3.8+ 以上。

uv pip install fastmcp

提示:在macOS上,可能需要使用 Homebrew 安装 uv(brew install uv),以便使其对Claude桌面应用程序可用。

对于开发者来说,可以参考以下命令安装:

# 克隆仓库
git clone https://github.com/jlowin/fastmcp.git
cd fastmcp
# 安装开发依赖
uv sync

创建一个简单的MCP服务器(公开一个计算器工具和一些数据)

# server.py
from fastmcp import FastMCP

# Create an MCP server
mcp = FastMCP("Demo")

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

# Add a dynamic greeting resource
@mcp.resource("greeting://{name}")
def get_greeting(name: str) -> str:
    """Get a personalized greeting"""
    return f"Hello, {name}!"

然后可以在Claude Desktop中安装此服务器

{
  "mcpServers": [
    {
      "name": "server",
      "url": "http://localhost:8000/mcp"
    }
  ]
}

并通过运行以下命令立即与其交互:

fastmcp install server.py

使用fastmcp.Image辅助类轻松处理图像输出。

from mcp.server.fastmcp import FastMCP, Image
from io import BytesIO
try:
    from PIL import Image as PILImage
except ImportError:
    raise ImportError("Please install the `pillow` library to run this example.")

mcp = FastMCP("My App")

@mcp.tool()
def create_thumbnail(image_path: str) -> Image:
    """Create a thumbnail from an image"""
    img = PILImage.open(image_path)
    img.thumbnail((100, 100))    
    buffer = BytesIO()
    img.save(buffer, format="PNG")
    return Image(data=buffer.getvalue(), format="png")

它将工具中的Image助手类返回,以向客户端发送图像。Image助手类负责处理MCP协议所需的base64编码格式的转换。它可以使用图像文件的路径,也可以使用字节对象。

MCP Client 类允许你从 Python 代码与任何 MCP 服务器(不仅仅是 FastMCP)进行交互:

from fastmcp import Client

async with Client("path/to/server") as client:
    # Call a tool
    result = await client.call_tool("weather", {"location": "San Francisco"})
    print(result)
    
    # Read a resource
    res = await client.read_resource("db://users/123/profile")
    print(res)

与 FastAPI 交互:

from fastapi import FastAPI
from fastmcp import FastMCP

# Your existing FastAPI application
fastapi_app = FastAPI(title="My Existing API")

@fastapi_app.get("/status")
def get_status(): 
    return {"status": "running"}

@fastapi_app.post("/items")
def create_item(name: str, price: float): 
    return {"id": 1, "name": name, "price": price}

# Generate an MCP server directly from the FastAPI app
mcp_server = FastMCP.from_fastapi(fastapi_app)

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

FastMCP 还有更多关于工具、资源、LLM、服务端、客户端等高级用法和参数说明,可以参考项目文档进行操作。

支持的开发场景

  • 私人助手搭建:快速搭建本地 MCP Server,整合各类小工具
  • Agent 工具集成:给你的智能体加上浏览器、搜索、计算、图像识别等新技能
  • 文档/知识问答:接 OpenAPI 现有服务,快速让 LLM 调用外部知识库
  • 多模态应用开发:结合图像输入输出,做图文问答、OCR、图像生成

写在最后

FastMCP 提供了一个高级的、Pythonic 的接口,用于构建,并与主流线上的MCP服务器交互。

可能以往,你自己搭 MCP 服务器,就像是一场体力活:到处找例子,研究协议规范,配环境,写成千上万行Demo代码,搞得精疲力尽。

而现在,有了 FastMCP,你可以把更多精力花在创造真正有价值的功能和体验上。

少了繁琐细节、有了更快的原型验证及更优开发体验。

所以,无论你是想打造下一个爆款应用,还是仅仅想搭个好用的智能体工具,FastMCP 都是你绝对值得收藏和上手的那把“开发利器”。

数据统计

相关导航