HTML ウィジェットを送信する

HTML ウィジェットは、ボットやエージェントが Teams メッセージで送信できるリッチ コンテンツの一種です。 ウィジェットは、 MCP Apps 標準の上に構築されます。 このガイドでは、 Teams SDK を使用して TypeScript で記述された Teams エージェントがどのように次のことを行うかを示します。

  1. 対話型の HTML ウィジェットをチャットに送信します。
  2. Teams に常にすべてのコンテンツが表示されるように、ウィジェットのサイズを正しく設定します。
  3. ウィジェットがエージェントに送り返すcallToolリクエストを処理します。

前提条件

  • Teams SDK を使用して構築された動作する TypeScript エージェント。
  • エージェントのパブリック HTTPS エンドポイント。

注:

HTML ウィジェットは プレビュー 機能です。 Teams SDK は、関連する API を試験的としてマークし、変更される可能性があります。

例: サイコロ ローラー

このガイドのすべての手順で、同じ小さなウィジェットを作成します。

  • エージェントは、[ 6 面サイコロを振る ] ボタンを含むウィジェットを送信します。
  • ユーザーがボタンを選択すると、ウィジェットはエージェントにサイコロを振るように依頼します。 エージェントは番号を選択して返します。
  • ウィジェットは、各結果をリストに追加します。 ウィジェットはロールするたびに大きくなるため、この例ではウィジェットのサイズ変更の方法も示します。

エージェントが送信すると、ウィジェットは次のようになります。

チャット メッセージのサイコロ ウィジェット: [6 面サイコロを振る] ボタン。

3 回ロールした後、ウィジェットは結果のリストに収まるように成長しました。

3 回抽がった後のサイコロ ウィジェットに、

あなたが書く内容

ウィジェットは、Teams がチャットのサンドボックス化された iframe 内にレンダリングする HTML ドキュメントです。 2 つのコードを記述します。

ピース 説明 責任
ウィジェット インライン CSS とプレーン JavaScript を含む 1 つの HTML ファイル。 フレームワークがありません。 Teams でハンドシェイクを実行し、その高さを報告し、ツールを呼び出します。
Agent 既存の Teams SDK エージェントの TypeScript コード。 拡張 Markdown メッセージでウィジェットを送信し、そのツール呼び出しに応答します。

プロジェクト レイアウト

widgets/
  dice-widget.html     # The widget: HTML, CSS, and JavaScript in one file
src/
  agent/
    widget-markdown.ts # Puts a widget in a fenced code block, for extended markdown messages
    dice-widget.ts     # Builds the dice widget's payload from dice-widget.html
    dice-tool.ts       # Handles tool calls from the widget
    correlation.ts     # Optional: identifies which widget made a tool call
    mcp-widgets.ts     # Optional: shows widgets from MCP servers

手順 1: ウィジェット ファイルを作成する

widgets/dice-widget.htmlを作成します。 これは Teams に表示される完全なページです。 最後の <script> 要素は今のところ空です。手順 3、4、5 で入力します。

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Dice roller</title>
    <style>
      /* No margins outside the root element, so that the root's height is
         the widget's full height (Step 4). */
      html,
      body {
        margin: 0;
      }

      /* "flow-root" keeps the margins of the root's first and last children
         inside the root, where they are measured (Step 4). */
      #widget-root {
        display: flow-root;
        font-family: system-ui, sans-serif;
      }
    </style>
  </head>
  <body>
    <!-- All visible content goes inside this element. The widget measures
         it to report its height (Step 4). -->
    <div id="widget-root"></div>

    <script>
      // The code from Steps 3, 4, and 5 goes here, in that order.
    </script>
  </body>
</html>

すべてが 1 つのファイルにあり、CSS と JavaScript はインラインで、ウィジェットは他のオリジンから何も読み込みません。 ウィジェットの作成の詳細については、「 Microsoft Teams の HTML ウィジェットの UX ガイドライン」を参照してください。

手順 2: ウィジェットを送信する

ウィジェットは、 拡張マークダウン メッセージ ( textFormat が "extendedmarkdown" のメッセージ アクティビティ) で送信されます。 ウィジェットは、言語html-widgetを含むフェンスされたコード ブロックとしてメッセージのtextに配置されます。 コード ブロックの内容は、JSON としてのウィジェットのペイロードです。

```html-widget
{"type":"widget/mcp-ui","name":"Dice roller","domain":"https://mybot.example.com","html":"<!doctype html>...", ...}
```

Teams では、コード ブロックがウィジェットとして表示されます。 メッセージの text には、コード ブロックの周りの通常の Markdown を含めることもできます ( 「Markdown とウィジェットの混合」を参照)。

ペイロードには次のフィールドがあります。

フィールド 必須 説明
type はい 常に "widget/mcp-ui"。
name はい ウィジェットの表示名。
description 不要 ウィジェットの簡単な説明。
domain はい ウィジェットに関連付けられている HTTPS オリジン。 エージェントの配信元を使用します。
html はい Teams が iframe でレンダリングする完全な HTML ドキュメント。
securityPolicy 不要 HTML が使用する可能性のある配信元。 resourceDomains 外部スクリプト、スタイル、画像、フォントについて説明します。 connectDomains fetch、XHR、および WebSocket 呼び出しをカバーします。 一覧にないものはすべてブロックされます。
mcpUrl 不要 MCP ツールによって生成されたウィジェットにのみ使用され、常にウィジェットに対して設定されます: ツールがウィジェットを生成した MCP サーバーの URL。 Teams では、これを使用して、エージェントの ID と MCP URL を対象とする専用ドメインでウィジェットを実行します。 MCP サーバーからのウィジェットを参照してください。

ウィジェットのペイロードを構築する

src/bot/dice-widget.tsの作成:

import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import type { IHtmlWidgetPayload } from "@microsoft/teams.api";

// The widget file from Step 1, read once when the bot starts. Adjust the
// path to where the file is deployed with your bot.
const DICE_WIDGET_HTML = readFileSync(
  resolve("widgets/dice-widget.html"),
  "utf8",
);

