MCP 生成の HTML ウィジェットを提供する

MCP で生成された HTML ウィジェットは、MCP サーバーがツールの結果とともに提供する対話型インターフェイスです。 Teams エージェントは、ウィジェットの HTML を読み取り、拡張 Markdown メッセージで送信し、ユーザーが開始したツール呼び出しを元の MCP サーバーに転送します。 ユーザーは、会話の中でツールの結果を直接操作できます。

このチュートリアルは、HTML を所有しているエージェントではなく MCP サーバーがウィジェットを提供する場合に使用します。 ハンドシェイク、サイズ設定、エージェント側ツールハンドラーを含む独自のウィジェットを構築するには、「 エージェントからHTMLウィジェットを送信する」を参照してください。

前提条件

  • パブリック HTTPS エンドポイントで利用可能な動作している TypeScript Teams SDK エージェント。
  • @modelcontextprotocol/sdkからClientを使用して、MCP App ツールとウィジェット リソースを提供するサーバーに接続されている MCP クライアント。
  • エージェント所有のウィジェット チュートリアルからのウィ ジェット マークダウン ヘルパー と ツール呼び出し ルート。 以下の組み合わせルートでは、MCP ウィジェットからではない呼び出しの handleWidgetTool が再利用されます。

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

一部の MCP サーバーは、ツールの結果と共にウィジェットを返します。これらのツールは MCP アプリ ツールです。 エージェントは、自分のウィジェットと同じ方法でこれらのウィジェットを Teams に表示できます。 各ウィジェットを拡張 Markdown メッセージで送信し、ウィジェットのツール呼び出しをそれを提供した MCP サーバーに転送します。

このセクションでは、エージェントが既に MCP TypeScript SDK (@modelcontextprotocol/sdk) のClientを使用して MCP サーバー上のツールを呼び出していることを前提としています。 Optional: どのウィジェットが呼び出しているかを識別して、各ウィジェットのツール呼び出しを適切な MCP サーバーにルーティングする関連付け ID を使用します。

ウィジェットのサポートの宣言

MCP サーバーは、それらをサポートするクライアントにのみウィジェットを返します。 MCP クライアントを作成するときに、そのサポートを宣言します。

import { Client } from "@modelcontextprotocol/sdk/client/index.js";

const client = new Client(
  { name: "My agent", version: "1.0.0" },
  {
    capabilities: {
      // Tells MCP servers that this client can display MCP App widgets.
      extensions: {
        "io.modelcontextprotocol/ui": {
          mimeTypes: ["text/html;profile=mcp-app"],
        },
      },
    },
  },
);

ツールを呼び出してウィジェットを作成する

MCP アプリ ツールは、ツールの _meta.ui.resourceUri フィールドにui:// URI を持つウィジェットを宣言します。 ウィジェットの HTML は MCP サーバー上のリソースであり、エージェントは readResource で読み取ります。 サーバーは、ウィジェットのドメイン、セキュリティ ポリシー、および権限を宣言することもできます。

MCP ツールによって生成されるウィジェットは、そのペイロードに mcpUrl フィールド (それを生成したツールの MCP サーバーの URL) を含める必要があります。

重要

MCP ツールによって生成されたウィジェットに常に mcpUrl を設定します。 Teams では、これを使用して専用ドメインでウィジェットを実行し、エージェントの ID とその MCP サーバーの URL を対象とします。 これにより、異なる MCP サーバーからのウィジェットは、相互に分離され、エージェント独自のウィジェットから分離されます。 mcpUrlない場合、MCP ウィジェットはエージェントの ID のみを対象とするドメインで実行され、そのドメインからの呼び出しを受け入れる任意のサービスを呼び出すことができます。 ウィ ジェットが実行される場所を参照してください。

src/bot/mcp-widgets.tsを作成します。 そのインポートには、このセクションのコードと、 ウィジェットのツール呼び出しの転送のコードが含まれます。

import { randomUUID } from "node:crypto";
import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
import {
  CallToolResultSchema,
  type CallToolResult,
  type Tool,
} from "@modelcontextprotocol/sdk/types.js";
import type {
  IHtmlWidgetCallToolInvokeActivity,
  IHtmlWidgetCallToolResponse,
  IHtmlWidgetPayload,
  IHtmlWidgetPermissions,
  IHtmlWidgetSecurityPolicy,
} from "@microsoft/teams.api";
import { correlationIdOf } from "./correlation";

// The MIME type of MCP App widgets.
const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app";

// A widget payload from an MCP tool. The correlationId and mcpUrl fields are
// not part of the published IHtmlWidgetPayload type yet.
export type McpWidgetPayload = IHtmlWidgetPayload & {
  correlationId: string;
  mcpUrl: string;
};

