news 2026/4/18 10:45:06

FastMCP之Overview

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
FastMCP之Overview

官方文档地址: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*b
Resources
资源会暴露客户端可以读取的数据源。
@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/health
Composing 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 server
OpenAPI 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: True
Transport-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=False
Custom 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}
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/18 1:16:52

操作系统 虚拟机

KVM https://cloud.tencent.com/developer/article/1444658

作者头像 李华
网站建设 2026/4/18 8:07:31

Linux 之 HugePage

参考链接 https://cloud.tencent.com/developer/article/2088122 https://help.aliyun.com/zh/alinux/support/performance-tuning-method-related-to-transparent-large-page-thp-in?spm0.0.0.i0 https://mp.weixin.qq.com/s/_JFLSehF-YaW40a_CmyyHg https://mp.weixin.qq.co…

作者头像 李华
网站建设 2026/4/18 0:03:12

如何使用curl进行网页抓取:完整教程

文章目录前言什么是curl以及为什么用它进行网页抓取?开发者喜欢curl进行抓取的原因curl不够用的时候入门:安装和设置curl检查curl是否已安装按操作系统安装验证您的安装用于网页抓取的基本curl命令理解curl语法获取网页的HTML将输出保存到文件跟随重定向…

作者头像 李华
网站建设 2026/4/18 6:32:11

电商大促期软件许可管控:动态调配应对流量峰值资源荒

电商大促期软件许可管控:动态调配应对流量峰值资源荒问题:电商大促期间的软件许可资源调度难题每年双十一大促、618、或者情人节、黑色星期五这些节点,电商平台都会经历流量的指数级飙升。不管你是天猫、京东,还是拼多多、唯品会&…

作者头像 李华
网站建设 2026/4/17 14:17:20

好写作AI:在创意写作课里,我是工具、伙伴,还是“灵感外挂”?

当一位创意写作课的老师发现,班上最内向的学生因为和AI讨论剧情而眼睛发亮时,她意识到,关于AI角色的争论或许该换个问法了。 深夜的创作工作坊里,大三学生小陈对着“科幻爱情”的命题抓耳挠腮。她打开好写作AI,输入了第…

作者头像 李华