WebMCP API 更新

François Beaufort
François Beaufort

发布时间:2026 年 11 月 26 日

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

请关注此页面,跟踪不同 Chrome 版本中 WebMCP 的 API 新增、行为变更和破坏性更改。

早期版本中的代码示例反映了每次更改时的 API 形式。如需了解最新用法,请参阅命令式 API 和声明式 API 文档。

Chrome 160

新 Tool 接口取代了 RegisteredTool 字典

在 PR #348 之后,getTools() 返回的对象现在是新 Tool 接口的实例,而不是 RegisteredTool 字典。此外,用于公开注册了该工具的文档窗口的 window 成员现在称为 source。此变更从 Chrome 160.0.8173.0 开始生效。

getTools() 返回的每个 Tool 都有一个唯一的内部 ID。executeTool() 会引用此 ID 来运行该工具。这修复了多个竞态条件,例如工具在运行时被取消注册。它还为运行由不透明来源文档注册的工具以及未来的 worker 集成做好了准备。

由于 Tool 现在是接口对象,因此请注意以下其他兼容性更改:

  • 现在,如果留空,inputSchema、outputSchema 和 annotations 将为 null,而不是 undefined。
  • JSON.stringify(tool) 会返回 "{}",而展开运算符 ({...tool}) 不会复制任何内容。请改为明确读取您需要的属性。
  • structuredClone(tool) 会抛出异常,因为 Tool 不可序列化。

以下示例读取工具的属性,同时保持与之前的 RegisteredTool 字典向后兼容:

const tools = await document.modelContext.getTools();
for (const tool of tools) {
  // TODO: Remove `tool.window` fallback when Chrome 160 reaches Stable (January 5, 2027).
  const source = tool.source ?? tool.window;

  // Use explicit properties rather than JSON.stringify(tool) or {...tool}.
  const { name, title, description, origin } = tool;
  const inputSchema = tool.inputSchema ?? null;
  const outputSchema = tool.outputSchema ?? null;
  const annotations = tool.annotations ?? null;

  console.log({ name, title, description, origin, inputSchema, outputSchema, annotations, source });
}

Chrome 159

在 registerTool 中添加 outputSchema 支持

从 Chrome 159.0.8140.0 开始,document.modelContext.registerTool() 支持可选的 outputSchema 属性。使用它为工具的返回值声明 JSON 架构,就像 inputSchema 描述其参数一样。规范更改位于 PR #254 中。

