FastMCP Component Manager 实战:用 HTTP 接口在运行时动态启停工具、资源与提示词
2026/9/10 21:13:02 网站建设 项目流程

FastMCP Component Manager 实战:用 HTTP 接口在运行时动态启停工具、资源与提示词

【免费下载链接】fastmcp🚀 The fast, Pythonic way to build MCP servers and clients.项目地址: https://gitcode.com/GitHub_Trending/fa/fastmcp

Component Manager 是 FastMCP 生态中的一个 contrib 扩展模块,它把server.enable()/server.disable()的编程式能力封装为一组 REST 端点,让你可以通过 HTTP 请求在运行时动态启用或禁用工具(tools)、资源(resources)与提示词(prompts)。本文将以 fastmcp_slim/fastmcp/contrib/component_manager/README.md 为骨架,结合仓库内的源码实现与测试用例,完整讲解该模块的安装接入、端点语义、认证加固、挂载服务器隔离,以及其底层的工作机制。读完本文,你将能基于该模块为 FastMCP 服务器构建特性开关(feature toggle)、管理后台或自动化运维能力。

模块定位与核心能力

Component Manager 解决的问题很直接:一个运行中的 FastMCP 服务器,如何在不重启、不修改代码的前提下,按需开放或收回某个组件?它通过注册一组 HTTP 路由,把"启用/禁用"这一管理操作从 Python 代码内部暴露到外部调用者(管理后台、运维脚本、Agent 工作流),并给出统一的 JSON 响应。

官方 README 列出的核心特性如下:

  • 可通过 HTTP 端点启用/禁用工具、资源、提示词三类组件;
  • 同时支持本地组件挂载服务器(mounted server)组件
  • 支持自定义API 根路径
  • 可选Auth scopes做访问控制;
  • 与 FastMCP 集成成本极低,最小只需一行set_up_component_manager(server=mcp)

需要说明的是,该模块属于fastmcp.contrib社区扩展包,README 中明确标注其并非 FastMCP 核心团队官方维护,而是由 gorocode 独立开发的扩展;许可证沿用 FastMCP 主项目。

安装与最小接入

模块位于fastmcp.contrib包内,无需单独安装——只要你的环境已经安装了 FastMCP(本仓库对应实现位于 fastmcp_slim/fastmcp),即可直接导入使用:

from fastmcp import FastMCP from fastmcp.contrib.component_manager import set_up_component_manager mcp = FastMCP( name="Component Manager", instructions="This is a test server with component manager.", ) set_up_component_manager(server=mcp)

包入口在 component_manager/init.py,公开的唯一 API 是set_up_component_manager。执行上述代码后,服务器会注册 6 条管理路由,默认挂在根路径/下。

API 端点一览

模块为三类组件各注册一对 enable/disable 端点,全部限定为POST方法(见 component_manager.py 中的路由构建逻辑):

组件类型启用端点禁用端点
工具POST /tools/{tool_name}/enablePOST /tools/{tool_name}/disable
资源POST /resources/{uri:path}/enablePOST /resources/{uri:path}/disable
提示词POST /prompts/{prompt_name}/enablePOST /prompts/{prompt_name}/disable

几个实现细节值得注意:

  • 资源端点使用{uri:path}路径参数,因此 URI 中的/可以被完整透传,例如POST /resources/data://test_resource/enable
  • 资源模板同样受支持,例如POST /resources/example://test/{id}/enable。端点内部会检测路径参数中是否包含{:若包含,则按template组件类型处理,否则按resource处理(对应 component_manager.py 的类型分派逻辑);
  • 支持可选的版本过滤参数?version=:端点会把request.query_params.get("version")原样透传给server.enable()/disable(),可用于针对特定版本的组件做启停(如POST /tools/my_tool/disable?version=v1),这正是 FastMCP 版本化组件能力在 HTTP 层的延伸。

成功的请求返回如下结构的 JSON:

HTTP/1.1 200 OK Content-Type: application/json { "message": "Disabled tool: example_tool" }

消息格式为"{action}d {component_type}: {name}",其中actionEnableDisablecomponent_typetool/resource/promptname为路径中解析出的组件名或资源 URI(见 component_manager.py)。

配置选项详解

set_up_component_manager共接受三个参数(见 component_manager.py):

参数类型默认值说明
serverFastMCP必填目标 FastMCP 服务器实例
pathstr"/"管理 API 的挂载根路径
required_scopeslist[str] \| NoneNone可选;仅在启用认证时生效,要求请求携带的 token 具备指定 scope

自定义根路径

当不希望管理端点与 MCP 主端点混在同一路径空间时,可以挂载到任意自定义前缀下:

set_up_component_manager(server=mcp, path="/admin")

挂载后端点变为POST /admin/tools/{name}/enablePOST /admin/resources/{uri:path}/disablePOST /admin/prompts/{name}/enable等。从源码看,无认证时路径前缀直接拼进各Route;而启用认证时则改用 Starlette 的Mount承载前缀(path != "/"时才挂载),以便认证中间件统一拦截。

用 Auth Scopes 加固管理端点

启用了认证的服务器上,可以要求调用者携带具备指定 scope 的 token:

mcp = FastMCP( name="Component Manager", instructions="This is a test server with component manager.", auth=auth, ) set_up_component_manager(server=mcp, required_scopes=["write", "read"])

结合仓库中的完整示例 example.py,可以看出一套可运行的 JWT 认证配置:

