命令式 API

Alexandra Klepper
Alexandra Klepper

發布日期:2026 年 5 月 18 日

說明 網頁 擴充功能 Chrome 狀態 意圖
GitHub 開發人員試用 開發人員試用 開發人員試用 開發人員試用 查看 實驗意圖

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

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

提供模型背景資訊

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

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

WebMCPza Maker

navigator.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: ({ layer, action }) => {
    toggleLayer(layer, action);
    return `Performed ${action || 'toggle'} on layer: ${layer}`;
  },
});

取得訂單狀態

navigator.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" ]
  }
});

您可以傳遞 AbortSignal 做為選用參數,移除工具。

const addTodoTool = {
  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
  },
};
const controller = new AbortController();
navigator.modelContext.registerTool(addTodoTool, { signal: controller.signal });

// Unregister the tool later...
controller.abort();

參與討論及分享意見

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