發布日期:2026 年 11 月 26 日
| 說明影片 | 網頁 | 擴充功能 | Chrome 狀態 | 意圖 |
|---|---|---|---|---|
| GitHub | 總覽 | 實驗意圖 |
請參閱本頁面,追蹤 Chrome 各版本中 WebMCP 的 API 新增、行為變更和破壞性變更。
早期版本中的程式碼範例反映了每次變更時的 API 形式。如需最新用法,請參閱命令式 API 和宣告式 API 說明文件。
Chrome 160
新 Tool 介面取代 RegisteredTool 字典
根據 PR #348,getTools() 傳回的物件現在是新 Tool 介面的例項,而非 RegisteredTool 字典。此外,window 成員 (會公開註冊工具的文件視窗) 現在稱為 source。這項異動自 Chrome 160.0.8173.0 起生效。
getTools() 傳回的每個 Tool 都有專屬的內部 ID。executeTool() 會參照這個 ID 來執行工具。這修正了多個競爭狀況,例如工具在執行時取消註冊。此外,這項功能也為執行不透明來源文件註冊的工具,以及日後整合 worker 做好準備。
由於 Tool 現在是介面物件,請留意下列其他相容性變更:
- 如果留空,
inputSchema、outputSchema和annotations現在會是null,而非undefined。 JSON.stringify(tool)會傳回"{}",而展開運算子 ({...tool}) 不會複製任何內容。請改為明確讀取所需屬性。structuredClone(tool)擲回,因為Tool無法序列化。
以下範例會讀取工具的屬性,同時與先前的 RegisteredTool 字典回溯相容:
const tools = await document.modelContext.getTools();
for (const tool of tools) {
// TODO: Remove `tool.window` fallback when Chrome 160 reaches Stable (January 5, 2027).
const source = tool.source ?? tool.window;
// Use explicit properties rather than JSON.stringify(tool) or {...tool}.
const { name, title, description, origin } = tool;
const inputSchema = tool.inputSchema ?? null;
const outputSchema = tool.outputSchema ?? null;
const annotations = tool.annotations ?? null;
console.log({ name, title, description, origin, inputSchema, outputSchema, annotations, source });
}
Chrome 159
在 registerTool 中新增 outputSchema 支援
從 Chrome 159.0.8140.0 開始,document.modelContext.registerTool() 支援選用的 outputSchema 屬性。您可以使用這個欄位,為工具的傳回值宣告 JSON 結構定義,就像 inputSchema 描述參數一樣。規格變更位於 PR #254。
規格尚未定義當工具的輸出內容
與其 outputSchema 不符時,executeTool() 是否會失敗 (請參閱
問題 #92)。目前,代理駕馭系統應先根據 outputSchema 檢查每項工具的輸出內容,再傳回模型。如果不相符,請傳送明確的驗證錯誤給模型,而非格式錯誤的資料。如需範例,請參閱 webmcp-extension PR #98。
await document.modelContext.registerTool({
name: "getWeather",
description: "Returns the current weather for a city.",
inputSchema: {
type: "object",
properties: { city: { type: "string" } },
required: ["city"]
},
outputSchema: {
type: "object",
properties: {
temperature: { type: "number" },
conditions: { type: "string" }
},
required: ["temperature", "conditions"]
},
async execute({ city }) { /* ... */ }
});
Chrome 156
將 ontoolactivated 和 ontoolcancel 移至 document.modelContext
自 Chrome 156.0.8076.0 起,ontoolactivated 和 ontoolcancel 事件處理常式屬性會從 window 移至 document.modelContext (請參閱 PR #245)。這些事件處理常式分別指出工具執行作業的開始和取消時間。
以下範例會處理這兩項事件,同時維持與舊版事件處理常式的回溯相容性:
const targetFor = (type, listener, options) =>
(`on${type}` in (document.modelContext ?? {}) ? document.modelContext : window)
.addEventListener(type, listener, options);
targetFor("toolactivated", ({ toolName }) => {
console.log(`Tool "${toolName}" started execution.`);
});
targetFor("toolcancel", ({ toolName }) => {
console.log(`Tool "${toolName}" execution is cancelled.`);
});
將偵錯成員新增至 ToolAnnotations
從 Chrome 156.0.8067.0 開始,ToolAnnotations 包含新的 debugging 成員。
為開發人員工具註冊工具時,請將 debugging 設為 true。包括檢查、架構測試和 Chrome 開發人員工具 AI 輔助功能。這有助於一般用途和使用者代理程式篩除開發人員專用工具。如需完整的技術詳細資料,請參閱 PR #253。
await document.modelContext.registerTool({
name: "getInternalState",
description: "Returns internal component state for diagnostics and troubleshooting.",
inputSchema: {
type: "object",
properties: { componentId: { type: "string", description: "ID of the component to inspect" } },
required: ["componentId"],
},
execute: ({ componentId }) => {
return myFramework.getState(componentId);
},
annotations: {
readOnlyHint: true,
debugging: true, // Diagnostic tool intended for troubleshooting
},
});
Chrome 155
變更 executeTool 輸入引數類型
在 PR #246 和 PR #251 之後,executeTool() 的輸入引數類型已從 DOMString 變更為 Chrome 155.0.8052.0 的選用 JavaScript 物件。
先前,executeTool() 需要字串化的輸入引數。直接接受選用的 JavaScript 物件,可避免手動呼叫 JSON.stringify(),並與 ToolExecuteCallback 的 inputObject 保持一致。如果輸入物件不是有效的 JavaScript 物件,也無法序列化為 JSON 字串,executeTool() 傳回的 Promise 現在會遭到拒絕。
以下範例會傳遞輸入物件,同時維持現有字串化輸入引數的回溯相容性:
const inputObject = { answer: 42 };
let result;
try {
result = await document.modelContext.executeTool(myTool, inputObject);
} catch (e) {
// TODO: Remove when executeTool doesn't accept JSON stringified inputArgs in Chrome Stable.
if (e.message.startsWith("Failed to parse input")) {
result = await document.modelContext.executeTool(myTool, JSON.stringify(inputObject));
} else {
throw e;
}
}
變更 RegisteredTool inputSchema 類型
根據 PR #241,RegisteredTool 的 inputSchema 屬性類型已從 DOMString 變更為 Chrome 155.0.8051.0 的 JavaScript 物件。這項異動最初在 Chrome 154.0.8014.0 中推出,但已暫時還原。
先前,雖然 ModelContextTool#inputSchema 在註冊期間定義為物件,但使用 getTools() 擷取時,RegisteredTool#inputSchema 會傳回字串化的 JSON 結構定義 (DOMString)。這項異動可確保 RegisteredTool#inputSchema 一律傳回 JavaScript 物件,也就是註冊時提供的結構定義深層副本,解決不一致的問題。
以下範例將 inputSchema 視為物件,同時維持現有字串化 JSON 結構定義的回溯相容性:
const [tool] = await document.modelContext.getTools();
const inputSchemaObject =
typeof tool.inputSchema === "string" ? JSON.parse(tool.inputSchema) : tool.inputSchema;
Chrome 154
將 consequentialHint 成員新增至 ToolAnnotations
從 Chrome 154.0.8017.0 開始,ToolAnnotations 包含新的 consequentialHint 成員。
註冊會執行高風險、不可逆或實際操作的工具 (例如預訂航班、轉帳或刪除資料) 時,請將 consequentialHint 設為 true。這項提示會指示代理在執行前,必須取得使用者明確確認,有助於防止非預期或未經授權的操作。如需完整的技術詳細資料,請參閱問題 #176。
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}.`;
},
});
Chrome 153
將 AbortSignal 傳遞至 ModelContextTool 執行函式
從 Chrome 153.0.8009.0 開始,使用 document.modelContext.registerTool() 註冊的工具 execute 函式一律會在第二個引數中接收 signal,將簽章變更為 execute(inputObject, { signal })。如需完整的技術詳細資料,請參閱問題 #48和 PR #247。
這樣一來,工具就能妥善處理使用者或代理啟動的執行取消作業。將這個信號傳遞至長時間執行的非同步工作或網路作業 (例如 fetch()),有助於避免不必要的工作、改善整體資源管理,並避免潛在的洩漏。
此外,取消註冊工具時,系統不會再自動取消執行中的作業,因此在元件架構中管理工具生命週期時,不會產生非預期的副作用。
以下範例會將 signal 轉送至 fetch() 要求,因此當執行作業取消時,網路活動會立即中止。如需宣告式 API 用法,請參閱 PR #321。
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";
},
});
Chrome 152
移除 navigator.modelContext
navigator.modelContext 已在 Chrome 150 中淘汰,並於 Chrome 152.0.7943.0 移除。改用 document.modelContext。
Chrome 151
從 registerTool 傳回 Promise
document.modelContext.registerTool() 方法會從 Chrome 151.0.7922.0 開始傳回 Promise。這項變更 (詳情請參閱問題 #175) 是必要的,因為跨來源 iframe 整合可讓工具在框架樹狀結構中共用,使註冊作業基本上是非同步的。只有在其他文件中的 getTools() 實際可使用該工具時,Promise 才會解析,確保在 API 演進時,能更妥善處理錯誤並向前相容。
請更新程式碼,改用下列範例所示的非同步模式。如需實際範例,請參閱 PR #228,瞭解 WebMCP 示範的更新方式。
try {
await document.modelContext.registerTool(myTool);
} catch (e) {
console.error('Tool registration failed:', e);
}
Chrome 150
淘汰 navigator.modelContext,改用 document.modelContext
為了配合工具實際上是依文件區分的事實,WebML CG 同意將 modelContext getter 從 Navigator 介面移至 Document 介面。如需完整的技術詳細資料,請參閱問題 #173 和 PR #184。
navigator.modelContext 自 Chrome 150.0.7861.0 起淘汰,並於 Chrome 152 移除。改用 document.modelContext。
下列功能偵測模式可維持 Chrome 版本在遷移前後的相容性。如需實際範例,請參閱 PR #189,瞭解 WebMCP 示範的更新方式。
const modelContext = document.modelContext || navigator.modelContext;
if (modelContext) {
// Register tools...
}
Chrome 149
將 untrustedContentHint 成員新增至 ToolAnnotations
從 Chrome 149.0.7810.0 開始,ToolAnnotations 包含新的 untrustedContentHint 成員。
如果工具會處理來自外部或未經驗證來源的資料,請明確將 untrustedContentHint 設為 true,表示工具的輸出內容含有註冊工具的作者認為不可信的資料。如需完整的技術詳細資料,請參閱問題 #136。
navigator.modelContext.registerTool({
name: "addTodo",
description: "Add a new item to the todo list",
inputSchema: {
type: "object",
properties: { text: { type: "string" } },
},
execute: ({ text }) => {
// You should handle the persistence logic here (omitted for demo)
return `Added todo: ${text}`;
},
annotations: { readOnlyHint: false, untrustedContentHint: true },
});
Chrome 148
在 registerTool 中將 unregisterTool 替換為 AbortSignal
WebML CG 同意,取消註冊工具所需的所有權層級,應與取消註冊事件監聽器相同。為防止指令碼不小心或惡意取消註冊非其建立的工具,系統會移除 unregisterTool()。
從 Chrome 148.0.7757.0 開始,registerTool() 支援選用的 AbortSignal。取消這個信號會觸發工具取消註冊。如需完整的技術詳細資料,請參閱 PR #147。
如要維持各版本之間的相容性,請使用類似以下範例的包裝函式。您也可以參考 PR #104,瞭解 WebMCP 示範的更新方式。
const controller = new AbortController();
navigator.modelContext.registerTool(myTool, { signal: controller.signal });
// Unregister tool later...
navigator.modelContext.unregisterTool?.(myTool.name);
controller.abort();
移除 toolparamtitle 屬性
自 Chrome 148.0.7730.0 起,系統會移除 toolparamtitle 屬性。如 WebML CG 的 PR #76 所述,合成 JSON 結構定義中的 title 欄位已不再有任何內容。未來仍有可能使用標準 HTML <label> 元素。
Chrome 147
移除 provideContext 和 clearContext
為改善 WebMCP API 形式,Chrome 147.0.7721.0 移除了 provideContext() 和 clearContext() 方法。這項異動詳情請參閱問題 #101,主要解決兩個架構問題:
- 在註冊新工具前清除現有工具,
provideContext()會造成安全風險,第三方指令碼可能會在無意中或惡意覆寫官方工具,並劫持使用者代理程式互動。 - 根據意見回饋,「全部刪除」模式在網頁 API 中並不常見。開發人員偏好類似
addEventListener的附加模型,讓指令碼能獨立管理自己的註冊。
如要維持更精細、更安全的控制,請使用 registerTool() 和 unregisterTool() (在 Chrome 148 中由 AbortSignal 取代)。