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

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

相关推荐
西门老铁16 小时前
🦞OpenClaw 让 MacMini 脱销了,而我拿出了6年陈的安卓机
人工智能
恋猫de小郭17 小时前
AI 可以让 WIFI 实现监控室内人体位置和姿态,无需摄像头?
前端·人工智能·ai编程
是一碗螺丝粉17 小时前
5分钟上手LangChain.js:用DeepSeek给你的App加上AI能力
前端·人工智能·langchain
两万五千个小时17 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
用户48159301959117 小时前
揭秘GPT-4与LLaMA背后的加速黑科技:KV Cache、MQA、GQA、稀疏注意力与MoE全解析
人工智能
用户51914958484517 小时前
Cisco SMA 暴露面检测工具 - 快速识别CVE-2025-20393风险
人工智能·aigc
碳基沙盒17 小时前
AI工具的“超级外挂”:从零手把手教你搭建私人 MCP 服务器
人工智能
马腾化云东17 小时前
Agent开发应知应会(langfuse):Langfuse Score概念详解和实战应用
人工智能·llm·ai编程
Baihai_IDP17 小时前
HackerNews 热榜第一名:AGI 的 A,原来代表的是 Ads(广告)
人工智能·程序员·llm
ma_king17 小时前
claude+tmux 团队模式使用
人工智能·claude