命令式 API

Alexandra Klepper
Alexandra Klepper
François Beaufort
François Beaufort

发布时间:2026 年 5 月 18 日,上次更新时间:2026 年 10 月 16 日

说明类视频 Web 扩展程序 Chrome 状态 目的
GitHub 源试用 源试用 查看 实验意向

您可以使用 WebMCP Imperative API 通过标准 JavaScript 定义多种类型的工具。您的工具可以执行不同的功能,例如表单输入、网站导航和状态管理。

在使用此 API 之前,请先了解使用场景示例。

提供模型上下文

使用 modelContext 接口注册工具。工具注册需要提供名称、说明和包含相关属性的输入架构。

使用 registerTool 向模型上下文添加单个工具。

WebMCPza Maker

await document.modelContext.registerTool({
  name: 'toggle_layer',
  description: 'Control pizza layers (sauce, cheese). Use "add", "remove", or "toggle".',
  inputSchema: {
    type: 'object',
    properties: {
      layer: { type: 'string', enum: ['sauce-layer', 'cheese-layer'] },
      action: { type: 'string', enum: ['add', 'remove', 'toggle'] },
    },
    required: ['layer'],
  },
  execute: async ({ layer, action }) => {
    await toggleLayer(layer, action);
    return `Performed ${action || 'toggle'} on layer: ${layer}`;
  },
});

获取订单状态

await document.modelContext.registerTool({
  name: 'get_order_status',
  description: 'Search orders in a given timeframe. Returns order number, shipping status and location',
  inputSchema: {
    "type": "object",
    "properties": {
      "timeframe": { "type": "string", "oneOf": [
        { "type": "string", "const": "today", "title": "Today" },
        { "type": "string", "const": "yesterday", "title": "Yesterday" },
        { "type": "string", "const": "last_7_days", "title": "Last 7 Days" },
        { "type": "string", "const": "last_30_days", "title": "Last 30 Days" },
        { "type": "string", "const": "last_6_months", "title": "Last 6 Months" }],
      "enum": [ "today", "yesterday", "last_7_days", "last_30_days", "last_6_months" ],
      "description": "Timeframe for the order lookup." }
    },
    "required": [ "timeframe" ]
  },
  execute: async ({ timeframe }) => {
    // Add your API or database logic here to fetch and return the order data as a string.
  },
});

工具注解(可选)

注册工具时,您可以在 annotations 属性中添加元数据。这些注解可帮助智能体和浏览器了解工具的安全特性、预期副作用、输出可信度和目标受众:

  • readOnlyHint(布尔值,默认值为 false):如果为 true,则表示该工具仅读取信息,不会修改应用或系统的状态(例如,搜索商品清单或检索订单状态)。这有助于代理确定是否可以安全地调用该工具,而不会产生副作用。
  • untrustedContentHint(布尔值,默认为 false):如果为 true,则表示从工具作者的角度来看,工具的输出包含不可信的数据(例如,用户生成的内容、评价或外部 Web 数据)。这会向智能体和客户端发出信号,表明返回的载荷需要加强安全处理(例如清理或分隔),以缓解间接提示词注入。
  • consequentialHint(布尔值,默认值为 false):如果为 true,则表示执行该工具会产生重大、现实或不可逆的操作(例如,预订航班、转账或删除数据)。这样一来,代理和浏览器就可以在执行高风险工具之前强制显示用户确认提示,从而降低用户意图被意外或恶意误解的风险。
  • debugging(布尔值,默认值为 false,从 Chrome 156 开始提供):如果为 true,则表示该工具专为检查和开发者工具(例如测试框架或 Chrome 开发者工具 AI 辅助功能)而设计,而不是为了与最终用户互动。这样,通用用户代理和最终用户代理就可以滤除面向开发者的工具。
await document.modelContext.registerTool({
  name: 'book_flight',
  description: 'Book a flight for the user with confirmed flight details.',
  inputSchema: {
    type: 'object',
    properties: {
      flightId: { type: 'string', description: 'ID of the flight to book' },
      passengers: { type: 'number', description: 'Number of tickets to purchase' },
    },
    required: ['flightId', 'passengers'],
  },
  annotations: {
    readOnlyHint: false,
    consequentialHint: true,
    untrustedContentHint: false,
    debugging: false,
  },
  execute: async ({ flightId, passengers }) => {
    // Add your flight booking transaction logic here.
    return `Booked ${passengers} passenger(s) on flight ${flightId}.`;
  },
});

如需查看注释如何影响智能体行为的示例,请参阅示例 WebMCP 扩展程序。

取消注册工具

您可以将 AbortSignal 作为可选参数传递,以移除工具。

const addTodoTool = {
  name: "addTodo",
  description: "Add a new item to the to-do list",
  inputSchema: {
    type: "object",
    properties: { text: { type: "string" } },
  },
  execute: async ({ text }) => {
    // You should handle the persistence logic here (omitted for demo)
    return `Added to-do: ${text}`;
  },
  annotations: {
    readOnlyHint: false,
    untrustedContentHint: true
  },
};
const controller = new AbortController();
await document.modelContext.registerTool(addTodoTool, { signal: controller.signal });

// Unregister the tool later...
controller.abort();

