---
title: "WebMCP"
description: "将应用中的操作作为 WebMCP 工具提供给浏览器中的 AI 智能体。"
canonical_url: "https://nuxt.zhcndoc.com/docs/4.x/guide/ai/webmcp"
---
# WebMCP

> 将应用中的操作作为 WebMCP 工具提供给浏览器中的 AI 智能体。

[WebMCP](https://webmachinelearning.github.io/webmcp/) 是一项提议中的浏览器 API，允许页面向浏览器中的 AI 智能体提供工具，使智能体无需猜测该点击哪个按钮，就能将商品加入购物车或提交表单。Nuxt 可以将模板中已绑定的操作转换为 WebMCP 工具。

::important
此功能仍处于实验阶段，其所基于的 API 仍在设计中。工具只会在[支持 WebMCP 的浏览器](#browser-support)中注册。
::

在 `nuxt.config` 中启用此功能：

```ts twoslash [nuxt.config.ts]
export default defineNuxtConfig({
  experimental: {
    webmcp: true,
  },
})
```

## 从模板创建工具

在函数的 JSDoc 中添加 `@tool` 标记，并将该函数绑定到元素的 `@click` 或 `@submit`，或组件上的某个事件。Nuxt 会注册一个以函数命名的工具，并使用 JSDoc 摘要作为工具描述：

```vue [app/pages/index.vue]
<script setup lang="ts">
const { data: products } = await useFetch('/api/products')
const cart = useCart()

/**
 * Add one of a product to the cart. Use when the user wants to buy something.
 * @tool
 */
function addToCart (sku: string) {
  cart.value.push(sku)
}
</script>

<template>
  <ul>
    <li
      v-for="product in products"
      :key="product.sku"
    >
      {{ product.name }}
      <button
        :disabled="!product.inStock"
        @click="addToCart(product.sku)"
      >
        Add
      </button>
    </li>
  </ul>
</template>
```

这会注册一个 `add_to_cart` 工具，并遵循以下规则：

- 参数来自模板，因此智能体无法传入页面上未显示的 SKU；
- 在 `v-for` 中，智能体会通过 `:key` 将条目选作 `target`；通用的 `list_targets` 工具会列出屏幕上显示的条目及其文本；
- `:disabled` 控制工具或其目标是否可以执行；
- 调用会执行绑定的表达式，其返回值就是工具结果。

编写面向智能体的描述时，应说明工具能为用户完成什么操作以及何时使用，不要写实现细节。

`@tool` 后的标记用于描述该操作：

| 标记              | 含义                                                                          |
| --------------- | --------------------------------------------------------------------------- |
| `readonly`      | 该工具只读取数据，因此智能体可以直接调用。                                                       |
| `consequential` | 该工具会产生难以撤销的影响，因此浏览器或智能体可能会先询问用户。                                            |
| `confirm`       | 操作必须由用户完成。调用会高亮相应控件（或填充表单），并返回 `status: "requires_user_action"`，而不会执行操作。    |
| `values`        | 对于表单，当前字段值会作为默认值发送给智能体。请参阅[调用可以读取和更改的内容](#what-a-call-can-read-and-change)。 |

```ts
/**
 * Place the order for everything in the cart. Use when the user is ready to pay.
 * @tool consequential
 */
function checkout () {}
```

## 表单

绑定到 `@submit` 的 `@tool` 函数会变为表单工具。它的输入是表单的 `v-model` 绑定；调用会写入这些值并提交表单，因此你自己的校验逻辑和提交处理函数会像用户操作一样运行。`v-model` 读取表单内部声明的 `v-for` 或插槽变量的字段，不属于该工具的输入。

通过 `@input` 传入 [Standard Schema](https://standardschema.dev)（例如 Zod、Valibot 或 ArkType），或通过表单的 `:schema` 绑定该 schema，以校验输入。实现了 Standard JSON Schema 的 schema（例如 Zod schema），或使用 `@valibot/to-json-schema` 中的 `toStandardJsonSchema()` 包装的 Valibot schema，也会用于向智能体描述输入。否则，类型将根据当前值和原生控件推断，标签则会作为描述。

```vue [app/pages/contact.vue]
<script setup lang="ts">
import { z } from 'zod'

const contactSchema = z.object({
  email: z.email(),
  message: z.string().min(5),
})
const form = reactive({ email: '', message: '' })

/**
 * Send a message to the shop. Use when the user has a question about an order.
 * @tool
 * @input contactSchema
 */
async function sendMessage () {
  await $fetch('/api/contact', { method: 'POST', body: form })
  return 'Sent.'
}
</script>

<template>
  <form @submit.prevent="sendMessage">
    <label>Email <input
      v-model="form.email"
      type="email"
    ></label>
    <label>Message <textarea v-model="form.message" /></label>
    <button type="submit">
      Send
    </button>
  </form>
</template>
```

在写入任何值之前，会先根据 schema 校验输入。写入值后，再检查 `required` 或 `type="email"` 等原生约束；若调用未通过这些约束，表单会恢复原状。

### 调用可以读取和更改的内容 {#what-a-call-can-read-and-change}

表单工具只会填写浏览器判定为已渲染且未禁用、非只读的字段。若调用尝试为其他字段提供值，则会被拒绝。

只有在绑定 `v-model` 的元素显示时，字段才算已渲染。以下情况不算已渲染：被 `v-if` 移除的字段、`<input type="hidden">`，以及通过 `v-show`、`hidden` 属性、`display: none`、`visibility: hidden`、`opacity: 0` 隐藏的字段或位于这类隐藏元素中的字段；位于已关闭 `<details>` 中的字段也不算，无论隐藏设置来自模板还是样式表。被自身可见 `<label>` 遮盖的复选框或单选按钮仍视为已渲染。

已渲染的字段在以下情况下仍会被拒绝：

- 通过 `disabled` 属性、已禁用的 `<fieldset>`、`aria-disabled="true"` 或 `data-disabled` 禁用；
- 通过 `readonly` 属性或 `aria-readonly="true"` 设为只读；
- 位于带有 `inert` 属性的元素内；
- 在模板中设置的组件 `disabled` 或 `readonly` prop 为 `true`；
- 已禁用的 `<option>`、单选按钮或复选框；
- 所提供的值不在任何选项中（隐藏属性或 `display: none` 隐藏的 `<option>` 或 `<optgroup>` 不计入选项）。

只要禁用或只读字段仍保持其原值，重复提交该字段已发布的默认值就会被接受。

表单字段的当前值不会发送给智能体。添加 `values` 标记即可将这些值作为默认值公开，使智能体能够读取已填写的内容：

```ts
/**
 * Save the profile. Use when the user wants to change their details.
 * @tool values
 */
function saveProfile () {}
```

即使启用了 `values`，以下字段的当前值仍不会发送：

- 字段未渲染；
- 字段的 `type="password"`；
- 字段的 `autocomplete` 为 `current-password`、`new-password`、`one-time-code` 或支付卡字段（例如 `cc-number`）；
- schema 将该属性、包含该属性的对象或该对象中的属性标记为 `writeOnly`。

默认值会在表单挂载时读取，因此字段之后即使被隐藏，仍会保留其已公开的默认值。

对于组件，是否已渲染取决于接收组件属性的元素。其他属性则会从该元素及其中第一个原生控件读取。

::warning
以下限制无法检测：

- 移出屏幕、被裁切或被其他元素遮挡的字段仍视为已渲染。
- 如果组件隐藏了自身控件，但外围元素仍显示，该组件仍视为已渲染。
- 无论字段类型如何，schema 为属性声明的默认值都会按原样公开。请勿在 schema 默认值中放入机密信息。
- 启用 `values` 时，如果字段不带上述任何安全标记，其中的机密信息会作为默认值公开。请为其设置 `type="password"`、相应的 `autocomplete`，或在 schema 中将属性设为 `writeOnly`。
- 以其他方式禁用的组件（例如通过对象形式的 `v-bind` 或在组件内部禁用），会被视为可编辑，除非其渲染出的元素带有上述属性之一。
- 如果组件没有将其属性渲染到元素上，则无法填写该组件。

这些检查会将智能体的操作限制在页面向用户提供的范围内。与其他请求一样，请在服务器上校验每次提交并进行授权。
::

## 在代码中创建工具

对于无法对应到单个控件的工具，可使用 `defineAgentTool()` 定义工具，并通过 `useAgentTool()` 在组件挂载期间提供该工具：

```vue [app/components/ProductSearch.vue]
<script setup lang="ts">
import { z } from 'zod'

const searchProducts = defineAgentTool({
  name: 'search_products',
  description: 'Find products by name. Use when the user asks what is for sale.',
  input: z.object({ query: z.string() }),
  annotations: { readOnlyHint: true },
  execute: ({ query }, { signal }) => $fetch('/api/products', { query: { q: query }, signal }),
})

useAgentTool(searchProducts)
</script>
```

`input` 会校验每次调用；当 schema 实现了 Standard JSON Schema 时，还会用于描述工具参数。对于其他 schema，请通过 `inputSchema` 描述参数。

传入包含 `key` 和 `label` 的 `targets`，即可让智能体从多个条目中进行选择；设置 `enabled` 可在不注销工具的情况下使工具暂不可用。智能体通过名为 `target` 的参数选择条目，因此带有 `targets` 的工具不能再将 `target` 用作输入属性。

## 显示智能体的操作

`useAgentActivity()` 会返回正在执行的工具调用，因此你可以向用户展示智能体正在执行的操作，并允许用户停止操作。停止调用会中止传递给 `execute` 的 `signal`，并向智能体返回要求其不要重试的结果。`@tool` 函数作为绑定的事件处理函数运行，不会接收 `signal`：表单工具若在提交前停止，会恢复表单；已经开始运行的处理函数则会执行至完成。

```vue [app/components/AgentStatus.vue]
<script setup lang="ts">
const { current, stop } = useAgentActivity()
</script>

<template>
  <p v-if="current">
    {{ current.message }}
    <button @click="stop">
      Stop
    </button>
  </p>
</template>
```

## 导航

Nuxt 还会注册一个 `navigate` 工具，用于列出应用中的页面，使智能体能够访问其他页面上的操作。页面切换时，工具也会随之更新。设置 `navigate: false` 可禁用该工具：

```ts twoslash [nuxt.config.ts]
export default defineNuxtConfig({
  experimental: {
    webmcp: { navigate: false },
  },
})
```

## 开发

对于无法转换为工具的绑定（例如包装了 `@tool` 函数的处理函数，或使用索引作为 key 的 `v-for`）、不符合 [WebMCP 工具设计指南](https://github.com/GoogleChromeLabs/webmcp-tools)的描述，以及缺少标签的表单字段，Nuxt 会在构建时发出警告。在开发环境中，如果工具或结果过长、超出智能体的处理能力，Nuxt 也会发出警告。

使用 Vite 构建器运行 `nuxt dev` 时，浏览页面期间各页面提供的工具都会写入 `.nuxt/webmcp/schema.json`。此功能适用于任何浏览器。你可以结合 [`webmcp-evals`](https://github.com/GoogleChromeLabs/webmcp-tools/tree/main/webmcp-evals) 检查模型是否选择了正确的工具。设置 `schema` 可将文件写入其他位置，设为 `false` 则可禁用此功能：

```ts twoslash [nuxt.config.ts]
export default defineNuxtConfig({
  experimental: {
    webmcp: { schema: 'webmcp.schema.json' },
  },
})
```

## 浏览器支持 {#browser-support}

WebMCP 目前在 Chrome 中处于早期预览阶段，默认未启用。在不支持 WebMCP 的环境中，不会注册任何工具，应用的行为与未启用此功能时相同。

若要在本地试用工具，请在 Chrome 中启用 `chrome://flags/#enable-webmcp-testing`，或使用 `--enable-features=WebMCP` 启动 Chrome，然后通过 `localhost` 打开应用，因为 WebMCP 需要安全上下文。你还需要一个可以调用 WebMCP 工具的智能体，例如 [Model Context Tool Inspector](https://chromewebstore.google.com/detail/model-context-tool-inspec/gbpdfapgefenggkahomfgkhfehlcenpd) 扩展。

若要向用户提供工具，请为网站[注册 WebMCP Origin Trial](https://developer.chrome.com/origintrials/#/register_trial/4163014905550602241)，并将令牌添加到页面中：

```ts twoslash [nuxt.config.ts]
export default defineNuxtConfig({
  app: {
    head: {
      meta: [
        { 'http-equiv': 'origin-trial', 'content': 'YOUR_ORIGIN_TRIAL_TOKEN' },
      ],
    },
  },
})
```

令牌与注册时使用的源绑定且会过期，因此其他源（例如 staging 或预览部署）需要单独注册令牌。


## Sitemap

See the full [sitemap](https://nuxt.zhcndoc.com/sitemap.md) for all pages.
