[FastMCP设计、原理与应用-15]挂载一个MCP服务器就像挂载一个目录一样容易

发布时间:2026/10/7 9:43:34
[FastMCP设计、原理与应用-15]挂载一个MCP服务器就像挂载一个目录一样容易
随着应用程序的增长我们可能需要将一个单一的MCP服务器拆分为多个功能专一的服务器例如一个用于天气一个用于日历一个用于管理后台并通过挂载Mount的方式将它们合并成可用通过一个客户端连接的单一服务器。挂载服务器后其所有工具、资源和提示都会通过父进程变为可用状态。连接是实时的挂载后向子进程添加工具该工具会立即在父进程中可见。1. 挂载一个FastMCP对象以如下这个演示程序为例我们创建的名为Server的FastMCP对象并通过调用mount方法挂载了两个FastMCP对象命名为Weather的服务器提供了返回天气信息的工具get_weather命名为OA的服务器提供的工具is_available用于确定某个人在指定的日志是否由任务安排。fromfastmcpimportFastMCPfromfastmcp.clientimportClientfromdatetimeimportdateimportasyncio weatherFastMCP(Weather)weather.tool()asyncdefget_weather(location:str)-str:Get the current weather for a given location.returnfThe current weather in{location}is sunny.oaFastMCP(OA)oa.tool()asyncdefis_available(name:str,date:date)-bool:Check if a person is available on a given date.returnTrueasyncdefmain():serverFastMCP(Server)server.mount(serverweather)server.mount(serveroa)asyncwithClient(server)asclient:toolsawaitclient.list_tools()tool_namesset([tool.namefortoolintools])asserttool_names{get_weather,is_available}serverFastMCP(Server)server.mount(serverweather,namespaceweather)server.mount(serveroa,namespaceoa)asyncwithClient(server)asclient:toolsawaitclient.list_tools()tool_namesset([tool.namefortoolintools])asserttool_names{weather_get_weather,oa_is_available}asyncio.run(main())上面的例子演示了针对mount方法的两次调用第一次仅仅指定被挂载的FastMCP对象所以工具名称保持不变。第二次指定了命名空间weather和os它会作为工具的名称前缀weather_get_weather和oa_is_available。classFastMCP(AggregateProvider,LifespanMixin,MCPOperationsMixin,TransportMixin,Generic[LifespanResultT],):defmount(self,server:FastMCP[LifespanResultT],namespace:str|NoneNone,as_proxy:bool|NoneNone,tool_names:dict[str,str]|NoneNone,prefix:str|NoneNone,)-None上面给出了mount方法的定义它的参数说明如下server被挂载的作为MCP服务器的FastMCP对象namespace命名空间。工具和提示词的名称将以{namespace}_为前缀资源将其作为前置路径as_proxy以代理的形式被挂载这个参数已经废弃因为我们倾向于自行创建代理tool_names: 提供一个字典来修改工具的名称prefix: 命名前缀已经废弃并使用namespace代替。2. 挂载一个代理由于mount方法只支持针对FastMCP对象的挂载。对于一个需要通过客户端远程调用MCP服务器我们可以采用代理的形式进行挂载。作为MCP服务器代理的FastMCPProxy对象之所以能够被挂载是因为它自身就是一个FastMCP对象。FastMCPProxy对象利用ProxyProvider提供组件后者又利用Client远程获取组件构造函数参数client_factory用于提供创建Client的工厂。出于性能的考虑远程获取的组件会在本地进行缓存缓存的过期时间默认为300秒。如果手工创建ProxyProvider可以利用构造函数的cache_ttl参数对缓存过期时间进行设置。classFastMCPProxy(FastMCP):def__init__(self,*,client_factory:ClientFactoryT,**kwargs,):super().__init__(**kwargs)self.client_factoryclient_factory provider:ProviderProxyProvider(client_factory)self.add_provider(provider)classProxyProvider(Provider):def__init__(self,client_factory:ClientFactoryT,cache_ttl:float|NoneNone,)ClientFactoryTCallable[[],Client]|Callable[[],Awaitable[Client]]FastMCPProxy可以通过如下这个全局函数fastmcp.server.create_proxy来创建。defcreate_proxy(target:(Client[ClientTransportT]|ClientTransport|FastMCP[Any]|FastMCP1Server|AnyUrl|Path|MCPConfig|dict[str,Any]|str),**settings:Any,)-FastMCPProxy如下的程序演示了以代理的形式挂载远程MCP服务器。fromfastmcpimportFastMCPfromfastmcp.clientimportClientfromfastmcp.serverimportcreate_proxyfromdatetimeimportdateimportasyncio serverFastMCP(Server)server.tool()asyncdefget_weather(location:str)-str:Get the current weather for a given location.returnfThe current weather in{location}is sunny.server.tool()asyncdefis_available(name:str,date:date)-bool:Check if a person is available on a given date.returnTrueasyncdefmain():asyncio.create_task(server.run_async(transportstreamable-http,host0.0.0.0,port3721))awaitasyncio.sleep(5)# Wait for the server to startmcpFastMCP()mcp.mount(create_proxy(http://localhost:3721/mcp))asyncwithClient(mcp)asclient:toolsawaitclient.list_tools()tool_namesset([tool.namefortoolintools])print(fTools:{tool_names})asserttool_names{get_weather,is_available}asyncio.run(main())