// Creates the payload of the dice widget.
//   botOrigin: your bot's public HTTPS origin, for example
//              https://mybot.example.com. Used as the widget's domain.
export function createDiceWidget(botOrigin: string): IHtmlWidgetPayload {
  return {
    // Always "widget/mcp-ui".
    type: "widget/mcp-ui",
    // Display name of the widget.
    name: "Dice roller",
    description: "Rolls dice on the bot.",
    // Origin associated with the widget. Use the bot's origin.
    domain: botOrigin,
    // The complete widget: HTML, CSS, and JavaScript.
    html: DICE_WIDGET_HTML,
    // Origins that the widget may use. Everything else is blocked. The dice
    // widget is self-contained, so every list is empty.
    securityPolicy: {
      // Targets of fetch, XHR, and WebSocket calls.
      connectDomains: [],
      // Sources of external scripts, styles, images, and fonts.
      resourceDomains: [],
      // Sources of nested iframes.
      frameDomains: [],
      // Allowed <base> URLs.
      baseUriDomains: [],
    },
  };
}

フェンスされたコード ブロックにウィジェットを配置する

src/bot/widget-markdown.tsを作成します。 どのウィジェットでも機能します。

import type { IHtmlWidgetPayload } from "@microsoft/teams.api";

// Returns the "html-widget" fenced code block that displays a widget in an
// extended markdown message.
export function widgetMarkdown(widget: IHtmlWidgetPayload): string {
  return "```html-widget\n" + JSON.stringify(widget) + "\n```";
}

メッセージを送信する

textがウィジェットのフェンスされたコード ブロックである拡張マークダウン メッセージを送信します。

import { createDiceWidget } from "./dice-widget";
import { widgetMarkdown } from "./widget-markdown";

// `send` comes from the context of the activity you are handling.
await send({
  type: "message",
  // Teams displays "html-widget" code blocks as widgets only in extended
  // markdown messages.
  textFormat: "extendedmarkdown",
  text: widgetMarkdown(createDiceWidget("https://mybot.example.com")),
});

重要

@microsoft/teams.apps によってエクスポートされた buildHtmlWidgetMessage ヘルパーまたは buildHtmlWidgetMarkdown ヘルパーは使用しないでください。 これらは独自のハンドシェイクと高さレポート コードをウィジェットの HTML に追加しますが、これはウィジェット独自のコードと競合します (ステップ 3 と 4)。

Markdown とウィジェットを混在させる

拡張 Markdown メッセージには、ウィジェットに関する通常の Markdown を含めることができます。 空白行で結合された Markdown 文字列とウィジェットの配列からメッセージの text を作成します。

import { createDiceWidget } from "./dice-widget";
import { widgetMarkdown } from "./widget-markdown";

await send({
  type: "message",
  textFormat: "extendedmarkdown",
  // Separate markdown and widgets with blank lines.
  text: [
    "**Feeling lucky?** Roll the die below.",
    widgetMarkdown(createDiceWidget("https://mybot.example.com")),
    "_The bot picks every number._",
  ].join("\n\n"),
});

メッセージの text は次のとおりです。

**Feeling lucky?** Roll the die below.

```html-widget
{"type":"widget/mcp-ui","name":"Dice roller", ...}
```

_The bot picks every number._

1 つのメッセージに複数のウィジェットを表示するには、各ウィジェットの配列に widgetMarkdown(...) エントリを追加します。

各メッセージには、完全なウィジェットが含まれています。 既に送信されたメッセージには、送信時に使用された HTML が保持されます。 dice-widget.htmlの変更は、後で送信するメッセージにのみ適用されます。

警告

メッセージを見ることができるすべてのユーザーは、ウィジェットの HTML を読むことができます。 秘密、トークン、またはプライベート データを絶対に入れないでください。

ウィジェットが別の配信元から何かを読み込む場合は、その配信元をセキュリティ ポリシーに一覧表示します。 Teams SDK の @microsoft/teams.apps パッケージによってエクスポートされた validateSecurityPolicy を単体テストで使用して、HTML で使用されているがポリシーで一覧表示されていないオリジンをキャッチします。

import { validateSecurityPolicy } from "@microsoft/teams.apps";
import { createDiceWidget } from "./dice-widget";

const widget = createDiceWidget("https://mybot.example.com");

// Returns one warning for each origin that the HTML references but the
// security policy does not allow.
const warnings = validateSecurityPolicy(
  widget.html,
  widget.securityPolicy ?? {},
);
// Expect: warnings is an empty array.

ウィジェットが実行される場所

Teams は、次の形式の専用ドメイン上のすべてのウィジェットをホストします。

https://<hash>.widget-renderer.usercontent.microsoft

<hash> ウィジェットの取得元によって異なります:

ウィジェット ペイロードで設定する内容 ドメインのスコープ: ハッシュするテキスト
エージェント独自のウィジェット (サイコロ ローラーなど) なし エージェントの ID <bot id>
MCP ツールによって生成されるウィジェット mcpUrl: MCP サーバーの URL (詳細) エージェントの ID と MCP URL <bot id>-<mcp URL>

MCP ツールによって生成されたウィジェットを送信する場合は、ウィジェットのペイロードの mcpUrl フィールドに MCP サーバーの URL を渡します。 Teams はその後、エージェントの ID とその URL からハッシュを生成し、ウィジェットが独自のドメインを取得するようにします。

ウィジェットがサービスのいずれか (たとえば、ウィジェットの connectDomainsにリストされている API など) を呼び出せるようにするには、CORS 設定などでウィジェットのドメインからの呼び出しを受け入れるようにそのサービスを構成します。

ドメインを見つけるには、 ウィジェット ドメイン ツールを使用してハッシュを生成します。 そのボックスに、エージェントの ID または文字列を <bot id>-<mcp URL> の形式で入力します。

警告

MCP ツールによって生成されたウィジェットから mcpUrl を省略すると、ウィジェットはエージェントの ID のみを対象とするドメインで実行されます。 その後、エージェント独自のウィジェット用のサービスを含め、そのドメインからの呼び出しを受け入れる任意のサービスを呼び出すことができます。 MCP ツールによって生成されたウィジェットのペイロードを常に mcpUrl 渡します。

手順 3: ウィジェットを Teams に接続する

Teams がウィジェットから他のものを受け入れる前に、ウィジェットがハンドシェイクを完了する必要があります。

  1. ui/initialize要求を送信します。
  2. 応答を待ちます。
  3. ui/notifications/initialized通知を送信します。