规范尚未定义当工具的输出与其 outputSchema 不匹配时,executeTool() 是否会失败(请参阅问题 #92)。目前,智能体 Harness 应根据每个工具的 outputSchema 检查其输出,然后再将其返回给模型。如果不匹配,请向模型发送明确的验证错误,而不是格式错误的数据。如需查看示例,请参阅 webmcp-extension PR #98。

await document.modelContext.registerTool({
  name: "getWeather",
  description: "Returns the current weather for a city.",
  inputSchema: {
    type: "object",
    properties: { city: { type: "string" } },
    required: ["city"]
  },
  outputSchema: {
    type: "object",
    properties: {
      temperature: { type: "number" },
      conditions: { type: "string" }
    },
    required: ["temperature", "conditions"]
  },
  async execute({ city }) { /* ... */ }
});

Chrome 156

将 ontoolactivated 和 ontoolcancel 重新定位到 document.modelContext

从 Chrome 156.0.8076.0 开始,ontoolactivated 和 ontoolcancel 事件处理脚本属性将从 window 移至 document.modelContext(请参阅 PR #245)。这些事件处理脚本分别指示工具执行何时开始以及何时取消。

以下示例会处理这两个事件,同时保持与旧版事件处理脚本的向后兼容性:

const targetFor = (type, listener, options) =>
  (`on${type}` in (document.modelContext ?? {}) ? document.modelContext : window)
    .addEventListener(type, listener, options);

targetFor("toolactivated", ({ toolName }) => {
  console.log(`Tool "${toolName}" started execution.`);
});
targetFor("toolcancel", ({ toolName }) => {
  console.log(`Tool "${toolName}" execution is cancelled.`);
});

向 ToolAnnotations 添加调试成员

从 Chrome 156.0.8067.0 开始,ToolAnnotations 包含一个新的 debugging 成员。

为开发者工具注册工具时,请将 debugging 设置为 true。这包括检查、框架测试和 Chrome 开发者工具 AI 辅助功能。 这有助于通用代理和最终用户代理过滤掉面向开发者的工具。如需了解完整的技术详情,请参阅 PR #253。

await document.modelContext.registerTool({
  name: "getInternalState",
  description: "Returns internal component state for diagnostics and troubleshooting.",
  inputSchema: {
    type: "object",
    properties: { componentId: { type: "string", description: "ID of the component to inspect" } },
    required: ["componentId"],
  },
  execute: ({ componentId }) => {
    return myFramework.getState(componentId);
  },
  annotations: {
    readOnlyHint: true,
    debugging: true, // Diagnostic tool intended for troubleshooting
  },
});

Chrome 155

更改 executeTool 输入参数类型

在 PR #246 和 PR #251 之后,executeTool() 的输入参数类型从 DOMString 更改为可选的 JavaScript 对象(从 Chrome 155.0.8052.0 开始)。

以前,executeTool() 需要字符串化的输入实参。直接接受可选 JavaScript 对象可避免手动调用 JSON.stringify(),并与 ToolExecuteCallback 的 inputObject 保持一致。如果输入对象既不是有效的 JavaScript 对象,也无法序列化为 JSON 字符串,则 executeTool() 返回的 promise 现在会拒绝。

以下示例传递输入对象,同时保持与现有字符串化输入参数的向后兼容性:

const inputObject = { answer: 42 };

let result;
try {
  result = await document.modelContext.executeTool(myTool, inputObject);
} catch (e) {
  // TODO: Remove when executeTool doesn't accept JSON stringified inputArgs in Chrome Stable.
  if (e.message.startsWith("Failed to parse input")) {
    result = await document.modelContext.executeTool(myTool, JSON.stringify(inputObject));
  } else {
    throw e;
  }
}

更改 RegisteredTool inputSchema 类型

在 PR #241 之后,从 Chrome 155.0.8051.0 开始,RegisteredTool 上的 inputSchema 属性类型从 DOMString 更改为 JavaScript 对象。此变更最初在 Chrome 154.0.8014.0 中实施,但后来暂时还原。

之前,虽然 ModelContextTool#inputSchema 在注册期间被定义为对象,但使用 getTools() 检索时,RegisteredTool#inputSchema 会返回字符串化的 JSON 架构 (DOMString)。此项变更确保 RegisteredTool#inputSchema 始终返回一个 JavaScript 对象,该对象是注册时提供的架构的深层副本,从而解决了这种不一致问题。

以下示例将 inputSchema 作为对象进行处理,同时保持与现有字符串化 JSON 架构的向后兼容性:

const [tool] = await document.modelContext.getTools();
const inputSchemaObject =
  typeof tool.inputSchema === "string" ? JSON.parse(tool.inputSchema) : tool.inputSchema;

Chrome 154

向 ToolAnnotations 添加 consequentialHint 成员

从 Chrome 154.0.8017.0 开始,ToolAnnotations 包含一个新的 consequentialHint 成员。

在注册执行高风险、不可逆或现实世界操作(例如预订航班、转账或删除数据)的工具时,请将 consequentialHint 设置为 true。此提示会指示智能体在执行操作之前要求用户明确确认,从而帮助防止意外或未经授权的操作。如需了解完整的技术详情,请参阅问题 176。

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,
  },
  execute: async ({ flightId, passengers }) => {
    // Add your flight booking transaction logic here.
    return `Booked ${passengers} passenger(s) on flight ${flightId}.`;
  },
});

Chrome 153

将 AbortSignal 传递给 ModelContextTool execute 函数

从 Chrome 153.0.8009.0 开始,使用 document.modelContext.registerTool() 注册的工具的 execute 函数始终在其第二个参数中接收 signal,从而将签名更改为 execute(inputObject, { signal })。如需了解完整的技术详情,请参阅问题 #48 和 PR #247。

这样,工具就可以妥善处理由用户或代理发起的执行取消。将此信号传递给长时间运行的异步任务或网络操作(例如 fetch())有助于防止不必要的工作、改进整体资源管理并避免潜在的泄漏。