from fastmcp import FastMCP from fastmcp.contrib.component_manager import set_up_component_manager from fastmcp.server.auth.providers.jwt import JWTVerifier, RSAKeyPair key_pair = RSAKeyPair.generate() auth = JWTVerifier( public_key=key_pair.public_key, issuer="https://dev.example.com", audience="my-dev-server", required_scopes=["mcp:read"], ) # 主服务器:组件管理需要 mcp:write 权限 mcp_token = key_pair.create_token( subject="dev-user", issuer="https://dev.example.com", audience="my-dev-server", scopes=["mcp:write", "mcp:read"], ) mcp = FastMCP( name="Component Manager", instructions="This is a test server with component manager.", auth=auth, ) set_up_component_manager(server=mcp, required_scopes=["mcp:write"])

调用时需在请求头携带 Bearer token。测试用例 tests/contrib/test_component_manager.py 严格验证了三种鉴权结果:无 token 返回401、token 缺 scope 返回403、token 具备所需 scope 返回200并真正改变组件状态。

用 Curl 实际操作一个工具

启用认证后的典型调用如下:

curl -X POST \ -H "Authorization: Bearer YOUR_TOKEN_HERE" \ -H "Content-Type: application/json" \ http://localhost:8001/tools/example_tool/enable

对应地,禁用即为POST /tools/example_tool/disable8001是示例中 FastMCP 服务器的 HTTP 端口,YOUR_TOKEN_HERE需替换为具备required_scopes中全部 scope 的访问令牌。

挂载服务器场景:细粒度的权限隔离

FastMCP 支持通过mcp.mount(server=child, namespace="mo")组合多个服务器。Component Manager 可以分别在主服务器和挂载服务器上各自启用、各自配置不同 scope,从而实现"主入口管全局、子入口只管自己"的权限分层:

mcp = FastMCP(name="Component Manager", instructions="...", auth=auth) set_up_component_manager(server=mcp, required_scopes=["mcp:write"]) mounted = FastMCP(name="Component Manager", instructions="...", auth=auth) set_up_component_manager(server=mounted, required_scopes=["mounted:write"]) mcp.mount(server=mounted, namespace="mo")

效果如下:

  • 访问主服务器(如http://localhost:8001)时,可以同时控制本地组件与带命名空间的挂载组件,例如POST /tools/mo_example_tool/enable控制的是挂载子服务器中命名空间为moexample_tool
  • 直接访问挂载服务器自身(如http://localhost:8002)时,只能控制其自有组件,例如POST /tools/example_tool/enable,且必须持有mounted:write相关 scope。

这样便可以为"平台管理员"和"子服务负责人"分配互不越权的管理面。底层原因是 FastMCP 在收集附加路由时会递归合并挂载服务器的路由_get_additional_http_routes()会遍历所有 provider,若发现内层是FastMCPProvider,就继续递归收集其子服务器的路由(见 transport.py)。因此主服务器的 HTTP app 天然能看到全部挂载组件的管理端点,而每个挂载服务器自身也独立持有自己的端点。

工作原理:从 HTTP 请求到组件状态变更

整个调用链分四层,均可在仓库源码中逐一对证:

  1. 路由注册set_up_component_manager()把构建好的Route列表追加到server._additional_http_routes(无认证时直接扩展该列表;有认证时追加一个由RequireAuthMiddleware包裹的Mount)。该列表在 server.py 中初始化,本质是用户自定义 HTTP 路由的挂载点。

  2. 路由合并进 ASGI app:在构建 SSE 应用与 Streamable HTTP 应用时,server_routes.extend(server._get_additional_http_routes())会把管理路由追加到全部内置路由之后(见 http.py 与 http.py),即最低优先级的自定义路由。

  3. 端点处理_make_endpoint()为每个路由生成异步端点函数。它先从request.path_params中取出nameuri,再读取可选的version查询参数,随后按组件类型分派——资源带{template处理、否则按resource,工具与提示词各归其类(见 component_manager.py)。

  4. 状态变更:端点最终调用getattr(server, action)(names={name}, version=version, components=components),即server.enable()server.disable()。这两个方法定义在 providers/base.py,本质是向服务器的变换链追加一个Visibility变换:enable标记匹配组件可见,disable标记隐藏;由于后加入的变换优先生效,同一组件可以先 disable 再 enable 恢复。enable还额外支持only=True的 allowlist 模式(先全局禁用再精确放行)。

测试验证与可复现的检查清单

仓库为模块提供了完整的测试覆盖:tests/contrib/test_component_manager.py,涵盖四个测试类,可作为验证模块行为最直接的依据:

  • TestComponentManagementRoutes:无认证下,对工具、普通资源、资源模板、提示词分别执行 enable/disable,断言 HTTP 200、JSON 响应体,并通过list_tools()/list_resources()/list_resource_templates()/list_prompts()验证组件状态真实改变;
  • TestAuthComponentManagementRoutes:认证场景下验证 401(无 token)、403(scope 不足)、200(scope 足够)三种结果;
  • TestComponentManagerWithPath/TestComponentManagerWithPathAuth:验证自定义路径/test下(含认证场景)路由前缀与鉴权行为正确。

如果你要基于该模块落地功能特性开关或管理后台,可参照上述用例建立同样的回归检查:先禁用组件并断言其从列表中消失,再通过 HTTP 端点启用并断言其恢复可见;对资源模板使用data://xxx/{id}形式的 URI 验证模板分支;对启用认证的服务器务必补充 401/403 用例。

小结

Component Manager 以极低的接入成本,为 FastMCP 服务器提供了一套完整的 HTTP 化组件治理能力。它不引入新的状态机制,而是复用 FastMCP 自身的enable/disable+Visibility变换体系,并借助_additional_http_routes与挂载路由递归合并机制自然延伸到多服务器组合场景,因此行为与核心 API 高度一致、可预测。将其与认证 scope 组合,即可构建出权限分层的管理界面或自动化运维入口。

【免费下载链接】fastmcp🚀 The fast, Pythonic way to build MCP servers and clients.项目地址: https://gitcode.com/GitHub_Trending/fa/fastmcp

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询