dice-widget.html の <script> 要素に次のコードを追加します。 要求を送信して応答を待機するヘルパーと、ハンドシェイクを実行する connect 関数を定義します。

// How long to wait for a response before giving up, in milliseconds.
const REQUEST_TIMEOUT_MS = 15000;
// Used to give every request a unique id.
let requestCount = 0;
// A promise that completes when the handshake is done. Set by connect().
let connection;

/**
 * Sends a message to Teams.
 * @param {object} message The message, without the "jsonrpc" field.
 * @returns {void}
 */
function postToHost(message) {
  window.parent.postMessage({ jsonrpc: "2.0", ...message }, "*");
}

/**
 * Normalizes an incoming message. Responses can arrive either as objects or
 * as JSON strings.
 * @param {unknown} data The data of a "message" event.
 * @returns {object | undefined} The message, or undefined if it is not an object.
 */
function readMessage(data) {
  if (typeof data === "string") {
    try {
      return JSON.parse(data);
    } catch {
      return undefined;
    }
  }

  return typeof data === "object" && data !== null ? data : undefined;
}

/**
 * Sends a request to Teams and waits for its response.
 * @param {string} method The request's method name.
 * @param {object} params The request's parameters.
 * @returns {Promise<object>} The response's result. Rejects if the response
 *   is an error, or if no response arrives within REQUEST_TIMEOUT_MS.
 */
function sendRequest(method, params) {
  requestCount += 1;
  const id = "request-" + requestCount;

  return new Promise((resolve, reject) => {
    const timer = setTimeout(
      () => finish(new Error(method + " timed out.")),
      REQUEST_TIMEOUT_MS,
    );

    // Settles the promise exactly once and stops listening for responses.
    function finish(error, result) {
      clearTimeout(timer);
      window.removeEventListener("message", onMessage);

      if (error) {
        reject(error);
      } else {
        resolve(result ?? {});
      }
    }

    function onMessage(event) {
      // Only trust messages that come from Teams.
      if (event.source !== window.parent) {
        return;
      }

      const message = readMessage(event.data);

      // Ignore anything that is not the response to this request.
      if (message?.jsonrpc !== "2.0" || message.id !== id) {
        return;
      }

      if (message.error) {
        finish(
          new Error(method + " failed (code " + message.error.code + ")."),
        );
      } else {
        finish(undefined, message.result);
      }
    }

    // Start listening before sending, so the response cannot be missed.
    window.addEventListener("message", onMessage);
    postToHost({ id, method, params });
  });
}

/**
 * Performs the handshake with Teams. Call it once when the widget starts.
 * Calling it again returns the same promise. If the handshake failed, the
 * next call starts a new attempt.
 * @param {string} appName The widget's name, sent to Teams.
 * @returns {Promise<void>} Completes when the handshake is done.
 */
function connect(appName) {
  connection ??= sendRequest("ui/initialize", {
    // The protocol version that this code implements.
    protocolVersion: "2026-01-26",
    appInfo: { name: appName, version: "1.0.0" },
    // This widget declares no optional capabilities.
    appCapabilities: {},
  }).then(
    () => {
      // Tells Teams the widget is ready. Completes the handshake.
      postToHost({ method: "ui/notifications/initialized", params: {} });
    },
    (error) => {
      // Allow a later call to retry.
      connection = undefined;
      throw error;
    },
  );

  return connection;
}

手順 4: ウィジェットの高さを報告する

ウィジェットの高さは、そのコンテンツによって決定される必要があります。

Teams は、ウィジェットが ui/notifications/size-changed 通知で報告する高さにウィジェットの iframe のサイズを設定します。 ウィジェットはハンドシェイク後、および変更されるたびにその高さを報告する必要があります。

<script>要素にreportHeightを追加します。

/**
 * Reports the height of `root` to Teams now, and every time it changes.
 * @param {HTMLElement} root The element that contains all of the widget's content.
 * @returns {() => void} A function that stops reporting.
 */
function reportHeight(root) {
  let lastHeight;

  function report() {
    // The exact rendered height of the root, in CSS pixels. Can be fractional.
    const height = root.getBoundingClientRect().height;

    // Skip duplicates, unless the iframe is still too short to show everything.
    if (height === lastHeight && window.innerHeight >= height) {
      return;
    }

    lastHeight = height;
    // Teams resizes the iframe to this height. Send it unrounded.
    postToHost({
      method: "ui/notifications/size-changed",
      params: { height },
    });
  }

  // Calls report() whenever the root's size changes for any reason: new
  // content, loaded fonts or images, or text that wraps differently.
  const observer = new ResizeObserver(report);

  observer.observe(root);
  // Report the initial height right away.
  report();

  return () => observer.disconnect();
}

iframe はウィジェットからサイズ設定されるため、iframe からウィジェットのサイズを設定することはできません。 ウィジェットの高さをそのコンテンツによって制御し続けるには:

  • すべてのコンテンツを 1 つのルート要素内に配置し、その要素 を getBoundingClientRect().height で測定します。 document.documentElement.scrollHeightやdocument.body.scrollHeightを測定しないでください。 これらの値は iframe より小さくなることはありません。そのため、ウィジェットは拡大できますが、縮小することはありません。
  • 正確な高さを報告します。 丸めないでください。 上に切り上げるとウィジェットの下にストリップが残り、切り捨てるとクリップされます。
  • iframe に合わせてウィジェットのサイズを変更しないでください。 html、body、またはルート要素で 100vh または height: 100% を使用しないでください。
  • 通常のページ フローで、すべてのコンテンツをルート内に保持します。 負の余白または position: fixed でルートの外側に配置されたコンテンツは測定されないため、クリップすることができます。
  • 根元の周りの余白を削除します。 手順 1 のスタイルは、最初と最後の子の余白が測定されるように、 html, body { margin: 0; }を設定し、ルートに display: flow-root を与えます。

サイコロ ウィジェットの高さは、その内容 (ボタン、抽選のリスト、エラー メッセージ) によって決まります。

手順 5: ウィジェットからツールを呼び出す

ウィジェットは、 name と arguments オブジェクトを使用してツールを呼び出すことで、エージェントに何かを行うように要求します。 ウィジェットを含むメッセージを送信したエージェントが 、手順 6 で呼び出しを処理します。