// Settings that an MCP server can declare for a widget, in the _meta.ui field
// of the widget's resource.
interface McpWidgetSettings {
  domain?: string;
  csp?: IHtmlWidgetSecurityPolicy;
  permissions?: IHtmlWidgetPermissions;
}

// Where tool calls from an MCP widget go.
interface McpWidgetRoute {
  // The client connected to the MCP server that provided the widget.
  client: Client;
  // The conversation that the widget was sent to.
  conversationId: string;
}

// The routes of the MCP widgets that this bot sent, by correlationId. In
// production, keep them in persistent storage: widgets in older messages can
// still call tools after your bot restarts.
const routes = new Map<string, McpWidgetRoute>();

// Returns the _meta.ui object of an MCP tool or resource, or undefined.
function uiMetadata(
  meta: Record<string, unknown> | undefined,
): object | undefined {
  const ui = meta?.ui;

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

// Returns the ui:// URI of a tool's widget, or undefined if the tool has none.
function widgetUri(tool: Tool): string | undefined {
  const ui = uiMetadata(tool._meta);

  return ui && "resourceUri" in ui && typeof ui.resourceUri === "string"
    ? ui.resourceUri
    : undefined;
}

// Calls an MCP tool and, if the tool has a widget, creates the widget's
// payload.
//   client:         client connected to the MCP server that provides the tool.
//   serverUrl:      URL of that MCP server, the one the client connected to.
//                   Sent as the widget's mcpUrl. Its origin is the widget's
//                   domain if the server doesn't declare one.
//   conversationId: the conversation the widget will be sent to.
//   tool:           the tool, as returned by client.listTools().
//   args:           the tool's arguments.
// Returns the tool's result, and the widget's payload if the tool has a widget.
export async function callMcpTool(
  client: Client,
  serverUrl: string,
  conversationId: string,
  tool: Tool,
  args: Record<string, unknown>,
): Promise<{ result: CallToolResult; widget?: McpWidgetPayload }> {
  const result = CallToolResultSchema.parse(
    await client.callTool({ name: tool.name, arguments: args }),
  );
  const uri = widgetUri(tool);

  // No widget for tools without one, or when the tool failed.
  if (!uri || result.isError) {
    return { result };
  }

  // Read the widget's HTML and settings from the MCP server.
  const resource = await client.readResource({ uri });
  const content = resource.contents.find((item) => item.uri === uri);

  if (!content || content.mimeType !== MCP_APP_MIME_TYPE) {
    throw new Error("The MCP server did not return the tool's widget.");
  }

  // The HTML is either text, or base64-encoded binary data.
  const html =
    "text" in content
      ? content.text
      : Buffer.from(content.blob, "base64").toString("utf8");
  const settings: McpWidgetSettings = uiMetadata(content._meta) ?? {};

  // Remember where this widget's tool calls must go.
  const correlationId = randomUUID();

  routes.set(correlationId, { client, conversationId });

  return {
    result,
    widget: {
      type: "widget/mcp-ui",
      name: tool.title ?? tool.name,
      description: tool.description,
      domain: settings.domain ?? new URL(serverUrl).origin,
      html,
      securityPolicy: settings.csp,
      permissions: settings.permissions,
      // The tool's arguments and result. Teams passes them to the widget,
      // which typically renders the result.
      toolInput: args,
      toolOutput: result,
      // Teams passes this back with every tool call from the widget.
      correlationId,
      // The URL of the MCP server whose tool produced the widget. Teams runs
      // the widget on a dedicated domain scoped to the bot's ID and this URL.
      mcpUrl: serverUrl,
    },
  };
}

ウィジェットを送信する

client.callTool ではなく callMcpTool を使用して MCP ツールを呼び出します。 ツールによってウィジェットが返された場合は、次のように送信します。

import { callMcpTool } from "./mcp-widgets";
import { widgetMarkdown } from "./widget-markdown";

// `client` is your MCP client, `tool` comes from client.listTools(), and
// `args` are the tool's arguments, for example chosen by your model.
const { result, widget } = await callMcpTool(
  client,
  "https://mcp.example.com/mcp",
  activity.conversation.id,
  tool,
  args,
);

if (widget) {
  await send({
    type: "message",
    textFormat: "extendedmarkdown",
    text: widgetMarkdown(widget),
  });
}

// Use `result` as you would for any MCP tool, for example by passing it back
// to your model.

MCP ウィジェットの HTML は既にハンドシェイクを実行しており、その高さを報告しています。 変更せずに送信します。 MCP ウィジェットの周囲に Markdown を追加するには、「Mix Markdown とウィジェット」に示すように、widgetMarkdown(widget) を text 配列に配置します。

レス ポンシブ スケーリング ガイダンスに従って、提供されたウィジェットを Teams モバイルでテストします。 レイアウトまたは操作の変更が必要な場合は、MCP サーバーの所有者に問い合わせてください。

注:

提供されたウィジェットに Teams のディープ リンクが含まれている場合は、 サポートされている Teams のディープ リンクの要件を満たしていることを確認してください。

ウィジェットのツール呼び出しを転送する

MCP ウィジェットがツールを呼び出すと、エージェントはウィジェットを提供した MCP サーバーに呼び出しを転送し、サーバーの結果をウィジェットに返します。

src/bot/mcp-widgets.ts に次のコードを追加します。

// Returns true if widgets may call this tool. MCP servers can restrict a tool
// to the model by setting its _meta.ui.visibility field to ["model"].
function isAvailableToWidgets(tool: Tool): boolean {
  const ui = uiMetadata(tool._meta);
  const visibility =
    ui && "visibility" in ui && Array.isArray(ui.visibility)
      ? ui.visibility
      : ["model", "app"];

  return visibility.includes("app");
}

// Builds a tool call response that reports an error to the widget.
function errorResult(text: string): IHtmlWidgetCallToolResponse {
  return {
    responseType: "htmlwidget/calltoolresult",
    callToolResult: {
      content: [{ type: "text", text }],
      structuredContent: {},
      isError: true,
    },
  };
}

// Forwards a tool call from an MCP widget to the MCP server that provided the
// widget, and returns the server's result to the widget.
// Returns undefined if the call does not come from an MCP widget.
export async function handleMcpWidgetTool(
  activity: IHtmlWidgetCallToolInvokeActivity,
): Promise<IHtmlWidgetCallToolResponse | undefined> {
  const correlationId = correlationIdOf(activity);

  // Only MCP widgets have a correlationId in this bot.
  if (!correlationId) {
    return undefined;
  }

  const route = routes.get(correlationId);

  // The widget must have been sent by this bot, to this conversation.
  if (!route || route.conversationId !== activity.conversation.id) {
    return errorResult("This widget is no longer available.");
  }

  // The tool must exist, and widgets must be allowed to call it. (If the
  // server has many tools, follow nextCursor to list all of them.)
  const { tools } = await route.client.listTools();
  const tool = tools.find((entry) => entry.name === activity.value.name);

  if (!tool || !isAvailableToWidgets(tool)) {
    return errorResult("Unknown tool: " + activity.value.name);
  }

  // Remove Teams' reserved __msteams__ property before forwarding the
  // arguments to the MCP server.
  const { __msteams__, ...args } = activity.value.arguments as Record<
    string,
    unknown
  >;
  const result = CallToolResultSchema.parse(
    await route.client.callTool({ name: tool.name, arguments: args }),
  );

  return {
    responseType: "htmlwidget/calltoolresult",
    callToolResult: {
      // Teams does not support resource_link items, so they are removed.
      content: result.content.filter((item) => item.type !== "resource_link"),
      // Always set these fields: fields you omit can reach the widget as null.
      structuredContent: result.structuredContent ?? {},
      isError: result.isError ?? false,
    },
  };
}

次に、手順 6 の widget.callTool ルートを更新して、MCP ウィジェットから handleMcpWidgetTool にツール呼び出しを送信するようにします。

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

app.on(
  "widget.callTool",
  async ({ activity }): Promise<IHtmlWidgetCallToolResponse> => {
    try {
      // Tool calls from MCP widgets go to their MCP server. All other tool
      // calls are handled by the bot itself.
      return (
        (await handleMcpWidgetTool(activity)) ?? handleWidgetTool(activity)
      );
    } catch (error) {
      // Safety net for unexpected failures, including MCP server errors.
      console.error("Widget tool failed.", error);

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

handleMcpWidgetTool 手順 6 のツール ハンドラーと同じ規則に従い、次の要件を追加します。

  • 送信したウィジェットからの通話のみを転送します。 通話は、関連付け ID が既知であり、同じ会話に属している場合にのみ転送されます。
  • ウィジェットが呼び出すことができるツールのみを転送します。 _meta.ui.visibilityが["model"]のツールは、モデル用に予約されています。
  • 引数から __msteams__ を削除します。 これは、MCP サーバーではなく、エージェントを対象としています。
  • サーバーの結果を返します。 サーバーが省略した場合でも structuredContent と isError を設定し、Teams がサポートしていない resource_link コンテンツ アイテムを削除します。

関連項目