MCP 客户端处理服务端通知的机制

MCP 服务端通过通知告知客户端工具列表或资源等状态变化。客户端可用统一消息处理函数过滤通知,也可继承 MessageHandler 按类型挂钩;在 2026-07-28 协议下需通过 listen() 打开流接收列表变更与资源更新。

当您需要响应服务器侧的修改, 如工具列表更新或资源修改时, 使用此功能 。 MCP服务器可以发送通知通知告知客户端状态变化. 消息处理器提供了处理这些通知的统一方式. ## 处理通知 最简单的方法是接收您所关心的通知的所有信件和过滤器的函数: ```python from pathlib import Path from fastmcp import Client async def message_handler(message): """Handle MCP notifications from the server.""" if hasattr(message, 'method'): method = message.method if method == "notifications/tools/list_changed": print("Tools have changed - refresh tool cache") elif method == "notifications/resources/list_changed": print("Resources have changed") elif method == "notifications/prompts/list_changed": print("Prompts have changed") elif method == "notifications/resources/updated": print("A resource was updated") client = Client( Path("my_mcp_server.py"), message_handler=message_handler, ) ``` ## MessageHandler 类 对于精细的瞄准,子类 `MessageHandler` 使用特定钩子 : ```python from pathlib import Path 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.""" print("Tool list changed - refreshing available tools") async def on_resource_list_changed( self, notification: mcp_types.ResourceListChangedNotification ) -> None: """Handle resource list changes.""" print("Resource list changed") async def on_prompt_list_changed( self, notification: mcp_types.PromptListChangedNotification ) -> None: """Handle prompt list changes.""" print("Prompt list changed") client = Client( Path("my_mcp_server.py"), message_handler=MyMessageHandler(), ) ``` ### 处理器模板 ```python from fastmcp.client.messages import MessageHandler import mcp_types class MyMessageHandler(MessageHandler): async def on_message(self, message) -> None: """Called for every notification and transport exception.""" pass async def on_exception(self, exception: Exception) -> None: """Called for transport-level exceptions.""" pass async def on_notification( self, notification: mcp_types.ServerNotification ) -> None: """Called for notifications (fire-and-forget).""" pass async def on_tool_list_changed( self, notification: mcp_types.ToolListChangedNotification ) -> None: """Called when the server's tool list changes.""" pass async def on_resource_list_changed( self, notification: mcp_types.ResourceListChangedNotification ) -> None: """Called when the server's resource list changes.""" pass async def on_prompt_list_changed( self, notification: mcp_types.PromptListChangedNotification ) -> None: """Called when the server's prompt list changes.""" pass async def on_progress( self, notification: mcp_types.ProgressNotification ) -> None: """Called for progress updates during long-running operations.""" pass async def on_resource_updated( self, notification: mcp_types.ResourceUpdatedNotification ) -> None: """Called when a specific resource changes.""" pass async def on_cancelled( self, notification: mcp_types.CancelledNotification ) -> None: """Called when a request is cancelled.""" pass async def on_logging_message( self, notification: mcp_types.LoggingMessageNotification ) -> None: """Called for log messages from the server.""" pass ``` ## 列表更改通知 维持工具缓存, 当工具改变时刷新的实用实例 : ```python from pathlib import Path from fastmcp import Client 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(Path("server.py"), message_handler=ToolCacheHandler()) ``` ## 正在收听更改 打开 `2026-07-28` 协议,服务器对客户端没有常备通道,因此列表更改和资源更新通知只到达客户端打开的流中 `listen()`。通过您想要的改变类型;每个事件都意味着“这个改变,如果你在乎的话”: ```python from pathlib import Path from fastmcp import Client client = Client(Path("my_mcp_server.py")) async def watch_tools() -> None: async with client: async with client.listen(tools_list_changed=True) as subscription: async for event in subscription: tools = await client.list_tools() print(f"Tools changed: {[tool.name for tool in tools]}") ``` `listen()` 也接受 `prompts_list_changed`, `resources_list_changed`,以及 `resource_subscriptions` (资源 URI 列表) 。 当一个流打开时, 它的事件也到达了信件处理器。 使用 [响应缓存](<https://github.com/clients/client#response-caching>) 启用时, 匹配的缓存列表会在每次事件生成之前被清除, 因此立即调试返回新列表 。 离开 `listen()` 块 关闭流。当流从服务器端结束时,因为一个 FastMCP 服务器关闭或重新启动或连接中断, 重复上升 `SubscriptionLost` 而不是结束循环。循环只有在服务器以协议的优雅关闭流而结束,而FastMCP服务器不发送时才会无一例外地结束。事件不会重播,所以在之后 `SubscriptionLost`中,在打开新流前重新连接并进行调试。在握手时代的连接中,输入 `listen()` 提高额 `ListenNotSupportedError`,且通知没有流便到达信件处理器。 `mcp.client.subscriptions`: ```python from pathlib import Path from mcp.client.subscriptions import ListenNotSupportedError, SubscriptionLost from fastmcp import Client client = Client(Path("my_mcp_server.py")) async def watch_tools_until_lost() -> None: async with client: try: async with client.listen(tools_list_changed=True) as subscription: async for event in subscription: tools = await client.list_tools() print(f"Tools changed: {[tool.name for tool in tools]}") except ListenNotSupportedError: print("Handshake-era server: handle changes in the message handler") except SubscriptionLost: print("The server ended the stream; reconnect and refetch") ``` 一个 FastMCP 服务器默认服务听流。 设置 `FASTMCP_ENABLE_SUBSCRIPTIONS_LISTEN=false` 在 FastMCP 导入之前,或 `fastmcp.settings.enable_subscriptions_listen = False` 在服务器创建前, 将其关闭: 打开 `2026-07-28` 连接服务器广告 `listChanged` 财务报告和财务报告 `resources.subscribe` 作为 `false`, `listen()` 失败 `Method not found` 错误( E)`-32601`),并且服务器的 `notify_*` 手握时代的连接不会受到影响。 ## 服务器请求 信件处理器只接收通知和运输例外; 服务器启动的请求从未到达它。 通过客户端的专用参数回答这些请求 : - **抽样请求**编号: 使用 [`sampling_handler`](<https://github.com/clients/sampling>) - **4. 讲解请求**编号: 使用 [`elicitation_handler`](<https://github.com/clients/elicitation>) - **根请求**编号: 使用 [`roots`](<https://github.com/clients/roots>) 进展和日志通知也到达了信件处理器,但他们的专用回调更简单: - **最新进展**编号: 使用 [`progress_handler`](<https://github.com/clients/progress>) - **日志消息**编号: 使用 [`log_handler`](<https://github.com/clients/logging>)

查看原始来源