命令式 API

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

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

说明类视频 Web 扩展程序 Chrome 状态 目的
GitHub 源试用 源试用 查看 Intent to Experiment

您可以使用 WebMCP 命令式 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 时,表示工具的输出包含工具作者认为不可信的数据(例如用户生成的内容、评价或外部网络数据)。这会向代理和客户端发出信号,表明返回的载荷需要采取更严格的安全处理措施(例如清理或分隔),以缓解间接提示注入
  • 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}.`;
  },
});

取消注册工具

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 函数接收一个名为 signalAbortSignal 参数作为其第二个实参,以便妥善处理用户或代理发起的执行取消。将此信号传递给长时间运行的异步任务或网络操作(例如 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 Page Agent 演示

执行工具

如需手动执行在 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 支持同时使用权限政策和显式源 gating 的跨源 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']
});

React 支持

React 使用 usewebmcp 软件包实验性地支持 WebMCP。如果您的应用已使用 React 编写,则可以使用与组件的挂载和卸载生命周期相关联的独立钩子来注册工具。useWebMCP hook 还提供基于架构的类型推断,并公开本地执行状态。

Angular 支持

Angular 实验性支持 WebMCP。 如果您的应用已使用 Angular 编写,您可以注册与应用依赖项注入生命周期绑定的工具,并将 Signal Forms 转换为 WebMCP 工具。

互动和分享反馈

WebMCP 正在积极讨论中,将来可能会发生变化。如果您试用了此 API 并有任何反馈,欢迎随时告诉我们。