此外,取消注册工具不再会自动取消正在进行的执行,从而消除了在组件框架中管理工具生命周期时出现的意外副作用。

以下示例将 signal 转发到 fetch() 请求,以便在取消执行时立即中止网络活动。如需了解声明式 API 的用法,请参阅 PR #321。

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";
  },
});

Chrome 152

navigator.modelContext(在 Chrome 150 中已弃用)已从 Chrome 152.0.7943.0 中移除。 请改用 document.modelContext。

Chrome 151

从 registerTool 返回 Promise

从 Chrome 151.0.7922.0 开始,document.modelContext.registerTool() 方法会返回 Promise。 问题 #175 中详细说明了这项更改,这是必要的,因为跨域 iframe 集成允许在框架树中共享工具,从而使注册从根本上变为异步。仅当该工具在其他文档中实际可供 getTools() 使用时,Promise 才会解析,从而确保在 API 演进过程中实现更好的错误处理和向前兼容性。

请更新您的代码,以使用以下示例中所示的异步模式。 如需查看实际示例,请参阅 PR #228 中 WebMCP 演示的更新方式。

try {
  await document.modelContext.registerTool(myTool);
} catch (e) {
  console.error('Tool registration failed:', e);
}

Chrome 150

为了与工具实际上是按文档提供的这一事实保持一致,WebML CG 同意将 modelContext getter 从 Navigator 接口移至 Document 接口。如需了解完整的技术详情,请参阅问题 #173 和 PR #184。

navigator.modelContext 自 Chrome 150.0.7861.0 起已弃用,随后在 Chrome 152 中被移除。改用 document.modelContext。

以下功能检测模式可在迁移前后的 Chrome 版本之间保持兼容性。如需查看实际示例,请参阅 PR #189 中 WebMCP 演示的更新方式。

const modelContext = document.modelContext || navigator.modelContext;
if (modelContext) {
  // Register tools...
}

Chrome 149

向 ToolAnnotations 添加 untrustedContentHint 成员

从 Chrome 149.0.7810.0 开始,ToolAnnotations 包含一个新的 untrustedContentHint 成员。

如果工具处理来自外部或未经验证来源的数据,请将 untrustedContentHint 显式设置为 true,以表明从注册该工具的作者的角度来看,工具的输出包含不可信的数据。如需了解完整的技术详情,请参阅问题 #136。

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

Chrome 148

在 registerTool 中将 unregisterTool 替换为 AbortSignal

WebML CG 同意,取消注册工具所需的所有权级别应与取消注册事件监听器相同。为防止脚本无意或恶意地取消注册并非由其创建的工具,unregisterTool() 已被移除。

从 Chrome 148.0.7757.0 开始,registerTool() 支持可选的 AbortSignal。中止此信号会触发工具的取消注册。如需了解完整的技术详情,请参阅 PR #147。

如需在不同版本之间保持兼容性,请使用类似于以下示例的封装容器。您还可以参考 PR #104,了解 WebMCP 演示的更新方式。

const controller = new AbortController();
navigator.modelContext.registerTool(myTool, { signal: controller.signal });

// Unregister tool later...
navigator.modelContext.unregisterTool?.(myTool.name);
controller.abort();

移除 toolparamtitle 属性

从 Chrome 148.0.7730.0 开始,toolparamtitle 属性已被移除。正如 WebML CG 在 PR #76 中所讨论的那样,任何内容都不会再对合成 JSON 架构中的 title 字段做出贡献。未来仍有可能使用标准 HTML <label> 元素来实现此目的。

Chrome 147

移除 provideContext 和 clearContext

为了改进 WebMCP API 形状,Chrome 147.0.7721.0 中移除了 provideContext() 和 clearContext() 方法。 此项变更在问题 #101 中有详细说明,主要解决了两个架构问题:

  • 在注册新工具之前清除现有工具,provideContext() 带来了安全风险,第三方脚本可能会无意或恶意覆盖官方工具并劫持用户代理互动。
  • 反馈表明,“全部删除”模式在 Web API 中并不常见。 开发者更倾向于采用类似于 addEventListener 的加法模型,以便脚本能够独立管理自己的注册。

如需保持更精细、更安全的控制,请使用 registerTool() 和 unregisterTool()(在 Chrome 148 中被 AbortSignal 取代)。