命令式 API

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

Published: May 18, 2026

说明类视频 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 支持同时使用权限政策和显式来源 gating 的跨源 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 并有反馈,欢迎告诉我们。