命令式 API

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

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

说明类视频 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() 仅返回调用文档或框架树中其他同源文档注册的同源工具。如需检索跨源工具,您必须在 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() 中发现的工具,请使用有效的 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 支持同时使用权限政策和显式来源限制的跨源 iframe。

“权限”政策

默认情况下,跨源 iframe 中停用了工具注册。网页必须使用 tools Permissions Policy 委托访问权限:

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

来源曝光

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

// https://partner.org

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

互动和分享反馈

WebMCP 正在积极讨论中,未来可能会发生变化。如果您尝试使用此 API 并有反馈,我们非常期待收到您的反馈。