FastMCP高级特性之Message Handling

消息

前面讲到,服务端可以发送消息。对于发送的消息,可以使用自定义消息处理器处理 MCP 消息、请求和通知。

MCP 客户端可以从服务器接收各种类型的消息,包括需要响应的请求和不需要响应的通知。消息处理器提供了一种统一的方式来处理所有这些消息。

Function-Based Handler

处理消息最简单的方法是使用一个接收所有消息的函数:

python 复制代码
from fastmcp import Client

async def message_handler(message):
    """Handle all MCP messages from the server."""
    if hasattr(message, 'root'):
        method = message.root.method
        print(f"Received: {method}")
        
        # Handle specific notifications
        if method == "notifications/tools/list_changed":
            print("Tools have changed - might want to refresh tool cache")
        elif method == "notifications/resources/list_changed":
            print("Resources have changed")

client = Client(
    "my_mcp_server.py",
    message_handler=message_handler,
)

Message Handler Class

为了实现细粒度的目标定位,FastMCP 提供了一个MessageHandler类,您可以通过子类化该类来利用特定的钩子:

python 复制代码
from fastmcp import Client
from fastmcp.client.messages import MessageHandler
import mcp.types

class MyMessageHandler(MessageHandler):
    async def on_tool_list_changed(
        self, notification: mcp.types.ToolListChangedNotification
    ) -> None:
        """Handle tool list changes specifically."""
        print("Tool list changed - refreshing available tools")

client = Client(
    "my_mcp_server.py",
    message_handler=MyMessageHandler(),
)

Available Handler Methods

python 复制代码
Message Handler Methods
​
on_message(message) -> Any MCP message
Called for ALL messages (requests and notifications)
​
on_request(request) -> mcp.types.ClientRequest
Called for requests that expect responses
​
on_notification(notification) -> mcp.types.ServerNotification
Called for notifications (fire-and-forget)
​
on_tool_list_changed(notification) -> mcp.types.ToolListChangedNotification
Called when the server's tool list changes
​
on_resource_list_changed(notification) -> mcp.types.ResourceListChangedNotification
Called when the server's resource list changes
​
on_prompt_list_changed(notification) -> mcp.types.PromptListChangedNotification
Called when the server's prompt list changes
​
on_progress(notification) -> mcp.types.ProgressNotification
Called for progress updates during long-running operations
​
on_logging_message(notification) -> mcp.types.LoggingMessageNotification
Called for log messages from the server

示例: 处理工具变更消息

python 复制代码
from fastmcp.client.messages import MessageHandler
import mcp.types

class ToolCacheHandler(MessageHandler):
    def __init__(self):
        self.cached_tools = []
    
    async def on_tool_list_changed(
        self, notification: mcp.types.ToolListChangedNotification
    ) -> None:
        """Clear tool cache when tools change."""
        print("Tools changed - clearing cache")
        self.cached_tools = []  # Force refresh on next access

client = Client("server.py", message_handler=ToolCacheHandler())

处理请求

虽然消息处理器会接收服务器发起的请求,但对于大多数用例,你应该改用专用的回调参数:

bash 复制代码
Sampling requests: 使用 sampling_handler
Progress requests: 使用 progress_handler
Log requests: 使用 log_handler

消息处理器主要用于监控和处理通知,而非响应请求。

相关推荐
jiang_changsheng1 分钟前
RTX 2080 Ti魔改22GB显卡的最优解ComfyUI教程
python·comfyui
JoySSLLian7 分钟前
手把手教你安装免费SSL证书(附宝塔/Nginx/Apache配置教程)
网络·人工智能·网络协议·tcp/ip·nginx·apache·ssl
BestSongC8 分钟前
行人摔倒检测系统 - 前端文档(1)
前端·人工智能·目标检测
模型时代15 分钟前
Anthropic明确拒绝在Claude中加入广告功能
人工智能·microsoft
夕小瑶18 分钟前
OpenClaw、Moltbook爆火,算力如何48小时内扩到1900张卡
人工智能
一枕眠秋雨>o<20 分钟前
透视算力:cann-tools如何让AI性能调优从玄学走向科学
人工智能
那个村的李富贵34 分钟前
昇腾CANN跨行业实战:五大新领域AI落地案例深度解析
人工智能·aigc·cann
集简云-软件连接神器37 分钟前
技术实战:集简云语聚AI实现小红书私信接入AI大模型全流程解析
人工智能·小红书·ai客服
松☆37 分钟前
深入理解CANN:面向AI加速的异构计算架构
人工智能·架构
rainbow72424438 分钟前
无基础学AI的入门核心,从基础工具和理论开始学
人工智能