callTool 関数

<script>要素にcallToolを追加します。

/**
 * Calls a tool on the bot and returns the bot's result.
 * @param {string} name The tool name that the bot's handler recognizes.
 * @param {object} args The tool's arguments. The bot receives them as
 *   activity.value.arguments.
 * @returns {Promise<{content?: Array<{type: string, text?: string}>,
 *   structuredContent?: object, isError?: boolean}>} The bot's result.
 *   Rejects if the call could not be completed. Resolves with isError: true
 *   if the bot ran the tool and reported a failure.
 */
async function callTool(name, args) {
  // Tool calls are only allowed after the handshake.
  if (!connection) {
    throw new Error("Call connect() before calling tools.");
  }

  await connection;

  return sendRequest("tools/call", { name, arguments: args });
}

結果は、手順 6 でエージェントが返す callToolResult オブジェクトです。

フィールド 説明
content コンテンツ項目の配列。 人間が判読できるメッセージには { type: "text", text } を使用します。
structuredContent ウィジェットがレンダリングするデータを持つオブジェクト。
isError true ツールに失敗したとき。 content のテキストでその理由が説明されています。

両方の種類のエラーを処理します。

  • 呼び出しを完了できなかった場合 (タイムアウトまたはエージェントのハンドラーが失敗した場合)、promise は拒否されます。
  • promise は isError: true で解決しますエージェントがツールを実行し、エラーを報告したとき。

サイコロ ウィジェット

最後に、 <script> 要素の最後にウィジェット独自のコードを追加します。 UI を構築し、Teams に接続し、高さを報告し、ボタンが選択されたときに roll_dice を呼び出します。

// Number of sides on the die.
const SIDES = 6;
const root = document.getElementById("widget-root");

// Build the UI: a button, a list of results, and a place for errors.
const button = document.createElement("button");
const rolls = document.createElement("ul");
const errorMessage = document.createElement("p");

button.type = "button";
button.textContent = "Roll a " + SIDES + "-sided die";
// Screen readers announce errors as soon as they appear.
errorMessage.setAttribute("role", "alert");
root.append(button, rolls, errorMessage);

button.addEventListener("click", async () => {
  // Prevent a second roll while this one is in progress.
  button.disabled = true;
  errorMessage.textContent = "";

  try {
    // Ask the bot to roll. The bot handles "roll_dice" in Step 6.
    const result = await callTool("roll_dice", { sides: SIDES });
    // The bot's human-readable message, if any.
    const text = result.content?.find((item) => item.type === "text")?.text;

    // The bot ran the tool but reported a failure.
    if (result.isError) {
      throw new Error(text ?? "The dice could not be rolled.");
    }

    // Show the rolled value that the bot returned in structuredContent.
    // textContent (not innerHTML) keeps the value from being parsed as HTML.
    const roll = document.createElement("li");

    roll.textContent = "You rolled " + result.structuredContent?.value + ".";
    rolls.append(roll);
  } catch (error) {
    // The call failed or the bot reported an error.
    errorMessage.textContent =
      error instanceof Error ? error.message : String(error);
  } finally {
    button.disabled = false;
  }
});

// Complete the handshake, then start reporting the widget's height. Every
// later change to the root's content is reported automatically.
connect("Dice roller").then(
  () => reportHeight(root),
  () => {
    errorMessage.textContent = "This widget could not connect to Teams.";
  },
);
  • 通話中はこのボタンは無効になるため、すばやくダブルクリックしても 2 回はロールされません。
  • 新しいロールと各エラー メッセージによってルートが背が高くなります。 手順 4 の ResizeObserver は、新しい高さを報告します。

手順 6: エージェントでツール呼び出しを処理する

ウィジェットがツールを呼び出すと、エージェントは htmlwidget/calltool 呼び出しアクティビティを受信します。 Teams SDK では、 widget.callTool ルートを使用して処理します。

  • activity.value.name はツール名です。
  • activity.value.arguments は、 unknown として型指定された引数オブジェクトです。

ハンドラーは IHtmlWidgetCallToolResponseを返します。

{
  // Always "htmlwidget/calltoolresult".
  responseType: "htmlwidget/calltoolresult",
  // Returned to the widget as the result of callTool().
  callToolResult: { content, structuredContent, isError },
}

src/bot/dice-tool.tsの作成:

import { randomInt } from "node:crypto";
import type {
  IHtmlWidgetCallToolInvokeActivity,
  IHtmlWidgetCallToolResponse,
} from "@microsoft/teams.api";

// Builds a tool call response. Always sets all three result fields, because
// fields you omit can reach the widget as null.
//   text:              human-readable message, shown by the widget on errors.
//   structuredContent: data for the widget to render.
//   isError:           true when the tool failed.
function toolResult(
  text: string,
  structuredContent: Record<string, unknown> = {},
  isError = false,
): IHtmlWidgetCallToolResponse {
  return {
    responseType: "htmlwidget/calltoolresult",
    callToolResult: {
      content: [{ type: "text", text }],
      structuredContent,
      isError,
    },
  };
}

// The "roll_dice" tool. Expects arguments of the form { sides: number }.
function rollDice(args: unknown): IHtmlWidgetCallToolResponse {
  // `args` comes from the browser: check its shape before using it. Other
  // properties (such as Teams' reserved __msteams__) are ignored.
  const sides =
    typeof args === "object" && args !== null && "sides" in args
      ? args.sides
      : undefined;

  // Reject invalid input with an error result instead of throwing.
  if (
    typeof sides !== "number" ||
    !Number.isInteger(sides) ||
    sides < 2 ||
    sides > 100
  ) {
    return toolResult("sides must be a whole number from 2 to 100.", {}, true);
  }

  // A random whole number from 1 to `sides`, inclusive.
  const value = randomInt(1, sides + 1);

  // The widget reads `value` from structuredContent.
  return toolResult("You rolled " + value + ".", { value, sides });
}

// Entry point for every tool call from the widget. Dispatches by tool name.
export function handleWidgetTool(
  activity: IHtmlWidgetCallToolInvokeActivity,
): IHtmlWidgetCallToolResponse {
  // The name and arguments that the widget passed to callTool().
  const { name, arguments: args } = activity.value;

  switch (name) {
    case "roll_dice":
      return rollDice(args);
    default:
      // Unknown tools also get an error result, never an exception.
      return toolResult("Unknown tool: " + name, {}, true);
  }
}

