命令式 API

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

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

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

您可以使用 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,则表示该工具的输出包含工具作者认为不可信的数据(例如用户生成的内容、评论或外部 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 页面代理演示 。 如需了解浏览器扩展程序中的代理如何在同源和跨域 iframe 中查找和运行工具,请参阅示例 WebMCP 扩展程序 。

执行工具

如需手动执行在 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']
});

React 支持

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

Angular 支持

Angular 实验性支持 WebMCP。 如果您的应用已使用 Angular 编写,则可以注册与应用的依赖项注入生命周期相关联的工具,并将信号表单转换为 WebMCP 工具。

Vue 支持

Vue 实验性支持 使用 @vueuse/core 软件包的 WebMCP。如果您的应用已使用 Vue 编写,则可以使用与当前 Vue 作用域生命周期相关联的 useWebMCP 可组合项注册工具。它还支持响应式和条件式工具注册,并自动规范化执行结果。

互动和分享反馈

WebMCP 目前正在积极讨论中,将来可能会发生变化。如果您尝试使用此 API 并有反馈,欢迎与我们分享。