命令式 API

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

發布日期:2026 年 5 月 18 日,上次更新日期:2026 年 10 月 16 日

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

您可以使用 WebMCP Imperative 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.
  },
});

工具註解 (選用)

註冊工具時,您可以在 annotations 屬性中新增中繼資料。這些註解可協助代理和瀏覽器瞭解工具的安全特性、預期副作用、輸出內容可信度,以及目標對象:

  • readOnlyHint (布林值,預設為 false):如果設為 true,表示工具只會讀取資訊,不會修改應用程式或系統的狀態 (例如搜尋產品目錄或擷取訂單狀態)。這有助於代理判斷是否能安全呼叫工具,而不會產生副作用。
  • untrustedContentHint (布林值,預設為 false):如果設為 true,表示從工具作者的角度來看,工具的輸出內容含有不受信任的資料 (例如使用者原創內容、評論或外部網頁資料)。這會向代理和用戶端發出信號,表示傳回的酬載需要更嚴格的安全處理,例如清理或分隔,以減輕間接提示詞注入。
  • consequentialHint (布林值,預設為 false):如果設為 true,表示執行工具會產生重大、實際或不可逆轉的動作 (例如預訂航班、轉帳或刪除資料)。這樣一來,代理和瀏覽器就能在執行高風險工具前,強制顯示使用者確認提示,降低使用者意圖遭意外或惡意誤解的風險。
  • debugging (布林值,預設為 false,Chrome 156 以上版本適用): 如果設為 true,表示工具專為檢查和開發人員工具設計 (例如測試架構或 Chrome 開發人員工具 AI 輔助),而非使用者互動。這樣一來,一般用途和使用者代理程式就能篩除開發人員專用工具。
await document.modelContext.registerTool({
  name: 'book_flight',
  description: 'Book a flight for the user with confirmed flight details.',
  inputSchema: {
    type: 'object',
    properties: {
      flightId: { type: 'string', description: 'ID of the flight to book' },
      passengers: { type: 'number', description: 'Number of tickets to purchase' },
    },
    required: ['flightId', 'passengers'],
  },
  annotations: {
    readOnlyHint: false,
    consequentialHint: true,
    untrustedContentHint: false,
    debugging: false,
  },
  execute: async ({ flightId, passengers }) => {
    // Add your flight booking transaction logic here.
    return `Booked ${passengers} passenger(s) on flight ${flightId}.`;
  },
});

如需註解如何影響代理行為的範例,請參閱「WebMCP 擴充功能範例」。

取消註冊工具

如要移除工具,請將 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();

自 Chrome 153 起,您可以取消註冊工具,而不必取消及中斷執行中的作業。這可避免在元件架構中管理工具生命週期時,發生非預期的副作用。

處理工具取消

execute 函式會接收名為 signal 的 AbortSignal 參數做為第二個引數,以便妥善處理使用者或代理啟動的執行取消作業。將這個信號傳遞至長時間執行的非同步工作或網路作業 (例如 fetch()),有助於避免不必要的工作、改善整體資源管理,並避免潛在的洩漏。

await document.modelContext.registerTool({
  name: 'fetch_tool',
  description: 'Fetch the text content of a URL and stream the response.',
  inputSchema: {
    type: 'object',
    properties: {
      url: { type: 'string', description: 'The URL to fetch' },
      priority: { type: 'string', enum: ['high', 'low', 'auto'] },
    },
    required: ['url'],
  },
  execute: async ({ url, priority }, { signal }) => {
    // Abort the fetch request when tool execution is aborted.
    const response = await fetch(url, { priority, signal });
    const stream = response.body.pipeThrough(new TextDecoderStream());
    for await (const chunk of stream) {
      document.querySelector('pre').textContent += chunk;
    }
    return 'Success';
  },
});

探索工具

使用 document.modelContext.getTools() 擷取可用工具。這個非同步方法會傳回一份已排序的清單,依字母順序排列呼叫文件有權存取的工具。

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

// {
//   annotations: { consequentialHint: false, debugging: false, readOnlyHint: false, untrustedContentHint: true }, // Optional hints
//   description: "Add a new item to the to-do list",
//   inputSchema: {"type":"object","properties":{…}},
//   name: "addTodo",
//   origin: "https://example.com",
//   title: ""
//   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']
});

請參閱 WebMCP 頁面代理程式示範,瞭解如何從 iframe 擷取工具,並在網頁式對話介面中執行。請參閱範例 WebMCP 擴充功能,瞭解瀏覽器擴充功能中的代理如何跨同源和跨源 iframe 尋找及執行工具。

執行工具

如要手動執行在 getTools() 中找到的工具,請呼叫 document.modelContext.executeTool(),並提供可序列化為 JSON 字串的輸入引數 (選用 JavaScript 物件)。這個非同步方法會傳回工具執行結果,或在觸發導覽時傳回空值。

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']
});

支援常見的 JavaScript 架構

React、Angular 和 Vue 實驗性支援 WebMCP。

  • React:使用 use-webmcp-tool 套件。使用與元件掛接和卸載生命週期連結的 useWebMCP 鉤子註冊工具。這個掛鉤支援條件式工具註冊,並會自動正規化執行結果。
  • Angular:註冊與應用程式依附元件注入生命週期相關聯的工具,並將 Signal Forms 轉換為 WebMCP 工具。
  • Vue:使用 @vueuse/core 套件中的 useWebMCP 可組合函式。註冊與目前 Vue 範圍生命週期繫結的工具。Vue 的實作支援反應式和條件式工具註冊,並會自動正規化執行結果。

參與並分享意見

WebMCP 仍在積極討論中,日後可能會有變動。如果您試用這個 API 後有任何意見,歡迎與我們分享。