エージェントの Appにルートを登録します。

import type { IHtmlWidgetCallToolResponse } from "@microsoft/teams.api";
import { handleWidgetTool } from "./dice-tool";

// Receives every tool call from widgets that this bot sent.
// `app` is your bot's App.
app.on(
  "widget.callTool",
  async ({ activity }): Promise<IHtmlWidgetCallToolResponse> => {
    try {
      // The return value is sent back to the widget.
      return handleWidgetTool(activity);
    } catch (error) {
      // Safety net for unexpected failures: log the details on the bot, and
      // return an error result rather than letting the invoke fail.
      console.error("Widget tool failed.", error);

      return {
        responseType: "htmlwidget/calltoolresult",
        callToolResult: {
          content: [{ type: "text", text: "Something went wrong." }],
          structuredContent: {},
          isError: true,
        },
      };
    }
  },
);

すべてのツール ハンドラーで次の規則に従います。

  1. 常に結果を返します。 ハンドラーにスローさせないでください。 content でisError: trueと読み取り可能なメッセージを使用してエラーを報告します。 ハンドラーがスローされた場合、呼び出しは失敗し、ウィジェットは一般的なエラーのみを受け取ります。
  2. content、structuredContent (データがないときは {} を使用)、isErrorの 3 つのフィールドを常にすべて設定します。 省略したフィールドは、 nullとしてウィジェットに到達する可能性がありますが、 MCP Apps SDK でビルドされたウィジェットは拒否します。
  3. argumentsを検証します。 それらはブラウザーから送られてきます。 HTTP 要求の本文と同様に、信頼されていない入力として扱ってください。
  4. 認識しないプロパティを無視します。 Teams は予約済み __msteams__ プロパティを arguments に追加できるため、予期しないプロパティを拒否しないでください。
  5. activity.fromに基づいて承認しない。 呼び出しは会話を識別しますが、ユーザーの Microsoft Entra ID を確実に保持することはできません。 ツールに検証済みのユーザーが必要な場合、ウィジェットはエージェントが検証するトークンを送信する必要がありますが、これはこのガイドの範囲外です。
  6. 迅速に対応します。 ユーザーはウィジェットで結果を待っています。

省略可能: どのウィジェットが呼び出しているかを特定する

ウィジェット ペイロードに最上位の correlationId 文字列を追加すると、Teams はそのウィジェットからのすべてのツール呼び出しで arguments.__msteams__.correlationId に渡します。 これを使用して、その特定のウィジェットに属するサーバー側の状態を見つけます。 たとえば、ランダムな UUID を生成し、データと共に格納し、ツールが呼び出されたときにそれを検索することができます。

src/bot/correlation.tsの作成:

import type {
  IHtmlWidgetCallToolInvokeActivity,
  IHtmlWidgetPayload,
} from "@microsoft/teams.api";

// Use this type for payloads that include a correlationId. The field is not
// part of the published IHtmlWidgetPayload type yet.
type HtmlWidgetPayloadWithCorrelation = IHtmlWidgetPayload & {
  correlationId: string;
};

// Returns the correlationId of the widget that made this tool call, or
// undefined if the widget's payload had none.
export function correlationIdOf(
  activity: IHtmlWidgetCallToolInvokeActivity,
): string | undefined {
  const args = activity.value.arguments;

  // Teams adds the ID under the reserved __msteams__ property of the arguments.
  if (typeof args !== "object" || args === null || !("__msteams__" in args)) {
    return undefined;
  }

  const metadata = args.__msteams__;

  // Accept the value only if it is a string.
  return typeof metadata === "object" &&
    metadata !== null &&
    "correlationId" in metadata &&
    typeof metadata.correlationId === "string"
    ? metadata.correlationId
    : undefined;
}

関連付け ID はウィジェットを識別します。 ユーザーが誰であるかを証明するものではありません。 ID を使用する前に、ID がストアに存在し、 activity.conversation.id の会話に属していることを確認してください。

ウィジェットで使用できるその他の API

MCP Apps 標準では、ウィジェットが周囲のチャットと対話するために使用できる追加の要求を定義しています。

要求 それを使用して 使用前に確認する
ui/open-link ウィジェットの外側 (ブラウザー タブなど) で URL を開きます。 hostCapabilities.openLinks
ui/message ユーザーの代わりにチャットにメッセージを投稿します。 hostCapabilities.message
ui/update-model-context 後のターンのために、ウィジェットの状態をモデルに静かに伝えます。 hostCapabilities.updateModelContext
ui/request-display-mode インライン、全画面表示、またはピクチャインピクチャで表示するように依頼します。 hostContext.availableDisplayModes

tools/call と同様に、4 つすべてが要求です。 ハンドシェイク後に送信し、返信を待ちます。 以下の例は大まかなものです。ウィジェットに適応させます。

Teams では、これらの要求はすべてサポートされています。 それでも、ウィジェットは、使用する前にホストが機能をサポートしていることを常にチェックし、サポートしていない場合は適切にフォールバックすることをお勧めします。 ui/initialize要求に対するホストの応答は、サポートする内容を示します。

  • hostCapabilitiesホストがサポートするオプションの要求ごとに 1 つのプロパティがあります。ui/open-link の場合は openLinks、ui/message の場合は message、ui/update-model-context の場合は updateModelContext です。 プロパティが見つからない場合は、要求を送信しないでください。
  • hostContext.availableDisplayModes ホストが ui/request-display-mode でサポートする表示モードを一覧表示します。 hostContext.displayMode はウィジェットの現在のモードです。

ハンドシェイクが完了したら、両方のオブジェクトを保持します。 この例および以下の例では、 sendRequest(method, params) は postMessage を使用して JSON-RPC 要求を Teams に送信し、応答の resultに対する Promise を返します。

// Set when the handshake completes. The examples below use them.
let hostCapabilities = {};
let hostContext = {};

const result = await sendRequest("ui/initialize", {
  protocolVersion: "2026-01-26",
  appInfo: { name: "My widget", version: "1.0.0" },
  // The display modes that the widget supports, if it uses more than inline.
  appCapabilities: { availableDisplayModes: ["inline", "fullscreen"] },
});

