news 2026/6/14 19:17:59

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/6/15 12:51:53

2025 AtomGit 最受欢迎 G-Star 项目 组织评选活动火热进行中!

2025 AtomGit 最受欢迎 G-Star 项目 & 组织评选活动火热进行中!本次活动面向全体 G-Star 认证个人项目、G-Star 认证开源组织。分个人和组织两个赛道,以项目/组织在 AtomGit 平台的 star 数、贡献者数、仓库数进行综合排名。最终评选出的前 40 名个人…

作者头像 李华
网站建设 2026/6/15 12:15:48

4.14、云原生安全攻防:容器与 Kubernetes 的脆弱点

——从容器逃逸到集群接管的真实攻击面解析“Kubernetes 不是不安全,而是你以为它只是个调度器。”随着企业全面上云、微服务化加速,Kubernetes 已经成为云原生事实标准。但在攻防视角下,K8s 同时也是一个攻击面极其丰富、配置极易出错的系统…

作者头像 李华
网站建设 2026/6/15 12:17:07

Ubuntu安装后必做的10项配置,包括PyTorch环境准备

Ubuntu安装后必做的10项配置,包括PyTorch环境准备 在一台全新的Ubuntu系统上按下回车完成安装的那一刻,真正的挑战才刚刚开始——尤其是对于AI开发者而言。你面对的不是一张白纸,而是一块未经雕琢的璞玉:没有GPU加速、没有深度学…

作者头像 李华
网站建设 2026/6/15 12:15:41

一键转换f4v视频至mkv格式技巧

日常生活中,我们常常会遇到老旧或特定平台专属格式的兼容性问题。F4V 作为 Adobe Flash 平台后期推出的高清视频封装格式。MKV是一种开源、灵活且功能强大的多媒体容器格式。接下来跟各位讲讲f4v转换mkv格式的方法。一、格式简介F4V 格式:是 Adobe 为 Fl…

作者头像 李华
网站建设 2026/6/15 12:16:49

【Docker】【实战】------- jar包裸运行 vs Docker 实战中的好处和对比

在百万级用户、10万级并发的高压力场景下,优先选择Docker(或容器化)方式部署10个Java服务,而非直接java -jar裸运行。核心原因是:高并发场景对服务的稳定性、可运维性、资源隔离、弹性扩展和故障恢复能力要求极高&…

作者头像 李华
网站建设 2026/6/15 12:19:07

Modbus协议C语言实现(易于移植版本)

易于移植的Modbus协议栈的C语言实现&#xff0c;支持RTU和ASCII模式&#xff0c;包含主机(Master)和从机(Slave)功能。 头文件 (modbus.h) #ifndef MODBUS_H #define MODBUS_H#include <stdint.h> #include <stddef.h>// 模式定义 typedef enum {MODBUS_RTU,MODB…

作者头像 李华