Puppeteer 中监听 WebMCP 工具移除事件:WebMCPToolsRemovedEvent 接口深度解析
Puppeteer 中监听 WebMCP 工具移除事件:WebMCPToolsRemovedEvent 接口深度解析
本篇指南聚焦 Puppeteer 实验性 WebMCP(Web Model Context Protocol)能力中的 WebMCPToolsRemovedEvent 接口,讲解其在工具生命周期管理中的定位、数据结构、底层实现原理与真实触发场景。读完你将掌握如何通过监听 toolsremoved 事件同步页面模型上下文中工具的增删变化,并能在自动化任务中正确推断与处理工具失效与动态更新。
WebMCPToolsRemovedEvent 是什么
WebMCPToolsRemovedEvent 是 Puppeteer 为 WebMCP API 提供的事件负载类型,定义在 docs/api/puppeteer.webmcptoolsremovedevent.md 中。它描述"页面上注册的 WebMCP 工具被移除"这一事件所携带的数据,是 WebMCP 类事件体系中与"工具新增"对称的"工具移除"一侧。
其接口签名为:
export interface WebMCPToolsRemovedEvent
它只包含一个属性字段:
| 属性 | 类型 | 说明 | 默认值 |
|---|---|---|---|
tools |
WebMCPTool[] | 被移除的工具数组 | — |
当页面上下文中的工具因为显式注销、DOM 变更或文档销毁等原因从可用集合中消失时,事件处理器收到的正是这样一个 WebMCPToolsRemovedEvent 对象,其中 tools 字段给出了本次被移除的全部 WebMCPTool 实例(而非仅名称或 ID),因此你可以在事件回调中继续读取被移除工具的 name、description、inputSchema 等元数据,用于清理本地状态或做进一步处理。
与 toolsadded 事件的对称关系
WebMCPToolsRemovedEvent 与兄弟接口 WebMCPToolsAddedEvent 结构完全一致,均只含一个 tools 字段,唯一的语义差异是"added"表示新增、"removed"表示移除。两者分别对应 WebMCP 类事件映射中的 toolsadded 与 toolsremoved 两个事件名。
事件在 WebMCP 类中的注册位置
WebMCPToolsRemovedEvent 并非孤立类型,它是 WebMCP 类(实验性 API)作为事件发射器所支持的四类事件负载之一。从源码 packages/puppeteer-core/src/cdp/WebMCP.ts 可见其类签名:
export class WebMCP extends EventEmitter<{
/** Emitted when tools are added. */
toolsadded: WebMCPToolsAddedEvent;
/** Emitted when tools are removed. */
toolsremoved: WebMCPToolsRemovedEvent;
/** Emitted when a tool invocation starts. */
toolinvoked: WebMCPToolCall;
/** Emitted when a tool invocation completes or fails. */
toolresponded: WebMCPToolCallResult;
}>
其中 toolsremoved 事件的负载类型正是本接口。WebMCP 继承自通用的 EventEmitter,这意味着你可以使用标准的事件 API(on/once/off/emit)订阅该事件。
同一文件中还给出了接口的原始定义与字段注释(packages/puppeteer-core/src/cdp/WebMCP.ts#L154-L162):
/**
* @public
*/
export interface WebMCPToolsRemovedEvent {
/**
* Array of tools that were removed.
*/
tools: WebMCPTool[];
}
需要注意接口上的 tools 字段中的对象是 Puppeteer 侧的 WebMCPTool 实例。从源码可以看出,一个 WebMCPTool 实例不仅承载工具元数据,还持有其来源 frame、定义位置 location、对应的表单元素 formElement 等信息,事件消费者可据此精确判断工具归属的页面帧。
底层实现:事件是如何被派发的
WebMCPToolsRemovedEvent 的产生机制可以从 WebMCP 内部实现中追溯。该类在构造时通过 #bindListeners() 向 CDP(Chrome DevTools Protocol)会话订阅了 WebMCP.toolsRemoved 协议事件(packages/puppeteer-core/src/cdp/WebMCP.ts#L413-L421),随后在内部处理器 #onToolsRemoved 中把 CDP 层的移除通知转换为 Puppeteer 侧事件(packages/puppeteer-core/src/cdp/WebMCP.ts#L294-L304):
#onToolsRemoved = (event: Protocol.WebMCP.ToolsRemovedEvent) => {
const tools: WebMCPTool[] = [];
event.tools.forEach(tool => {
const removedTool = this.#tools.get(tool.frameId)?.get(tool.name);
if (removedTool) {
tools.push(removedTool);
}
this.#tools.get(tool.frameId)?.delete(tool.name);
});
this.emit('toolsremoved', {tools});
};
可以看到该处理器有三个关键动作:
- 映射查表:以 CDP 事件中的
frameId + tool.name为键,在内部#tools缓存(Map<frameId, Map<name, WebMCPTool>>)中查找对应的 Puppeteer 侧WebMCPTool实例; - 更新缓存:将命中工具从内部注册表中删除,保证随后调用 WebMCP.tools() 返回的是最新快照;
- 派发事件:将收集到的工具数组封装成
{tools}对象,即标准的 WebMCPToolsRemovedEvent 结构,通过this.emit('toolsremoved', {tools})广播给所有订阅者。
也就是说,即使某个移除行为没有被 CDP 以 toolsRemoved 事件通知(例如整帧销毁),Puppeteer 仍会在 #onContextDisposed 清理逻辑中主动收集该帧残留的所有工具并补发 toolsremoved 事件(packages/puppeteer-core/src/cdp/WebMCP.ts#L338-L349),从源码结构上保证了"工具从页面消失"这一状态总能被同步到 Puppeteer 侧。此外同文档导航(如 hash 变更)不会销毁上下文,因而不会触发移除事件——测试用例对这一点有显式覆盖。
触发时机:什么情况下会收到该事件
结合仓库内的集成测试 test/src/cdp/webmcp.test.ts,WebMCPToolsRemovedEvent 主要出现在以下三类真实场景:
- 通过 AbortController 注销命令式工具:页面内使用
document.modelContext.registerTool(tool, {signal})注册工具后,对 signal 调用abort()会触发该工具被注销,对应测试should fire toolsremoved events(test/src/cdp/webmcp.test.ts#L177-L269)用controller.abort()触发了一次toolsremoved,并断言removedTools[0].name === 'test-tool-1'且其元数据完整可读; - 移除声明式工具对应的表单:通过
<form toolname="...">声明式注册的工具,当对应 DOM 元素被document.querySelector('form').remove()移除时也会产生移除事件,同一个测试用例对此进行了验证; - 跨文档导航 / 帧上下文销毁:
page.goto()到新页面、刷新或目标帧上下文被销毁时,旧文档中注册的所有工具会被整体清理。测试should remove tools on frame navigation(test/src/cdp/webmcp.test.ts#L271-L304)与should handle multiple navigations and report tools correctly(test/src/cdp/webmcp.test.ts#L306-L361)验证了"导航后收到 toolsremoved、tools() 归零、新文档重新触发 toolsadded"的完整生命周期。
这些测试同时印证了事件负载的语义:一次事件可能携带多个被移除工具(例如整帧销毁时一次广播全部残留工具)。
实战示例:跟踪页面工具集的变化
把 toolsremoved 与 toolsadded 配对使用,可以维护一份始终与页面模型上下文一致的"当前可用工具"清单,这在使用 WebMCP.tools() 对工具执行 execute() 之前做状态校验时尤为有用。示例:
// 启动时启用 WebMCP(需要 Chrome 151+ 并开启 --enable-features=WebMCP)
// const browser = await puppeteer.launch({
// args: ['--enable-features=WebMCP'],
// });
await page.goto('https://www.example.com');
const toolRegistry = new Map<string, string>(); // name -> description 快照
page.webmcp.on('toolsadded', event => {
for (const tool of event.tools) {
toolRegistry.set(tool.name, tool.description);
console.log(`Tool added: ${tool.name}`);
}
});
page.webmcp.on('toolsremoved', (event: WebMCPToolsRemovedEvent) => {
for (const tool of event.tools) {
toolRegistry.delete(tool.name);
console.log(`Tool removed: ${tool.name}`);
}
});
// 初始同步:一次性获取当前已注册的工具
for (const tool of page.webmcp.tools()) {
toolRegistry.set(tool.name, tool.description);
}
事件订阅遵循 EventEmitter 的标准用法,可以使用 page.webmcp.once('toolsremoved', handler) 只响应下一次移除,也可以用 page.webmcp.off('toolsremoved', handler) 取消订阅。tools 字段中携带的完整 WebMCPTool 对象还额外提供了 frame、location 等信息,可用来区分不同子帧中的同名工具或定位工具来源代码。
环境要求与使用前提
需要强调的是,WebMCP 整体属于实验性能力。在 Page 的抽象定义中,webmcp 访问器被标注为 Experimental API,要求 Chrome 151+ 且以 --enable-features=WebMCP 启动(见 packages/puppeteer-core/src/api/Page.ts)。测试代码也通过 setupSeparateTestBrowserHooks({ args: ['--enable-features=WebMCP'] }) 来搭建运行环境(test/src/cdp/webmcp.test.ts#L20-L24)。在不满足该前提的浏览器/Chrome 版本上,page.webmcp 相关能力可能不可用,接口定义与行为可能随规范演进而变化。
同时,WebMCPToolsRemovedEvent 只是事件数据契约,其语义正确性建立在页面侧声明式(表单)或命令式(modelContext.registerTool)工具机制之上,编写自动化脚本时应结合目标页面的实际实现确认工具注册方式,从而准确预测 toolsremoved 的出现时机。
小结
WebMCPToolsRemovedEvent是 WebMCP 事件体系中的"工具移除"负载类型,唯一字段tools为 WebMCPTool[];- 它与 WebMCPToolsAddedEvent 结构对称,分别服务于
toolsremoved与toolsadded事件; - Puppeteer 内部将 CDP 的
WebMCP.toolsRemoved协议事件与帧上下文销毁清理统一映射为该事件并维护内部工具缓存(packages/puppeteer-core/src/cdp/WebMCP.ts); - 显式注销、表单移除、跨文档导航都会触发该事件,仓库测试用例可作为验证行为是否一致的可执行规范。