hostCapabilities = result.hostCapabilities ?? {};
hostContext = result.hostContext ?? {};
// Then send ui/notifications/initialized to complete the handshake.

if (hostCapabilities.openLinks) {
  // The host accepts ui/open-link requests from this widget.
}

tools/callと同様に、これらの要求は 2 つの方法で失敗する可能性があります。 両方を処理する:

  • Promise は、 Teams がエラー (たとえば、要求が拒否された、またはサポートされていないなど) を返すか、時間内に応答しない場合に拒否されます。
  • promise は isError: true で解決しますTeams が要求を受け入れたが完了できなかったとき。 ui/open-link ui/messageこの方法でエラーを報告できます。

ウィジェットはサンドボックス化された iframe で実行されるため、通常のリンク、 target="_blank"、および window.open をブロックできます。 ページを開くには、次の例に示すようにページを開くように Teams に依頼します。

/**
 * Asks Teams to open a URL outside the widget, for example in a browser tab.
 * @param {string} url An absolute URL.
 * @returns {Promise<void>} Rejects if Teams can't or won't open the URL.
 */
async function openLink(url) {
  if (!hostCapabilities.openLinks) {
    throw new Error("Teams can't open links from this widget.");
  }

  const result = await sendRequest("ui/open-link", { url });

  if (result.isError) {
    throw new Error("The link could not be opened.");
  }
}

// For example, open the widget's links through Teams.
link.addEventListener("click", (event) => {
  event.preventDefault();
  openLink(link.href).catch(() => {
    // Fall back, for example by showing the URL so that the user can copy it.
  });
});
  • リンクやボタンの選択など、ユーザーのアクションに応答してのみリンクを開きます。
  • 絶対 https:// URL を使用します。 Teams は、他の URL を拒否したり、開く前にユーザーに確認を求めたりすることができます。
  • securityPolicy では、URL の配信元を記載する必要はありません。 Teams はウィジェットの外側でページを開きます。 securityPolicy は、ウィジェット自体が読み込んで呼び出す内容のみを制御します。

HTML ウィジェットは、次の Teams ディープ リンクのみをサポートします。

リンクの種類 サポートされる URL パターン
チャット https://teams.microsoft.com/l/chat/...
メッセージ https://teams.microsoft.com/l/message/...
会議に参加する https://teams.microsoft.com/l/meetup-join/...
会議 ID で会議に参加する https://teams.microsoft.com/meet/...

