当前位置: 首页 > news >正文

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}
http://www.cnnetsun.cn/news/67096.html

相关文章:

  • 使用PyTorch训练微调Qwen3-14B的入门级教程
  • 从代码看BuildingAI:企业级智能体平台设计解析
  • 负责处理大数据量的Excel导出功能
  • JMeter---正则表达式提取器
  • 如何利用diskinfo下载官网资源优化Qwen3-VL-8B存储性能
  • 量子电导式氢气浓度检测仪在制氢系统中的优势
  • 牛了个牛,做好功能测试就靠“它”
  • AutoGPT任务执行风险预警系统设计理念
  • 树形结构遍历与递归应用解析
  • 雷科电力-REKE2195电缆路径及定位仪
  • 轻量级部署方案:LobeChat在树莓派上的可行性实验
  • 口碑是营销出来的?格行真实用户实测:网速和售后真有那么好? “流量靠猜”“网速成迷”3 大场景实测给答案
  • AI搜索排名GEO优化服务商行业排行榜
  • AutoGPT支持Apple Silicon芯片加速了吗?M系列Mac实测
  • LWGANet:两大核心模块:TGFI(减空间冗余)和 LWGA(减通道冗余。
  • 如何用AI大数据在1秒内构建完整客户画像,获取高质量线索的源码系统
  • 好写作AI:专治学术“写作困难户”,让你告别深夜emo和DDL恐惧!
  • 好写作AI:论文格式“救星”,一键告别“调参”噩梦
  • halcon3d 求角平分面
  • 家校沟通不用“猜”,小二查成绩让每分进步都清晰可见
  • 云服务器邂逅英伟达B200:AI算力革命的黄金搭档
  • Qwen3-14B在编程与数学推理中的表现评测
  • AutoGPT在非营利组织运营管理中的价值体现
  • MyBatis基础入门《十五》分布式事务实战:Seata + MyBatis 实现跨服务数据一致性
  • 行为学实验室整体解决方案 动物行为学整体解决方案
  • 【前端】从零开始搭建现代前端框架:React 19、Vite、Tailwind CSS、ShadCN UI-第五章《主题(Theme)系统 —— Light / Dark / System》
  • 从零开始部署Qwen3-8B:VSCode安装调试全流程
  • LU,数显式脑立体定位仪 大鼠脑定位仪 小鼠脑定位仪 小动物脑定位仪
  • 2025年geo系统源码开发公司技术方案有那些
  • 一文带你了解使用ARP欺骗的中间人 (MiTM) 攻击,黑客技术零基础入门到精通教程!