命令式 API

Alexandra Klepper
Alexandra Klepper

发布时间:2026 年 5 月 18 日

说明类视频 Web 扩展程序 Chrome 状态 目的
GitHub 开发者试用 开发者试用 开发者试用 开发者试用 查看 实验意向

您可以使用 WebMCP 命令式 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" ]
  },
  execute: ({ timeframe }) => {
    // Add your API or database logic here to fetch and return the order data as a string.
  },
});

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 并有反馈意见,欢迎随时告诉我们。