命令型 API

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

公開日: 2026 年 5 月 18 日、最終更新日: 2026 年 9 月 1 日

商品の解説 ウェブ 拡張機能 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 の場合、ツールを実行すると、重大な、現実世界の、または元に戻せないアクション(フライトの予約、送金、データの削除など)が発生することを示します。これにより、エージェントとブラウザは、リスクの高いツールを実行する前にユーザー確認のプロンプトを強制的に表示し、ユーザーの意図が誤って、または悪意を持って誤って伝えられるリスクを軽減できます。
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 関数は、ユーザーまたはエージェントによって開始された実行のキャンセルを適切に処理するために、2 番目の引数として 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, 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 Page Agent のデモをご覧ください。

ツールを実行する

getTools() で検出されたツールを手動で実行するには、有効な JSON 文字列として入力引数を指定して document.modelContext.executeTool() を呼び出します。この非同期メソッドは、ツールの実行結果を返します。ナビゲーションがトリガーされた場合は null を返します。

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.modelContexttoolchange イベントをリッスンして、使用可能なツールのリストが変更されたときに通知を受け取ることができます。

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 では、usewebmcp パッケージを使用して WebMCP の試験運用サポートが提供されています。アプリケーションがすでに React で記述されている場合は、コンポーネントのマウントとアンマウントのライフサイクルに関連付けられたスタンドアロン フックを使用してツールを登録できます。useWebMCP フックは、スキーマ駆動型の型推論も提供し、ローカル実行状態を公開します。

Angular のサポート

Angular には WebMCP の試験運用版でのサポートがあります。アプリケーションが Angular で記述されている場合は、アプリケーションの依存性注入ライフサイクルに関連付けられたツールを登録し、Signal フォームを WebMCP ツールに変換できます。

意見交換とフィードバックの提供

WebMCP は現在活発な議論の対象となっており、今後変更される可能性があります。この API をお試しになり、フィードバックがございましたら、ぜひお聞かせください。