从 Chrome 153 开始,您可以取消注册工具,而无需取消和中断正在进行的执行。这样可以防止在组件框架中管理工具生命周期时出现意外的副作用。

处理工具取消

execute 函数接收名为 signal 的 AbortSignal 参数作为其第二个实参,以妥善处理用户或智能体发起的执行取消。将此信号传递给长时间运行的异步任务或网络操作(例如 fetch())有助于防止不必要的工作、改进整体资源管理并避免潜在的泄露。

await document.modelContext.registerTool({
  name: 'fetch_tool',
  description: 'Fetch the text content of a URL and stream the response.',
  inputSchema: {
    type: 'object',
    properties: {
      url: { type: 'string', description: 'The URL to fetch' },
      priority: { type: 'string', enum: ['high', 'low', 'auto'] },
    },
    required: ['url'],
  },
  execute: async ({ url, priority }, { signal }) => {
    // Abort the fetch request when tool execution is aborted.
    const response = await fetch(url, { priority, signal });
    const stream = response.body.pipeThrough(new TextDecoderStream());
    for await (const chunk of stream) {
      document.querySelector('pre').textContent += chunk;
    }
    return 'Success';
  },
});

探索各类工具

使用 document.modelContext.getTools() 检索可用工具。此异步方法会返回调用文档有权访问的工具的列表,按字母顺序排序。

const [tool] = await document.modelContext.getTools();
console.log(tool);

// {
//   annotations: { consequentialHint: false, debugging: false, readOnlyHint: false, untrustedContentHint: true }, // Optional hints
//   description: "Add a new item to the to-do list",
//   inputSchema: {"type":"object","properties":{…}},
//   name: "addTodo",
//   origin: "https://example.com",
//   title: ""
//   window: Window {window: Window, self: Window, …},
// }

默认情况下,getTools() 仅返回由调用文档或框架树中其他同源文档注册的同源工具。如需检索跨域工具,您必须在 fromOrigins 选项中明确列出其来源。此数组仅支持安全来源。

只有在满足以下条件时,系统才会添加来自跨域文档的工具:

  1. 托管来源列在 fromOrigins 选项中。
  2. 该工具已明确向您的源公开。
// https://example.com

// Get same-origin tools only
const sameOriginTools = await document.modelContext.getTools();

// Get same-origin tools plus tools from specific cross-origin documents
const allTools = await document.modelContext.getTools({
  fromOrigins: ['https://partner.org']
});

如需查看如何从 iframe 检索工具并在基于 Web 的聊天界面中执行这些工具的示例,请参阅 WebMCP 页面智能体演示。 请参阅示例 WebMCP 扩展程序,了解浏览器扩展程序中的智能体如何在同源和跨域 iframe 中查找并运行工具。

执行工具

如需手动执行在 getTools() 中发现的工具,请调用 document.modelContext.executeTool(),并传入一个可选的 JavaScript 对象作为输入参数,该对象可序列化为 JSON 字符串。此异步方法会返回工具执行的结果,或者在触发导航时返回 null。

const result = await document.modelContext.executeTool(tool, { text: "Buy milk" });
console.log(result);

// 'Added to-do: Buy milk'

您可以将 AbortSignal 作为可选参数传递,以取消待执行的工具。

const controller = new AbortController();
document.modelContext.executeTool(tool, { text: "Buy milk" }, { signal: controller.signal });

// Cancel tool execution later...
controller.abort();

事件

框架可以监听 document.modelContext 上的 toolchange 事件,以便在可用工具列表发生更改时收到通知。

document.modelContext.addEventListener("toolchange", (event) => {
  // Tools have changed.
});

跨域 iframe

WebMCP 支持同时使用权限政策和显式源限制的跨域 iframe。

权限政策

默认情况下,跨域 iframe 中会停用工具注册。网页必须使用 tools 权限政策 委托访问权限:

<iframe src="https://example.com" allow="tools"></iframe>

源站暴露

默认情况下,工具不适用于跨域文档。您可以使用 registerTool 中的 exposedTo 数组列出允许查看和执行工具的特定来源。此数组仅支持安全来源。

// https://partner.org

await document.modelContext.registerTool({
  name: 'my_shared_tool',
  description: 'Shared across origins',
  // ...
}, {
  exposedTo: ['https://example.com']
});

在常见 JavaScript 框架中提供支持

React、Angular 和 Vue 均提供对 WebMCP 的实验性支持。

  • React:使用 use-webmcp-tool 软件包。使用与组件的装载和卸载生命周期相关联的 useWebMCP 钩子注册工具。此钩子支持条件式工具注册,并会自动对执行结果进行标准化。
  • Angular:注册与应用依赖项注入生命周期相关联的工具,并将 Signal Forms 转换为 WebMCP 工具。
  • Vue:使用 @vueuse/core 软件包中的 useWebMCP 可组合项。注册与当前 Vue 作用域生命周期相关联的工具。Vue 的实现支持响应式和条件式工具注册,并会自动对执行结果进行标准化。

参与互动并分享反馈

WebMCP 目前正处于积极讨论阶段,未来内容可能会有所调整。如果您在试用此 API 后有任何反馈,欢迎与我们分享。