命令式 API

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

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

说明类视频 Web 扩展程序 Chrome 状态 目的
GitHub 开发者试用 开发者试用 查看 实验目的

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

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

提供模型上下文

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

使用 registertool 将单个工具添加到模型上下文。

WebMCPza Maker

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

获取订单状态

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

您可以将 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();
document.modelContext.registerTool(addTodoTool, { signal: controller.signal });

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

探索各类工具

如需查看可用工具,请使用 document.modelContext.getTools()。此异步方法会返回调用文档有权访问的工具列表(根据其来源)。

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

// {
//   annotations: { readOnlyHint: false, untrustedContentHint: true },
//   description: "Add a new item to the to-do list",
//   inputSchema: '{"type":"object","properties":{"text":{"type":"string"}}}',
//   name: "addTodo",
//   origin: "https://example.com",
//   window: Window {window: Window, self: Window, ...},
// }

执行工具

如需手动执行在 getTools() 中发现的工具,请使用有效的 JSON 字符串作为输入实参调用 document.modelContext.executeTool()。此异步方法会返回工具执行结果;如果触发了导航,则返回 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 数组列出允许查看和执行工具的特定来源。此数组仅支持安全来源。

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

互动和分享反馈

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