命令式 API

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

發布日期:2026 年 5 月 18 日,上次更新日期:2026 年 9 月 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.
  },
});

工具註解 (選填)

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

  • readOnlyHint (布林值,預設為 false):如設為 true,表示工具只會讀取資訊,不會修改應用程式或系統的狀態 (例如搜尋產品目錄或擷取訂單狀態)。這有助於判斷是否能安全呼叫工具,不會產生副作用。
  • untrustedContentHint (布林值,預設為 false):當 true 時,表示工具的輸出內容含有工具作者認為不可信的資料 (例如使用者原創內容、評論或外部網路資料)。這會向代理和用戶端發出信號,表示傳回的酬載需要加強安全處理,例如清除或劃分界線,以減輕間接提示詞注入的影響。
  • consequentialHint (布林值,預設為 false):如設為 true,表示執行工具會導致重大、實際或不可逆的動作 (例如預訂航班、轉移款項或刪除資料)。這項功能可讓代理程式和瀏覽器在執行高風險工具前,強制顯示使用者確認提示,降低意外或惡意誤解使用者意圖的風險。
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,
  },
  execute: async ({ flightId, passengers }) => {
    // Add your flight booking transaction logic here.
    return `Booked ${passengers} passenger(s) on flight ${flightId}.`;
  },
});

取消註冊工具

您可以傳遞 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 函式會收到名為 signalAbortSignal 參數做為第二個引數,以便妥善處理使用者或代理發起的執行作業取消要求。將這個信號傳遞至長時間執行的非同步工作或網路作業 (例如 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, 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']
});

如需如何從 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']
});

React 支援

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

Angular 支援

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

參與討論及分享意見

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