これらのディープ リンクは、次の要件をすべて満たす必要があります。

  • HTTPS を使用します。
  • ウィジェットと同じクラウド環境をポイントし、ウィジェット自身のアカウントで開きます。
  • URL フラグメント (#) を含まない。
  • fqdn も homeCloud クエリ パラメーターも含めません。

Teams のディープ リンクは、ウィジェットに関連付けられているアカウントを使用して開きます。

注:

Teams はサポートされていない Teams のディープ リンクを無視し、 ui/open-link 要求はエラーを返します。 これらの制限は、通常の Web リンクには適用されません。

Teams のディープ リンクの詳細については、「 アプリへのディープ リンクを調べて構成する」を参照してください。

チャットにメッセージを投稿します。 ui/message

ui/message ユーザーがメッセージを送信したかのように会話にメッセージを追加し、エージェントはそれに応答します。 ウィジェット内の選択で会話を続ける必要がある場合 (例: [このフライトを予約 ] ボタンや [この詳細情報] ボタンなど) に使用します。

パラメーターは次のとおりです。

  • role、常に "user"されます。
  • contentこれは、MCP コンテンツ ブロックの配列です。

hostCapabilities.message に他の種類 (image など) が一覧表示されていない限り、テキスト ブロックを使用します。

/**
 * Posts a message to the chat on the user's behalf. The agent responds to it.
 * @param {string} text The message's text.
 * @returns {Promise<void>} Rejects if Teams doesn't post the message.
 */
async function sendMessage(text) {
  if (!hostCapabilities.message) {
    throw new Error("Teams can't post messages from this widget.");
  }

  const result = await sendRequest("ui/message", {
    role: "user",
    content: [{ type: "text", text }],
  });

  if (result.isError) {
    throw new Error("The message could not be posted.");
  }
}

// For example, when the user selects a flight in the widget:
bookButton.addEventListener("click", () =>
  sendMessage("Book flight " + flight.number + " on " + flight.date + "."),
);
  • 明示的なユーザーの操作に応答する場合にのみメッセージを送信する。 メッセージは、ユーザーのメッセージとしてチャットに表示されるため、そのテキストはユーザーが明確に要求したものである必要があります。
  • エージェントとユーザーのテキストを記述します。 これは通常のチャット メッセージです。短く読みやすくし、シークレットを含めないでください。
  • Teams は、投稿前にユーザーにメッセージの承認を求めることができます。

エージェントのコンテキストを更新します。 ui/update-model-context

ui/update-model-context メッセージを投稿したり、新しいターンを開始し たりせずに 、ウィジェットで何が起こっているかをエージェントに伝えます。 エージェントがユーザーの次の質問に答える必要がある状態に使用します。 たとえば、ユーザーが選択したアイテム、適用されたフィルター、フォーム内の値などがあります。

パラメーターは、コンテンツ ブロックの配列である content と、機械可読データを持つオブジェクトである structuredContent です。 どちらも省略可能です。 応答が空のオブジェクトです。

/**
 * Replaces the widget's context for the agent. Teams sends it to the
 * agent, which decides how to use it.
 * @param {string} text A short description of the widget's current state.
 * @param {object} [structuredContent] The same state, as data.
 * @returns {Promise<void>}
 */
async function updateModelContext(text, structuredContent) {
  // Context updates are optional: skip them if Teams doesn't accept them.
  if (!hostCapabilities.updateModelContext) {
    return;
  }

  await sendRequest("ui/update-model-context", {
    content: [{ type: "text", text }],
    structuredContent,
  });
}

// For example, when the user selects a laptop configuration:
updateModelContext(
  "The user is viewing the Contoso 14 laptop, in silver, with 16 GB of memory.",
  { productId: "contoso-14", color: "silver", memoryGb: 16 },
);
  • 毎回、完全な現在の状態を送信します。 各更新プログラムは、前の更新プログラムに置き換えられます。それには追加されません。
  • 小さな変更ごとに更新を送信しないようにします。 Teams は各更新プログラムをエージェントに送信します。 入力のデバウンスなどによって、変更が完了するまで待機します。
  • contentには必ずテキストの説明を含めます。 hostCapabilities.updateModelContext が structuredContent を一覧表示しない限り、モデルはstructuredContentを受け取らない場合があります。
  • コンテキストを目に見えるものとして扱います。 モデルがそれを読み取ると、Teams はそれをユーザーに表示できます。 シークレットを含めません。

何かが異なる動作をすることをエージェントに伝える 2 つの方法:

動作 ui/message ui/update-model-context
チャットに表示されます はい。ユーザーからのメッセージとして 不要
エージェントに応答させる はい、すぐに完了します その必要はありません。 エージェントがその使用方法を決定します。
繰り返しの呼び出し 通話ごとに新しいメッセージが投稿されます 各呼び出しで前のコンテキストが置き換えられます

エージェントでコンテキストの更新を処理する

Teams では、ウィジェットのエージェントは各 ui/update-model-context 要求を受け取ります。 アダプティブ カードからのAction.Submitと同様に、valueに要求が含まれるメッセージ アクティビティとして到着します。

{
  "method": "ui/update-model-context",
  "params": {
    "content": [{ "type": "text", "text": "The user is viewing the Contoso 14 laptop..." }],
    "structuredContent": { "productId": "contoso-14", "color": "silver", "memoryGb": 16 }
  }
}

任意の方法で更新を処理するのは エージェントの責任 です。 Teams は、コンテキストを会話に追加したり、モデルに渡したりしません。 たとえば、エージェントは会話の最新のコンテキストを保存し、次のターンにモデルのプロンプトに含めるか、無視することができます。

Teams SDK では、@microsoft/teams.apps からのtryGetWidgetModelContextを使用してmessageハンドラーの開始時に更新プログラムをチェックします。 アクティビティがコンテキスト更新ではない場合は、要求または undefined を返します。

import { tryGetWidgetModelContext } from "@microsoft/teams.apps";

// The latest widget context for each conversation. Use your own storage.
const widgetContexts = new Map<string, unknown>();

app.on("message", async ({ activity }) => {
  const update = tryGetWidgetModelContext(activity);

  if (update) {
    // A context update from a widget, not a message from the user. Each
    // update replaces the previous one. Don't reply: a reply would appear in the chat.
    widgetContexts.set(activity.conversation.id, update.params);
    return;
  }

  // Your normal message handling. For example, add the stored widget context
  // to the model's prompt.
});
  • 通常のメッセージ処理の前に更新を処理して、ユーザーからのメッセージとして扱われないようにします。
  • コンテキストを信頼できない入力として扱う。 ブラウザーから来ます。 それを検証し、モデルに渡されるテキストがモデルの命令を変更しようとする可能性があることに注意してください。
  • 更新プログラムに返信しない。 ウィジェットはエージェントを待機しません: Teams はウィジェット自体の要求に応答します。

表示モードを変更します。 ui/request-display-mode

ウィジェットは、次の 3 つのモードのいずれかで表示できます。

モード 説明 Teams でサポートされています
inline 既定: ウィジェットがチャット メッセージに表示されます。 はい
fullscreen ウィジェットは、Teams メイン ウィンドウ内の大きなモーダル ダイアログに表示されます。 はい
pip ピクチャインピクチャ: ウィジェットが会話の上に浮かびます。 不要

Teams は pip をサポートしていません。 Teams では、Teams のメイン ウィンドウ内に表示される大きなモーダル ダイアログ fullscreen にウィジェットが表示されます。

inline 以外のモードを使用するには:

  1. ui/initialize リクエストのappCapabilities.availableDisplayModesで、ウィジェットがサポートするすべてのモード (inlineを含む) を宣言します。 Teams は、宣言されているモードのみにウィジェットを切り替えます。
  2. 要求する前に、Teams がhostContext.availableDisplayModesでモードをサポートしていることを確認します。
  3. 応答でモードを使用します。 応答の mode は、ウィジェットが実際にあるモードであり、要求したモードとは異なる場合があります。
  4. ui/notifications/host-context-changedを聞きます。 Teams は、ユーザーが fullscreen を終了するときなど、要求なしにモードを変更できます。
/**
 * Asks Teams to show the widget in another display mode.
 * @param {"inline" | "fullscreen" | "pip"} mode The requested mode.
 * @returns {Promise<string>} The mode that the widget is in afterward.
 */
async function requestDisplayMode(mode) {
  // Don't request a mode that Teams doesn't support.
  if (!hostContext.availableDisplayModes?.includes(mode)) {
    return hostContext.displayMode ?? "inline";
  }

  const result = await sendRequest("ui/request-display-mode", { mode });

  return result.mode;
}

// Teams sends changes to the host context, such as a new display mode.
window.addEventListener("message", (event) => {
  const message = event.data;

  if (
    event.source !== window.parent ||
    message?.method !== "ui/notifications/host-context-changed"
  ) {
    return;
  }

  // An update contains only the fields that changed: merge it.
  hostContext = { ...hostContext, ...message.params };
  // Let CSS adapt the layout, with selectors like [data-display-mode="fullscreen"].
  document.body.dataset.displayMode = hostContext.displayMode ?? "inline";
});

// For example, an "Expand" button.
expandButton.addEventListener("click", async () => {
  const mode = await requestDisplayMode("fullscreen");

  document.body.dataset.displayMode = mode;
});

ウィジェットの高さのレポートは 、ウィジェットの高さがそのコンテンツによって決まる inline モードにのみ適用されます。 fullscreen モードでは、Teams はウィジェットの高さを設定します。 ウィジェットをコンテンツに合わせてサイズ変更する代わりに、その高さ (たとえば、ルート要素に height: 100vh がある) を塗りつぶし、ウィジェットが inline モードに戻ったときにコンテンツ ドリブン サイズに戻します。

すべてをまとめる

既存のエージェントには、次の 2 つの追加が必要です。

  1. ウィジェットを含む拡張 Markdown メッセージの send 呼び出し (ステップ 2)。
  2. widget.callToolルート (ステップ 6)。

widgets/dice-widget.html の <script> 要素には、手順 3、手順 4、手順 5 のコードが順番に含まれます。

MCP サーバーからのウィジェットを表示するには、MCP クライアントでウィジェットのサポートを宣言し、 callMcpTool で MCP ツールを呼び出し、MCP ウィジェットから handleMcpWidgetTool (MCP サーバーからのウィジェット) にツール呼び出しを送信します。

試すには:

  1. エージェントを実行して、Teams チャットでウィジェットを送信するようにします。
  2. [ 6 面ダイを数回振 る] を選択します。 各ロールがリストに表示され、ウィジェットはスクロール バーなしでそれに合わせて拡大されます。
  3. iOS と Android の Teams でウィジェットを縦向きと横向きの両方でテストします。 プライマリ コンテンツがクリップされておらず、ホバーに頼らずにタッチでアクションが使用できることを確認します。 レス ポンシブスケーリングを参照してください。

注:

現在、HTML ウィジェット コンテンツはエクスポート API を使用してエクスポートできません。 コンテンツ エクスポート要件がある組織向けのボットを開発する場合は、この制限事項を考慮してください。 この制限が要件を満たしていない場合、組織は HTML ウィジェットを送信できるボットを無効にできます。

チェックリスト

ウィジェットを送信する

  • [ ] ウィジェットは、インラインCSSとJavaScriptを含む1つのHTMLファイルです。
  • [ ] ウィジェットは、ペイロードを含むhtml-widgetフェンスされたコード ブロックとして拡張 Markdown メッセージ (textFormat: "extendedmarkdown") で送信されます。 メッセージは buildHtmlWidgetMessage または buildHtmlWidgetMarkdown を使って構築されません。
  • [ ] HTML が読み込むオリジンは resourceDomains 内にあり、呼び出すオリジンは connectDomains 内です。
  • [ ] HTML にはシークレットは含まれていません。
  • [ ] ウィジェットが呼び出すサービスは、ウィジェットのドメイン https://<hash>.widget-renderer.usercontent.microsoft からの呼び出しを受け入れます。

ハンドシェイクとサイズ

  • [ ] ハンドシェイク (ui/initialize、次に ui/notifications/initialized) が最初に完了します。
  • [ ] ウィジェットの高さはそのコンテンツによって決まります: ウィジェットは 1 つのルート要素を getBoundingClientRect().height で測定し、scrollHeightことはなく、iframe に収まるようにサイズ設定されていません (100vh、または html、body、またはルートのheight: 100%)。
  • [ ] 高さは、 ResizeObserverから丸めずに正確に報告されます。
  • [ ] html と body には余白がなく、ルートは display: flow-root を使用し、通常のページ フローではすべてのコンテンツがルート内にとどまります。

ツールの呼び出し

  • [ ] ウィジェットは、ユーザーのアクションに応答してツールを呼び出します。
  • [ ] ウィジェットは、拒否された callTool Promise と isError: true の結果の両方を処理します。
  • [ ] エージェントのハンドラーは常に content、 structuredContent、 isError を返し、スローしません。
  • [ ] エージェントは argumentsを検証し、 __msteams__などの不明なプロパティを無視し、 activity.fromに基づいて承認しません。

その他の API

  • [ ] ui/open-link、 ui/message、 ui/update-model-context、および ui/request-display-mode は、ハンドシェイク後にのみ送信され、Teams が ui/initialize への応答でサポートを宣言した場合にのみ送信されます。
  • [ ] ui/open-link と ui/message は、ユーザーのアクションへの応答としてのみ送信され、ウィジェットは失敗した場合にフォールバックを持ちます。
  • [ ] 各 ui/update-model-context リクエストには、ウィジェットの完全な現在の状態と、 contentのテキスト説明が含まれています。
  • [ ] ウィジェットが使用するすべての表示モードは appCapabilities.availableDisplayModes で宣言され、ウィジェットは応答と ui/notifications/host-context-changedでそのモードを使用します。

MCP サーバーからのウィジェット

  • [ ] MCP クライアントは io.modelcontextprotocol/ui 拡張機能を宣言します。
  • [ ] 各 MCP ウィジェットのペイロードには、ツールがそれを生成した MCP サーバーの URL である mcpUrl が含まれているため、ウィジェットはエージェントの ID とその URL を対象とする専用ドメインで実行されます。
  • [ ] 各 MCP ウィジェットには一意の correlationId があり、MCP サーバーおよび会話とともに格納されます。
  • [ ] ツール呼び出しは、同じ会話内の既知のウィジェットに対してのみ転送され、ウィジェットが呼び出す可能性のあるツールに対してのみ転送されます。
  • [ ] __msteams__ は、転送される前に引数から削除されます。

リファレンス: メッセージ

コード メッセージ Kind ペイロード 返信
ウィジェット ui/initialize 要求 { protocolVersion, appInfo: { name, version }, appCapabilities } 現在のテーマなど、 hostContextを含めることができるオブジェクト
ウィジェット ui/notifications/initialized Notification {} なし
ウィジェット ui/notifications/size-changed Notification { height } (CSS ピクセル単位) なし
ウィジェット tools/call 要求 { name, arguments } エージェントの callToolResult
ウィジェット ui/open-link 要求 { url } {}URL が開けなかったかどうか{ isError: true }
ウィジェット ui/message 要求 { role: "user", content }ここで、 content はブロックの配列です {}または、メッセージが投稿されなかった場合は{ isError: true }
ウィジェット ui/update-model-context 要求 { content?, structuredContent? } {}
ウィジェット ui/request-display-mode 要求 { mode }: "inline"、 "fullscreen"、または "pip" { mode }: ウィジェットの実際の表示モード
Teams ui/notifications/host-context-changed Notification 変更された hostContext フィールド (以下 displayMode なし
agent message アクティビティ (tryGetWidgetModelContext) ハンドラー activity.value: ui/update-model-context 要求 なし
agent widget.callTool ルート (htmlwidget/calltool) ハンドラー activity.value: { name, arguments } { responseType: "htmlwidget/calltoolresult", callToolResult }

要求は応答を待機します。 通知はそうではありません。

次の手順