FastMCP 服务器组合机制

FastMCP 的 mount() 可将多个专注服务器组合为单一父服务器,子服务器的工具、资源和提示词经实时链接对客户端可见,并支持命名空间、标签过滤与版本冲突解析。

随着应用程序的增长,你会想将其分成焦点服务器——一个用于天气,一个用于日历,一个用于管理员,把它们合并成一个客户端连接的单一服务器. `mount()` 不错 当您挂载一个服务器时, 它的所有工具、 资源和提示都会通过父程序可用 。 连接是活的 : 在挂载后给孩子添加一个工具, 然后通过父程序立即可见 。 ```python from fastmcp import FastMCP weather = FastMCP("Weather") @weather.tool def get_forecast(city: str) -> str: """Get weather forecast for a city.""" return f"Sunny in {city}" @weather.resource("data://cities") def list_cities() -> list[str]: """List supported cities.""" return ["London", "Paris", "Tokyo"] main = FastMCP("MainApp") main.mount(weather) # main now serves get_forecast and data://cities ``` ## 正在挂载外部服务器 使用远程 HTTP 服务器或基于子进程的 MCP 服务器挂载 `create_proxy()`: ```python from pathlib import Path from fastmcp import FastMCP from fastmcp.server import create_proxy mcp = FastMCP("Orchestrator") # Mount a remote HTTP server (URLs work directly) mcp.mount(create_proxy("http://api.example.com/mcp"), namespace="api") # Mount local Python scripts (file paths work directly) mcp.mount(create_proxy(Path("./my_server.py")), namespace="local") ``` ### 正在挂载 npm/ uvx 软件包 对于 npm 包或 Python 工具,请使用配置 dict 格式 : ```python from fastmcp import FastMCP from fastmcp.server import create_proxy mcp = FastMCP("Orchestrator") # Mount npm package via config github_config = { "mcpServers": { "default": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"] } } } mcp.mount(create_proxy(github_config), namespace="github") # Mount Python tool via config sqlite_config = { "mcpServers": { "default": { "command": "uvx", "args": ["mcp-server-sqlite", "--db", "data.db"] } } } mcp.mount(create_proxy(sqlite_config), namespace="db") ``` 或使用明确的运输类别: ```python from fastmcp import FastMCP from fastmcp.server import create_proxy from fastmcp.client.transports import NpxStdioTransport, UvxStdioTransport mcp = FastMCP("Orchestrator") mcp.mount( create_proxy(NpxStdioTransport(package="@modelcontextprotocol/server-github")), namespace="github" ) mcp.mount( create_proxy(UvxStdioTransport(tool_name="mcp-server-sqlite", tool_args=["--db", "data.db"])), namespace="db" ) ``` 关于高级配置,见 [代理服务器](<https://github.com/servers/providers/proxy>). ## 名称间隔 在安装多个服务器时, 使用命名空间来避免命名冲突 : ```python from fastmcp import FastMCP weather = FastMCP("Weather") calendar = FastMCP("Calendar") @weather.tool def get_data() -> str: return "Weather data" @calendar.tool def get_data() -> str: return "Calendar data" main = FastMCP("Main") main.mount(weather, namespace="weather") main.mount(calendar, namespace="calendar") # Tools are now: # - weather_get_data # - calendar_get_data ``` ### 命名间隔如何工作 | 组件类型 | 无命名空间 | 与 `namespace="api"` | |----------------|-------------------|------------------------| | 工具 | `my_tool` | `api_my_tool` | | 提示 | `my_prompt` | `api_my_prompt` | | 资源 | `data://info` | `data://api/info` | | 模板 | `data://{id}` | `data://api/{id}` | 命名间隔用途 [变换](<https://github.com/servers/transforms/transforms>) 在引擎盖下。 没有资源和模板的 URI `://`,例如, `urn:example:config`,但保持不变,可以使用其列出的标识符进行读取。命名空间不会将这些URI与碰撞隔离;等效标识符使用普通的 [提供者解析命令](#conflict-resolution). ## 动态组成 因为 `mount()` 创建一个活链接,您可以在安装后将组件添加到一个子服务器中,并且它们会立即通过母服务器提供: ```python from fastmcp import FastMCP dynamic_server = FastMCP("Dynamic") main = FastMCP("Main") main.mount(dynamic_server, namespace="dynamic") # Add a tool AFTER mounting - it's accessible through main @dynamic_server.tool def added_later() -> str: return "Added after mounting!" ``` ## 协议扩展 当您挂载本地的 FastMCP 服务器时, 它 [由供应商捆绑的扩展](<https://github.com/servers/extensions#provider-extensions>) 跟踪组件到父目录 。 选择自动注册的扩展赋予父目录, 并请求客户端所需的方法 。 配置一个明确显示父目录的扩展, 用于选择所有挂载提供者的设置 。 组成在父程序启动前需要新扩展的提供者。 一旦扩展寿命开始, 额外的提供者可以使用已注册在根上的扩展 。 [启动规则](<https://github.com/servers/extensions#startup>) 也可通过嵌套山体和聚合物加以应用。 ## 标签过滤 父服务器标签过滤器向挂载服务器递归应用 : ```python from fastmcp import FastMCP api_server = FastMCP("API") @api_server.tool(tags={"production"}) def prod_endpoint() -> str: return "Production data" @api_server.tool(tags={"development"}) def dev_endpoint() -> str: return "Debug data" # Mount with production filter prod_app = FastMCP("Production") prod_app.mount(api_server, namespace="api") prod_app.enable(tags={"production"}, only=True) # Only prod_endpoint (namespaced as api_prod_endpoint) is visible ``` ## 业绩考量 业务类 `list_tools()` 在母服务器上,它受到所有挂载服务器性能的影响。这一点尤其明显: - 基于HTTP的挂载服务器(用于本地工具的300 -400ms vs 1 -2ms) - 初始化缓慢的挂载服务器 - 深层的等级 如果低潜伏度至关重要,则考虑实施缓存战略或限制上升的深度。 ## 自定义路由 自定义 HTTP 路由 `@server.custom_route()` 挂载时也转发 : ```python from fastmcp import FastMCP from starlette.requests import Request from starlette.responses import JSONResponse, Response subserver = FastMCP("Sub") @subserver.custom_route("/health", methods=["GET"]) async def health_check(request: Request) -> Response: return JSONResponse({"status": "ok"}) main = FastMCP("Main") main.mount(subserver, namespace="sub") # /health is now accessible through main's HTTP app. # Custom route paths are not namespaced by mount(namespace=...). ``` ## 解决冲突 当安装具有相同命名空间(或无命名空间)的多个服务器时, FastMCP 询问所有挂载的供应商请求的组件, 并返回最高匹配版本。 如果两个未转换组件( 或两个等号版本) 使用相同的标识符, 供应商先注册获胜 。 ```python from fastmcp import FastMCP server_a = FastMCP("A") server_b = FastMCP("B") @server_a.tool def shared_tool() -> str: return "From A" @server_b.tool def shared_tool() -> str: return "From B" main = FastMCP("Main") main.mount(server_a) main.mount(server_b) # shared_tool returns "From A" (first mounted, same unversioned key) ``` 一个服务器拒绝在同名下持有一个版本和未转换的组件, 但两个没有命名空间的服务器可以. FastMCP 在列表中首次看到该组合时登录一个警告。 在此状态中, 列表中只显示版本组件, 而请求一个版本则缺少运行未转换的组件。 给挂载服务器一个命名空间, 或两个版本的组件, 以避免它 。

查看原始来源