恒美微站
首页
关于我们
建站服务
主题模板
案例展示
资讯中心
联系我们
FastMCP 社区贡献模块(fastmcp.contrib)完全指南:MCPMixin、BulkToolCaller 与 Component Manager
首页
资讯中心
/
FastMCP 社区贡献模块(fastmcp.contrib)完全指南:MCPMixin、BulkToolCaller 与 Component Manager
FastMCP 社区贡献模块(fastmcp.contrib)完全指南:MCPMixin、BulkToolCaller 与 Component Manager
发布时间:2026/9/11 7:47:34
FastMCP 社区贡献模块fastmcp.contrib完全指南MCPMixin、BulkToolCaller 与 Component Manager【免费下载链接】fastmcp The fast, Pythonic way to build MCP servers and clients.项目地址: https://gitcode.com/GitHub_Trending/fa/fastmcp导读fastmcp.contrib是 FastMCP 中存放社区贡献模块的扩展包它由核心团队之外的个人开发者维护为 FastMCP 服务器提供三类即插即用的能力——以类方法批量注册工具/资源/提示的MCPMixin、在单次请求中并发执行多个工具调用的BulkToolCaller、以及通过 HTTP 接口在运行时启停组件的Component Manager。读完本文你将掌握这三个模块的导入方式、配置参数、底层实现原理与测试验证方法可以直接在自己的 FastMCP 服务器中落地使用。一、fastmcp.contrib 包是什么fastmcp.contrib目录仓库路径fastmcp_slim/fastmcp/contrib/README.md存放的是community-contributed modules社区贡献模块。与核心库不同这些模块扩展了 FastMCP 的功能但不由核心团队官方维护。使用前必须了解官方 README 明确声明的两条保证Guarantees稳定性级别不同contrib 中的模块在测试要求和稳定性保障上可能低于核心库可能被核心变更破坏对核心 FastMCP 库的修改可能在主变更日志没有明确警告的情况下破坏 contrib 模块。因此官方建议Use these modules at your own discretion自行斟酌使用同时欢迎社区贡献——但要求包含测试和文档。这一点在三个子模块中得到了体现每个子模块都自带独立的README.md与example.py且仓库 tests/contrib/ 下为它们提供了完整测试套件。1.1 导入方式按照官方 README 的用法说明contrib 模块统一从fastmcp.contrib包导入from fastmcp.contrib import my_module注意contrib 模块可能拥有与核心库不同的依赖。这些差异会记录在各自模块的 README 中或者通过单独的 requirements / 依赖文件声明。这一点在mcp_mixin上体现得最明显——它直接依赖mcp.types.ToolAnnotations与mcp_types而component_manager则依赖 Starlette 的路由与认证中间件。1.2 当前包含的模块总览模块核心能力源码位置mcp_mixin类方法装饰器批量注册 tools / resources / promptsfastmcp_slim/fastmcp/contrib/mcp_mixin/bulk_tool_caller单次请求批量调用多个工具fastmcp_slim/fastmcp/contrib/bulk_tool_caller/component_managerHTTP 接口运行时启停组件fastmcp_slim/fastmcp/contrib/component_manager/三个模块之间还有依赖关系BulkToolCaller直接继承自MCPMixin见 bulk_tool_caller.py 中的class BulkToolCaller(MCPMixin)说明mcp_mixin是整个 contrib 包的地基。二、MCPMixin把类方法变成 MCP 组件mcp_mixin模块提供MCPMixin基类以及配套装饰器mcp_tool、mcp_resource、mcp_prompt源码见 mcp_mixin.py。它的核心价值在于开发者只需定义一个普通的 Python 类用装饰器标记方法再调用一次注册方法即可把整个类注册到 FastMCP 服务器而无需逐个调用mcp.tool()/mcp.resource()/mcp.prompt()。2.1 支持的完整能力清单模块 READMEmcp_mixin/README.md明确列出其支持的核心特性Tools工具enable/disable启停、annotations注释/标注、excluded arguments排除参数、meta元数据Prompts提示enable/disable、metaResources资源enable/disable、meta2.2 三个装饰器的签名与参数从源码可以确认三个装饰器的精确签名def mcp_tool(nameNone, *, enabledNone, **kwargs) # name 缺省时为方法名 def mcp_resource(uri, *, nameNone, enabledNone, **kwargs) # uri 必填 def mcp_prompt(nameNone, *, enabledNone, **kwargs)enabledFalse时该组件在注册阶段被直接跳过不会注册到服务器客户端无法调用**kwargs会原样透传给Tool.from_function/Resource.from_function/Prompt.from_function例如description、tags、annotations、auth、timeout、version、mime_type等。一个值得注意的底层实现细节mcp_mixin.py在导入时通过inspect.signature()动态读取三个from_function的签名来构造合法关键字集合_TOOL_VALID_KWARGS等这意味着核心库给from_function新增参数时装饰器会自动跟随无需手动同步。同时装饰器会在装饰阶段而非注册阶段对未知参数立即抛出TypeError——test_mcp_mixin.py 中的TestMCPMixinValidation测试类专门验证了这一点test_error_raised_at_decoration_not_registration。2.3 完整示例以下代码来自模块 README 并做了修正整理覆盖了全部特性from mcp.types import ToolAnnotations from fastmcp import FastMCP from fastmcp.contrib.mcp_mixin import MCPMixin, mcp_tool, mcp_resource, mcp_prompt class MyComponent(MCPMixin): mcp_tool(namemy_tool, descriptionDoes something cool.) def tool_method(self): return Tool executed! # 禁用工具客户端永远调不到 mcp_tool(namedisabled_tool, descriptionHidden tool., enabledFalse) def disabled_tool_method(self): return Youll never get here! # 排除参数客户端无法传入 delete_everything mcp_tool( namesafe_tool, descriptionA safe tool., exclude_args[delete_everything], ) def excluded_param_tool_method(self, delete_everythingFalse): if delete_everything: return Nothing to delete. return Tool executed! # 带 annotations给 LLM 额外的使用提示 mcp_tool( nameannotated_tool, annotationsToolAnnotations( titleAttn LLM, use this tool first!, readOnlyHintFalse, destructiveHintFalse, idempotentHintFalse, ), ) def annotated_tool_method(self): return Tool executed! # 带 meta附加任意键值对 mcp_tool( namedata_tool, descriptionFetches user data from database, meta{version: 2.0, category: database, author: dev-team}, ) def data_tool_method(self, user_id: int): return fFetching data for user {user_id} mcp_resource(uricomponent://data) def resource_method(self): return {data: some data} mcp_resource( uricomponent://config, titleConfig Resource, meta{internal: True, cache_ttl: 3600, priority: high}, ) def config_resource_method(self): return {config: data} mcp_prompt( nameanalysis_prompt, titleData Analysis Prompt, descriptionAnalyzes data patterns, meta{complexity: high, domain: analytics}, ) def analysis_prompt_method(self, dataset: str): return fAnalyze the patterns in {dataset} mcp_server FastMCP() component MyComponent() # 带前缀注册避免多个同类型实例注册时发生命名冲突 component.register_all(mcp_server, prefixmy_comp) # 不带前缀注册使用装饰器中指定的原名/原 URI # component.register_all(mcp_server)注册完成后若使用前缀my_comp服务器上会出现my_comp_my_tool这样的工具名与my_compcomponent://data这样的资源 URI。2.4 注册方法与分隔符机制MCPMixin提供四个注册方法源码中均有完整 docstringregister_tools(mcp_server, prefixNone, separator_)register_resources(mcp_server, prefixNone, separator)register_prompts(mcp_server, prefixNone, separator_)register_all(mcp_server, prefixNone, tool_separator_, resource_separator, prompt_separator_)三种类型使用不同的默认分隔符定义于 mcp_mixin.py 顶部常量工具_例如my_comp_my_tool资源例如my_compcomponent://data提示_例如my_comp_analysis_promptprefix参数可选。若省略则按装饰器中的原始名字/URI 注册若提供则拼接规则为f{prefix}{separator}{original}且资源的 name 与 URI 都会加上前缀。register_all允许为三种类型分别指定不同的分隔符。这些行为全部被 test_mcp_mixin.py 中的参数化测试覆盖test_tool_registration、test_resource_registration、test_prompt_registration、test_register_all_with_prefix_custom_separators等。底层注册流程见register_tools源码遍历类中带有_mcp_tool_registration标记的方法 → 拼接前缀 → 弹出 mixin 专用的_mixin_enabled标记判断是否跳过 → 调用Tool.from_function(fnmethod, **registration_info)→ 交给mcp_server.add_tool(tool)。资源与提示的流程完全对称。2.5 与核心库的联动验证test_mcp_mixin.py 中的TestMCPMixinNewParams测试类证明装饰器可以把authrequire_scopes(write)、timeout5.0、version2.0等核心库新参数一路透传到from_function实现组件级的鉴权、超时与版本控制。三、BulkToolCaller一次请求批量调用工具BulkToolCaller源码见 bulk_tool_caller.py继承自MCPMixin向 FastMCP 服务器提供两个批量工具用于在单次请求中执行多个工具调用从而减少大量独立工具调用带来的网络与调度开销。3.1 快速上手参考官方示例 example.pyfrom fastmcp import FastMCP from fastmcp.contrib.bulk_tool_caller import BulkToolCaller mcp FastMCP() mcp.tool def echo_tool(text: str) - str: Echo the input text return text bulk_tool_caller BulkToolCaller() # 注册批量调用工具内部会通过 FastMCPTransport 建立与服务器的内存连接 bulk_tool_caller.register_tools(mcp)BulkToolCaller可以实例化后注册到任意 FastMCP 服务器既支持批量调用不同工具也支持同一工具带不同参数多次调用。3.2 工具一call_tools_bulk多个不同工具参数tool_callslist[CallToolRequest]请求对象列表每个对象包含tool工具名str与arguments参数字典continue_on_errorbool可选某个调用出错后是否继续执行后续调用默认为True。返回list[CallToolRequestResult]每个结果包含isError、contentMCP 内容列表以及原始请求中的tool名称与arguments。CallToolRequest与CallToolRequestResult都是模块内定义的 Pydantic 模型后者继承mcp_types.CallToolResult并额外附加tool与arguments字段通过from_call_tool_result()工厂方法构建。3.3 工具二call_tool_bulk同一工具多次调用参数toolstr要调用的工具名tool_argumentslist[dict]参数字典列表每个字典对应一次运行continue_on_errorbool可选默认为True。返回与call_tools_bulk相同的list[CallToolRequestResult]。3.4 底层原理与自我保护从源码bulk_tool_caller.py可以看到关键实现register_tools()会先建立FastMCPTransport(mcp_server)内存传输再调用父类MCPMixin.register_tools()完成注册每次实际调用时通过async with Client(self.connection)打开一个临时客户端执行client.call_tool_mcp(nametool, argumentsarguments)自我保护机制类中定义了_BULK_TOOL_NAMES frozenset({call_tools_bulk, call_tool_bulk})_call_tool()一旦发现目标工具在这两个名字中会直接返回一个is_errorTrue的结果提示 BulkToolCaller cannot call itself防止批量工具递归调用自身导致死循环continue_on_errorFalse时遇到result.is_error即立即中断并返回已收集的结果。test_bulk_tool_caller.py 对以上行为做了完整验证包括单次成功、多次成功、出错即停test_call_tool_bulk_error_stops、出错继续test_call_tools_bulk_error_continues、无返回值工具、以及两个批量工具的自我调用拦截test_call_tools_bulk_blocks_self_invocation。四、Component ManagerHTTP 接口运行时启停组件Component Manager源码见 component_manager.py为 FastMCP 服务器提供一套统一的 HTTP API用于在运行时启用/禁用工具、资源和提示。适用于功能开关feature toggling、管理后台、自动化工作流等需要动态控制组件激活状态的场景。4.1 特性清单模块 READMEcomponent_manager/README.md列出的特性通过 HTTP 端点启用/禁用tools、resources、prompts同时支持本地组件与挂载mounted/server组件可自定义API 根路径可选Auth scopes认证作用域保护接口与 FastMCP 最小化配置即可集成。4.2 基础安装与配置该模块属于fastmcp.contrib包使用 FastMCP 时无需额外安装from fastmcp import FastMCP from fastmcp.contrib.component_manager import set_up_component_manager mcp FastMCP(nameComponent Manager, instructionsThis is a test server with component manager.) set_up_component_manager(servermcp)4.3 完整端点清单所有端点默认注册在/下传入了自定义路径时则挂载在该路径下。三种类型的启停路由实现于_build_routes()组件类型启用端点禁用端点ToolsPOST /tools/{tool_name}/enablePOST /tools/{tool_name}/disableResourcesPOST /resources/{uri:path}/enablePOST /resources/{uri:path}/disablePromptsPOST /prompts/{prompt_name}/enablePOST /prompts/{prompt_name}/disable资源模板 URI 同样受支持例如POST /resources/example://test/{id}/enable POST /resources/example://test/{id}/disable示例响应HTTP 200JSONHTTP/1.1 200 OK Content-Type: application/json { message: Disabled tool: example_tool }4.4 底层路由与分派逻辑set_up_component_manager(server, path/, required_scopesNone)的签名与行为见 component_manager.py路由通过server._additional_http_routes.extend(routes)挂载到 FastMCP 的 HTTP 应用上不带鉴权时路由直接把path前缀拼进每条 Route带鉴权时改用MountRequireAuthMiddleware(Starlette(routesroutes), required_scopes)包裹整组路由来自mcp.server.auth.middleware.bearer_authpath由 Mount 统一处理端点的endpoint由_make_endpoint()工厂生成从path_params读取nametools/prompts或uriresources支持?versionv1查询参数对应组件的版本管理资源模板识别当 resource 路径中含{时自动判定为 template 组件并调用server.enable()/disable()的components[template]分支否则走[resource]最终调用server.enable(names{name}, versionversion, componentscomponents)或对应的disable()并返回 JSON 消息。4.5 自定义根路径将管理 API 挂载到其他路径set_up_component_manager(servermcp, path/admin)挂载后端点变为POST /admin/tools/{tool_name}/enable等。test_component_manager.py 中的TestComponentManagerWithPath验证了/test前缀下的启停行为。4.6 使用 Auth Scopes 保护端点服务器启用认证时通过required_scopes声明管理接口所需的作用域mcp FastMCP(nameComponent Manager, instructions..., authauth) set_up_component_manager(servermcp, required_scopes[write, read])curl 调用示例带 Bearer Tokencurl -X POST \ -H Authorization: Bearer YOUR_TOKEN_HERE \ -H Content-Type: application/json \ http://localhost:8001/tools/example_tool/enable鉴权语义在测试中得到完整验证无 Token 返回401未认证Token 缺少所需 scope 返回403权限不足Token 正确则返回 200见 test_component_manager.py 的TestAuthComponentManagementRoutes与TestComponentManagerWithPathAuth。4.7 与挂载服务器组合分级权限控制可以给主服务器与挂载服务器分别配置不同的 scope实现细粒度的管理权限mcp FastMCP(nameComponent Manager, instructions..., authauth) set_up_component_manager(servermcp, required_scopes[mcp:write]) mounted FastMCP(nameComponent Manager, instructions..., authauth) set_up_component_manager(servermounted, required_scopes[mounted:write]) mcp.mount(servermounted, namespacemo)这样即可区分访问级别——访问主服务器可以同时控制本地与挂载组件挂载组件以mo_为前缀# 通过主服务器控制挂载组件 curl -X POST \ -H Authorization: Bearer YOUR_TOKEN_HERE \ -H Content-Type: application/json \ http://localhost:8001/tools/mo_example_tool/enable # 直接访问挂载服务器只能控制它自己的组件 curl -X POST \ -H Authorization: Bearer YOUR_TOKEN_HERE \ -H Content-Type: application/json \ http://localhost:8002/tools/example_tool/enable完整的可运行示例见 component_manager/example.py其中使用JWTVerifierRSAKeyPair生成带mcp:write/mounted:writescope 的测试 Token并演示了主服务器、挂载服务器与本地 resource / mounted tool 的组合写法。4.8 工作原理小结set_up_component_manager()为 tools、resources、prompts 注册 HTTP 路由每个端点内部调用server.enable()或server.disable()按组件名/URI 操作返回 JSON 成功消息。五、维护约定与贡献要求使用 contrib 模块前请牢记官方 README 的几点约定自行承担风险contrib 模块的测试要求与稳定性保证可能低于核心库跟随核心升级核心库的变更可能不经过主 changelog 直接破坏 contrib 模块升级 FastMCP 版本后应回归验证独立依赖contrib 模块可能有额外的第三方依赖如mcp_types、Starlette请以各模块 README 或依赖文件为准贡献需带测试与文档官方欢迎社区贡献但要求附上测试和文档——这也是本仓库中每个 contrib 模块都配有 tests/contrib/ 测试与example.py示例的原因。以component_manager为例其维护说明见 component_manager/README.md明确写道该模块不由 FastMCP 核心团队官方维护是独立的扩展使用中遇到问题或希望贡献时可在仓库提交 issue 或 pull request。模块遵循 FastMCP 主项目的开源许可证。六、总结fastmcp.contrib用三个精心设计、测试完备的模块展示了 FastMCP 扩展生态的典型形态MCPMixin把方法即组件的抽象做到极致配合前缀/分隔符机制天然支持多实例注册与命名空间隔离BulkToolCaller在 MCPMixin 之上叠加了内存传输与自我保护逻辑是降低多工具调用开销的实用工具Component Manager通过标准 HTTP 端点 可选 OAuth scope把组件启停变成可鉴权的远程管理能力。三者相互配合覆盖了声明组件 → 批量调用 → 运行时管理的完整生命周期。在使用时请始终记住 contrib 的社区维护属性在升级核心库后及时回归测试让这些锦上添花的模块安全地服务于你的 MCP 应用。【免费下载链接】fastmcp The fast, Pythonic way to build MCP servers and clients.项目地址: https://gitcode.com/GitHub_Trending/fa/fastmcp创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考