命令式 API

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

发布时间:2026 年 5 月 18 日

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

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

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

提供模型上下文

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

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

WebMCPza Maker

navigator.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: ({ layer, action }) => {
    toggleLayer(layer, action);
    return `Performed ${action || 'toggle'} on layer: ${layer}`;
  },
});

获取订单状态

navigator.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: ({ 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: ({ 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();
navigator.modelContext.registerTool(addTodoTool, { signal: controller.signal });

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

探索工具

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

const [tool] = await navigator.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 字符串作为输入实参来调用 navigator.modelContext.executeTool()。此异步方法返回工具执行结果,或者在触发导航时返回 null。

const result = await navigator.modelContext.executeTool(tool, '{"text": "Buy milk"}');
console.log(result);

// 'Added to-do: Buy milk'

AbortSignal 作为可选参数传递时,您可以使用它来取消待处理的工具执行。

const controller = new AbortController();
navigator.modelContext.executeTool(tool, '{"text": "Buy milk"}', {
  signal: controller.signal,
});

// Cancel tool execution later...
controller.abort();

事件

框架可以监听 navigator.modelContext 上的 toolchange 事件,以便在可用工具列表发生更改时收到通知。

navigator.modelContext.addEventListener("toolchange", (event) => {
  // Tools have changed.
});

跨源 iframe

WebMCP 支持同时使用权限政策和显式来源限制的跨源 iframe。

“权限”政策

在跨源 iframe 中,工具注册默认处于停用状态。网页必须使用tools 权限政策来委托访问权限:

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

来源曝光

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

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

互动和分享反馈

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