官方文档地址:https://gofastmcp.com/
创建一个服务
一个简单的服务
fromfastmcpimportFastMCP# Create a basic server instancemcp=FastMCP(name="MyAssistantServer")# You can also add instructions for how to interact with the servermcp_with_instructions=FastMCP(name="HelpfulAssistant",instructions=""" This server provides data analysis tools. Call get_average() to analyze numerical data. """,)参数解释
- name mcp服务的名称
- instructions mcp服务的描述,帮助客户端了解服务的目的和提供的功能。
组件
Tools
Tools是一个函数,它可以被用于执行动作或者访问外部系统。@mcp.tooldefmultiply(a:float,b:float)->float:"""Multiplies two numbers together."""returna*bResources
资源会暴露客户端可以读取的数据源。@mcp.resource("data://config")defget_config()->dict:"""Provides the application configuration."""return{"theme":"dark","version":"1.0"}Resource Template
资源模板是参数化的资源,允许客户端请求特定数据。@mcp.resource("users://{user_id}/profile")defget_user_profile(user_id:int)->dict:"""Retrieves a user's profile by ID."""# The {user_id} in the URI is extracted and passed to this functionreturn{"id":user_id,"name":f"User{user_id}","status":"active"}Prompts
提示词是用于指导大语言模型(LLM)的可重复使用的消息模板。@mcp.promptdefanalyze_data(data_points:list[float])->str:"""Creates a prompt asking for analysis of numerical data."""formatted_data=", ".join(str(point)forpointindata_points)returnf"Please analyze these data points:{formatted_data}"Tag-Based Filtering
FastMCP 支持基于标签的过滤,可根据配置的包含 / 排除标签集有选择地展示组件。这对于为不同环境或用户创建服务器的不同视图非常有用。@mcp.tool(tags={"public","utility"})defpublic_tool()->str:return"This tool is public"@mcp.tool(tags={"internal","admin"})defadmin_tool()->str:return"This tool is for admins only"- Include tags: 如果指定了(标签),则仅公开至少有一个匹配标签的组件
- Exclude tags: 任何带有匹配标签的组件都会被过滤掉
- Precedence: 排除标签始终优先于包含标签(先排除,再匹配)
# Only expose components tagged with "public"mcp=FastMCP(include_tags={"public"})# Hide components tagged as "internal" or "deprecated"mcp=FastMCP(exclude_tags={"internal","deprecated"})# Combine both: show admin tools but hide deprecated onesmcp=FastMCP(include_tags={"admin"},exclude_tags={"deprecated"})Running the Server
FastMCP 服务器需要一种传输机制来与客户端进行通信。通常,你可以通过在 FastMCP 实例上调用 mcp.run () 方法来启动服务器,这一操作常在主服务器脚本的 if name == "main": 代码块中进行。这种模式能确保与各种 MCP 客户端的兼容性。# my_server.pyfromfastmcpimportFastMCP mcp=FastMCP(name="MyServer")@mcp.tooldefgreet(name:str)->str:"""Greet a user by name."""returnf"Hello,{name}!"if__name__=="__main__":# This runs the server, defaulting to STDIO transportmcp.run()# To use a different transport, e.g., HTTP:# mcp.run(transport="http", host="127.0.0.1", port=9000)FastMCP 支持多种传输选项:
- STDIO (default, for local tools)
- HTTP (recommended for web services, uses Streamable HTTP protocol)
- SSE (legacy web transport, deprecated)
Custom Routes
当使用 HTTP 传输协议运行服务器时,你可以借助 @custom_route 装饰器,在 MCP 端点旁添加自定义 Web 路由。这对于像健康检查这样的简单端点很有用,它们需要与 MCP 服务器一同提供服务:fromfastmcpimportFastMCPfromstarlette.requestsimportRequestfromstarlette.responsesimportPlainTextResponse mcp=FastMCP("MyServer")@mcp.custom_route("/health",methods=["GET"])asyncdefhealth_check(request:Request)->PlainTextResponse:returnPlainTextResponse("OK")if__name__=="__main__":mcp.run(transport="http")# Health check at http://localhost:8000/healthComposing Servers
FastMCP 支持通过 import_server(静态复制)和 mount(实时链接)将多个服务器组合在一起。这使您能够将大型应用程序组织成模块化组件,或者重用现有的服务器。# Example: Importing a subserverfromfastmcpimportFastMCPimportasyncio main=FastMCP(name="Main")sub=FastMCP(name="Sub")@sub.tooldefhello():return"hi"# Mount directlymain.mount(sub,prefix="sub")Proxying Servers
FastMCP 可以通过 FastMCP.as_proxy 充当任何 MCP 服务器(本地或远程)的代理,让你能够桥接传输方式或为现有服务器添加前端。例如,你可以通过标准输入输出在本地暴露远程 SSE 服务器,反之亦然。 当使用断开连接的客户端时,代理会为每个请求创建新的会话,从而自动安全地处理并发操作。fromfastmcpimportFastMCP,Client backend=Client("http://example.com/mcp/sse")proxy=FastMCP.as_proxy(backend,name="ProxyServer")# Now use the proxy like any FastMCP serverOpenAPI Integration
FastMCP 可以使用 FastMCP.from_openapi () 和 FastMCP.from_fastapi () 从 OpenAPI 规范或现有的 FastAPI 应用程序自动生成服务器。这使您能够立即将现有的 API 转换为 MCP 服务器,而无需手动创建工具。importhttpxfromfastmcpimportFastMCP# From OpenAPI specspec=httpx.get("https://api.example.com/openapi.json").json()mcp=FastMCP.from_openapi(openapi_spec=spec,client=httpx.AsyncClient())# From FastAPI appfromfastapiimportFastAPI app=FastAPI()mcp=FastMCP.from_fastapi(app=app)Server Configuration
服务器可以通过初始化参数、全局设置和特定于传输的设置相结合的方式进行配置。Server-Specific Configuration
特定于服务器的设置在创建 FastMCP 实例时传递,并控制服务器行为:fromfastmcpimportFastMCP# Configure server-specific settingsmcp=FastMCP(name="ConfiguredServer",include_tags={"public","api"},# Only expose these tagged componentsexclude_tags={"internal","deprecated"},# Hide these tagged componentson_duplicate_tools="error",# Handle duplicate registrationson_duplicate_resources="warn",on_duplicate_prompts="replace",include_fastmcp_meta=False,# Disable FastMCP metadata for cleaner integration)Global Settings
全局设置会影响所有 FastMCP 服务器,可通过环境变量(前缀为 FASTMCP_)或.env 文件进行配置:importfastmcp# Access global settingsprint(fastmcp.settings.log_level)# Default: "INFO"print(fastmcp.settings.mask_error_details)# Default: Falseprint(fastmcp.settings.strict_input_validation)# Default: Falseprint(fastmcp.settings.include_fastmcp_meta)# Default: TrueTransport-Specific Configuration
传输设置在运行服务器时提供,并控制网络行为# Configure transport when runningmcp.run(transport="http",host="0.0.0.0",# Bind to all interfacesport=9000,# Custom portlog_level="DEBUG",# Override global log level)# Or for async usageawaitmcp.run_async(transport="http",host="127.0.0.1",port=8080,)Setting Global Configuration
全局 FastMCP 设置可通过环境变量(以 FASTMCP_为前缀)进行配置。
# Configure global FastMCP behaviorexport FASTMCP_LOG_LEVEL=DEBUG export FASTMCP_MASK_ERROR_DETAILS=Trueexport FASTMCP_STRICT_INPUT_VALIDATION=Falseexport FASTMCP_INCLUDE_FASTMCP_META=FalseCustom Tool Serialization
默认情况下,当需要将工具返回值转换为文本时,FastMCP 会将其序列化为 JSON。你可以在创建服务器时提供一个 tool_serializer 函数来自定义此行为:importyamlfromfastmcpimportFastMCP# Define a custom serializer that formats dictionaries as YAMLdefyaml_serializer(data):returnyaml.dump(data,sort_keys=False)# Create a server with the custom serializermcp=FastMCP(name="MyServer",tool_serializer=yaml_serializer)@mcp.tooldefget_config():"""Returns configuration in YAML format."""return{"api_key":"abc123","debug":True,"rate_limit":100}