命令式 API

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

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

說明 網頁 擴充功能 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 Permissions Policy 委派存取權:

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

React 支援

React 實驗性支援 WebMCP,使用 usewebmcp 套件。如果應用程式已使用 React 編寫,您可以使用與元件掛接和卸載生命週期相關聯的獨立掛鉤註冊工具。useWebMCP 鉤子也提供結構定義導向的類型推論,並公開本機執行狀態。

Angular 支援

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

Vue 支援

Vue 實驗性支援 WebMCP,可使用 @vueuse/core 套件。如果應用程式已使用 Vue 編寫,您可以使用與目前 Vue 範圍生命週期連結的 useWebMCP 可組合函式註冊工具。此外,還支援反應式和條件式工具註冊,並自動將執行結果標準化。

互動及分享意見

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