命令式 API

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

發布日期:2026 年 5 月 18 日,上次更新日期:2026 年 7 月 1 日

說明影片 網頁 擴充功能 Chrome 狀態 意圖
GitHub 來源試用 來源試用 總覽 實驗意圖

您可以使用 WebMCP 命令式 API,透過標準 JavaScript 定義多種工具。工具可以執行各種函式,例如表單輸入、網站導覽和狀態管理。

使用這項 API 前,請先瞭解用途範例

提供模型背景資訊

使用 modelContext 介面註冊工具。註冊工具時,必須提供名稱、說明和輸入結構定義,並包含相關屬性。

使用 registertool 將單一工具新增至模型環境。

WebMCPza Maker

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

取得訂單狀態

await 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();
await 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 擷取工具,並在網頁式對話介面中執行工具,請參閱 WebMCP 網頁代理程式示範

執行工具

如要手動執行 getTools() 中探索到的工具,請呼叫 document.modelContext.executeTool(),並將輸入引數做為有效的 JSON 字串。這個非同步方法會傳回工具執行結果,或在觸發導覽時傳回空值。

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 權限政策委派存取權:

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

來源曝光

根據預設,工具無法用於跨原始來源文件。您可以在 registerTool 中使用 exposedTo 陣列,列出允許查看及執行工具的特定來源。這個陣列僅支援安全來源。

// https://partner.org

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

Angular 支援

Angular 實驗性支援 WebMCP。如果應用程式已使用 Angular 編寫,您可以註冊與應用程式的依附元件注入生命週期相關聯的工具,並將 Signal Forms 轉換為 WebMCP 工具。

參與討論及分享意見

WebMCP 目前仍在討論階段,日後可能會有變動。如果您試用過這項 API,歡迎提供意見。