
Cursor
地表最强Ai写代码工具。
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、服务端、客户端等高级用法和参数说明,可以参考项目文档进行操作。
FastMCP 提供了一个高级的、Pythonic 的接口,用于构建,并与主流线上的MCP服务器交互。
可能以往,你自己搭 MCP 服务器,就像是一场体力活:到处找例子,研究协议规范,配环境,写成千上万行Demo代码,搞得精疲力尽。
而现在,有了 FastMCP,你可以把更多精力花在创造真正有价值的功能和体验上。
少了繁琐细节、有了更快的原型验证及更优开发体验。
所以,无论你是想打造下一个爆款应用,还是仅仅想搭个好用的智能体工具,FastMCP 都是你绝对值得收藏和上手的那把“开发利器”。