提供 MCP 生成的 HTML 小组件

MCP 生成的 HTML 小组件是 MCP 服务器与工具结果一起提供的交互式界面。 Teams 代理读取小组件的 HTML,在扩展的 Markdown 消息中发送它,并将用户启动的工具调用转发到原始 MCP 服务器。 用户可以直接在对话中与该工具的结果进行交互。

当 MCP 服务器提供小组件而不是拥有 HTML 的代理时,请使用本演练。 要构建自己的小组件,包括其握手、大小调整和机器人端工具处理程序,请参阅 从代理发送 HTML 小组件。

先决条件

  • 公共 HTTPS 终结点上可用的工作 TypeScript Teams SDK 机器人。
  • 连接到提供 MCP 应用程序工具和小组件资源的服务器的 MCP 客户端,使用 Client from @modelcontextprotocol/sdk.
  • 来自代理拥有的小组件演练的小 组件 Markdown 帮助程序 和 工具调用路由 。 下面的组合路由重用 handleWidgetTool 了非来自 MCP 小组件的调用。

来自 MCP 服务器的小组件

某些 MCP 服务器会返回小组件以及工具的结果:这些工具是 MCP 应用工具。 机器人可以在 Teams 中显示这些小组件,其方式与其自身的小组件相同。 它会在扩展的 Markdown 消息中发送每个小组件,并将小组件的工具调用转发到提供它的 MCP 服务器。

本部分假定机器人已使用 MCP TypeScript SDK (@modelcontextprotocol/sdk) 中的 MCP Client 服务器调用工具。 它使用可选中的相关 ID :确定哪个小组件正在调用 ,以将每个小组件的工具调用路由到正确的 MCP 服务器。

声明小组件支持

MCP 服务器仅将小组件返回给支持它们的客户端。 在创建 MCP 客户端时声明该支持:

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

const client = new Client(
  { name: "My bot", 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中使用 URI 声明其小组件ui://。 小组件的 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,
    },
  };
}

发送小组件

使用 callMcpTool 而不是 client.callTool调用 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,请放入 widgetMarkdown(widget) 数 text 组中,如 “混合 markdown 和小组件”中所示。

按照 响应式缩放指南,在 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,
    },
  };
}

然后更新widget.callTool步骤 6 中的路由,以便它将工具调用从 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 服务器省略了它们,并删除 resource_link Teams 不支持的内容项。

另请参阅