资讯动态

VueUse useWebMCP 实战指南:在 Vue 3 中为 AI Agent 注册 WebMCP 工具并自动管理其生命周期

发布时间:2026/10/3 17:37:15 来源:尧图企业网站定制
前端【免费下载链接】vueuseCollection of essential Vue Composition Utilities for Vue 3项目地址https://gitcode.com/gh_mirrors/vu/vueuse点击查看免费下载导读useWebMCP是 VueUse 在packages/core/useWebMCP下提供的一个组合式函数composable用于把页面中的 JavaScript 函数注册为 WebMCP 规范下的“工具tool”从而让内置于浏览器、iframe 或浏览器扩展中的 AI Agent 能够发现并调用它而无需去解析 DOM、无障碍树或截图。读完本文你将掌握useWebMCP的完整 API 与配置项、响应式注册/注销的底层机制、结果归一化的全部规则以及如何借助源码与测试用例在真实项目中正确接入 WebMCP 工具能力。注意WebMCP 规范目前处于实验阶段其底层命令式 API 暴露在document.modelContext上registerTool 用于注销的AbortSignal。useWebMCP会自动进行特性检测在 API 缺失的环境退化为无操作no-op因此依赖该功能前请先检查isSupported。为什么需要 useWebMCP声明式封装命令式 APIWebMCP 的核心思路是网页把自身的 JavaScript 函数以“工具”的形式暴露出来AI Agent 通过发现与调用这些工具来操作页面而不是通过抓取 DOM、可访问性树或屏幕截图来理解页面。原始的命令式注册方式如下摘自 index.mdconst controller new AbortController() document.modelContext.registerTool({ name: add-todo, description: Add a new item to the user\s active todo list, inputSchema: { /* … */ }, async execute({ text }) { return { content: [{ type: text, text: Added todo item: ${text}. }] } }, }, { signal: controller.signal }) // Unregister later: controller.abort()useWebMCP正是对这个基于AbortSignal的命令式 API 的声明式封装工具在组合式函数运行时注册并在当前作用域scope被销毁时自动注销。这保证了 Agent 看到的工具集合与屏幕上实际存在的 UI 保持同步——组件卸载、路由切换时不再有“幽灵工具”残留在浏览器中。快速上手注册一个 add-todo 工具从vueuse/core导入useWebMCP传入工具描述与execute执行函数即可。以下示例来自 官方文档 与配套的 demo.vueimport { useWebMCP } from vueuse/core import { shallowRef } from vue const todos shallowRefstring[]([]) const { isSupported, isRegistered, error } useWebMCP({ name: add-todo, description: Add a new item to the user\s active todo list, inputSchema: { type: object, properties: { text: { type: string, description: The text content of the todo item }, }, required: [text], }, async execute({ text }) { todos.value [...todos.value, text] return Added todo item: ${text} successfully. }, })在 demo 页面中isSupported、isRegistered与error.message会被直接渲染到模板上方便你实时确认当前浏览器环境是否支持 WebMCP、工具是否已注册、以及是否存在注册错误详见 demo.vue。API 全解选项Options与返回值ReturnuseWebMCP的类型定义位于 packages/core/useWebMCP/index.ts完整选项如下选项类型必填说明nameMaybeRefOrGetterstring是工具标识符Agent 通过它调用该工具descriptionMaybeRefOrGetterstring是自然语言描述Agent 据此决定何时调用inputSchemaMaybeRefOrGetterobject \| undefined否描述工具参数的 JSON SchemaannotationsMaybeRefOrGetterWebMCPToolAnnotations \| undefined否提示信息塑造 Agent 的使用方式如readOnlyHint、untrustedContentHintexecute(args) Result \| PromiseResult是Agent 调用的函数可异步返回值会被归一化为 WebMCP 工具结果抛出的错误或返回的Error会变成isError结果enabledMaybeRefOrGetterboolean否仅当为true时注册工具默认trueformatOutput(result, args) unknown否在归一化前对execute结果进行整形onError(error: unknown) void否当execute或formatOutput抛出/返回错误时的副作用回调documentConfigurableDocument否自定义 document 对象来自ConfigurableDocument默认为全局 document其中annotations支持两个已定义的内置提示见 index.tsreadOnlyHint?: boolean—— 工具不改变状态Agent 可以安全地推测性调用untrustedContentHint?: boolean—— 工具可能返回应被视为不可信的内容。返回值结构UseWebMCPReturn如下返回值类型说明isSupportedComputedRefboolean当前环境是否支持 WebMCP继承自Supportable见 types.tsisRegisteredShallowRefboolean工具当前是否已注册errorShallowRefError \| null注册错误例如由tools权限策略permissions policy导致的NotAllowedError底层原理特性检测、AbortSignal 注销与 watch 重注册深入 index.ts 的实现可以看到三个关键设计严格的特性检测isSupported useSupported(() typeof doc?.modelContext?.registerTool function)。注意这里要求registerTool必须是可调用的函数而不仅仅是modelContext对象存在——一个存在但不完整的 API 会被报告为“不支持”而不是冒出一个注册错误。useSupported内部基于useMounted与computed实现见 useSupported/index.ts。测试 index.test.ts 专门覆盖了“modelContext存在但缺少可调用的registerTool”这一边界情况。AbortSignal 即生命周期注册时创建new AbortController()将其signal传给registerToolcleanup()通过controller?.abort()实现注销并把isRegistered置为false。tryOnScopeDispose(cleanup)保证作用域销毁时自动注销。测试 index.test.ts 验证了“运行即注册、作用域销毁即注销signal 被 abort”的完整闭环。只对可发现字段做响应式重注册watch监听isSupported、name、description、inputSchema、annotations后两者通过safeStringify序列化比较以及enabled任一变化即重新注册。execute、formatOutput、onError则在调用时实时读取因此闭包变化不会造成频繁的重注册。inputSchema与annotations被序列化后再比较意味着“内容相等的新对象”不会触发无谓的重注册——这一行为同样有测试佐证index.test.ts。flush: post确保注册在 DOM 更新后执行。结果归一化execute 的返回值如何变成 MCP 工具结果无论execute返回什么toToolResponseindex.ts都会把它归一化为合法的 MCP 工具结果execute返回/抛出归一化结果字符串{ content: [{ type: text, text }] }undefined/null无返回值{ content: [] }成功、无载荷已经是{ content: [...] }的对象原样透传不做任何改动抛出的值Error或非 Errorthrow not signed in、throw { code: 403 }先触发onError再返回{ content: [{ type: text, text }], isError: true }——失败绝不能对 Agent 表现为成功返回的Error实例与抛出完全同等对待触发onError返回isError结果其他任意值对象/数组/数字通过safeStringify序列化为 JSON 文本块两个值得注意的实现细节safeStringifyindex.ts对JSON.stringify做了 try/catch 包裹循环引用或BigInt等不可序列化值不会让一次成功调用变成错误——测试 index.test.ts 用循环引用对象验证了这一行为toErrorResponseindex.ts对抛出的Error取message对抛出的字符串原样使用对抛出的对象则safeStringify并始终带上isError: true。execute内部的实际执行链index.ts为await options.execute(args)→ 若有formatOutput则先整形 → 若结果是Error实例则抛出 →toToolResponse任何异常都会进入 catch先调用onError其自身抛错会被吞掉绝不影响工具执行路径测试见 index.test.ts再返回toErrorResponse(err)。响应式与条件注册按登录状态暴露工具name、description、inputSchema、annotations和enabled都接受 ref 或 getter。可发现字段discoverable field变化会触发重注册切换enabled则先注销再重新注册。官方文档给出了“仅登录后暴露 checkout 工具”的示例import { useWebMCP } from vueuse/core import { shallowRef } from vue const signedIn shallowRef(false) useWebMCP({ name: checkout, description: Complete the checkout for the current cart, enabled: signedIn, // only exposed to agents while signed in annotations: { readOnlyHint: false }, execute() { // … }, onError(err) { console.error(checkout tool failed, err) }, })测试 index.test.ts 验证了enabled为false时不注册、翻转为true时注册、再翻回false时注销。这一模式非常适合按登录态、订阅等级或页面可见性动态控制 Agent 可用的工具面。注册多个工具一次注册一个工具需要多个工具就多次调用useWebMCP——每次调用各自管理独立的注册生命周期互不干扰import { useWebMCP } from vueuse/core useWebMCP({ name: add-todo, description: Add a new item to the todo list, execute({ text }) { // … }, }) useWebMCP({ name: clear-todos, description: Remove every item from the todo list, annotations: { readOnlyHint: false }, execute() { // … }, })实战要点与最佳实践综合源码与测试以下是接入useWebMCP时的关键建议先查isSupported再做能力展示WebMCP 是实验性规范在无document.modelContext.registerTool的环境绝大多数现有浏览器中useWebMCP会安静地退化为 no-opisRegistered恒为false、error恒为null。应据此降级 UI 提示而不是报错。善用enabled做条件暴露把注册条件声明式地绑定到登录态等响应式状态切换时无需手写注册/注销逻辑。保持execute返回语义清晰成功时返回字符串或可序列化对象失败时抛错或返回Error配合onError做本地日志/上报Agent 端将收到带isError: true的结果不会误读为成功。注册失败要检查error例如tools权限策略被禁用时registerTool会抛出NotAllowedError该错误会被捕获并写入error测试见 index.test.ts。工具在组件卸载时自动注销依托tryOnScopeDispose与 Vue 的 effect scope 生命周期深度绑定路由切换或组件销毁后 Agent 不会再看到已不存在的工具。参考资料WebMCP explainer specwebmachinelearning/webmcpGoogleChromeLabs/use-webmcp-tool——本组合式函数所参照的 React Hook 实现如果想进一步阅读源码与测试可前往仓库内的 packages/core/useWebMCP/index.ts、packages/core/useWebMCP/index.test.ts 与 packages/core/useWebMCP/demo.vue 深入研习。赞分享前端【免费下载链接】vueuseCollection of essential Vue Composition Utilities for Vue 3项目地址https://gitcode.com/gh_mirrors/vu/vueuse点击查看免费下载相关推荐VueUse tryOnScopeDispose 详解在 effect scope 生命周期中安全注册清理逻辑VueUse tryOnScopeDispose 详解在 effect scope 生命周期中安全注册清理逻辑 tryOnScopeDispose 是 VueAI 应用人工智能大模型数字人AI Agent语音前端后端桌面应用移动开发即时通讯3D渲染FluentValidation 依赖注入集成指南手动注册、自动扫描与生命周期管理实战FluentValidation 依赖注入集成指南手动注册、自动扫描与生命周期管理实战 本指南围绕 FluentValidation 的依赖注入DI集成展后端AI Agent 生命周期状态机实战用 agentmesh 的 lifecycle-transitions 示例管理 Agent 全生命周期AI Agent 生命周期状态机实战用 agentmesh 的 lifecycle transitions 示例管理 Agent 全生命周期 本篇文章以 ag人工智能AI AgentAI 安全治理策略引擎认证鉴权Agent 沙箱可观测性上一篇MouseJiggler 免费防锁屏工具3 种模式 1 行命令30 秒装好下一篇Hutool-core 核心工具库完全指南集合、IO、日期、转换与 20 基础工具的源码级解析创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价 →
↑