Fornecer widgets HTML gerados por MCP

Um widget HTML gerado por MCP é uma interface interativa que um servidor MCP fornece junto com um resultado de ferramenta. Seu agente do Teams lê o HTML do widget, envia-o em uma mensagem Markdown estendida e encaminha chamadas de ferramenta iniciadas pelo usuário para o servidor MCP de origem. Os usuários podem interagir com os resultados da ferramenta diretamente na conversa.

Use este passo a passo quando um servidor MCP fornecer o widget em vez de seu agente possuir o HTML. Para criar seu próprio widget, incluindo seu handshake, dimensionamento e manipulador de ferramentas do lado do agente, consulte Enviar um widget HTML de um agente.

Pré-requisitos

  • Um agente do SDK do Teams TypeScript disponível em um ponto de extremidade HTTPS público.
  • Um cliente MCP conectado a um servidor que fornece ferramentas de aplicativo MCP e recursos de widget, usando Client de .@modelcontextprotocol/sdk
  • O widget Markdown helper e a rota de chamada de ferramenta do passo a passo do widget de propriedade do agente. A rota combinada abaixo reutiliza handleWidgetTool chamadas que não são de widgets MCP.

Widgets dos servidores MCP

Alguns servidores MCP retornam um widget junto com o resultado de uma ferramenta: essas ferramentas são ferramentas de aplicativo MCP. Seu agente pode mostrar esses widgets no Teams da mesma maneira que seus próprios widgets. Ele envia cada widget em uma mensagem Markdown estendida e encaminha as chamadas de ferramenta do widget para o servidor MCP que o forneceu.

Esta seção pressupõe que seu agente já chama ferramentas em servidores MCP com um Client do SDK TypeScript MCP (@modelcontextprotocol/sdk). Ele usa a ID de correlação de Opcional: identifique qual widget está chamando para rotear as chamadas de ferramenta de cada widget para o servidor MCP correto.

Declarar suporte a widgets

Os servidores MCP retornam widgets apenas para clientes que dão suporte a eles. Declare esse suporte ao criar o cliente 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"],
        },
      },
    },
  },
);

Chamar a ferramenta e criar o widget

Uma ferramenta de aplicativo MCP declara seu widget com um ui:// URI no campo da _meta.ui.resourceUri ferramenta. O HTML do widget é um recurso no servidor MCP, que o agente lê com readResource. O servidor também pode declarar o domínio, a política de segurança e as permissões do widget.

Um widget produzido por uma ferramenta MCP deve incluir o mcpUrl campo em seu conteúdo: a URL do servidor MCP cuja ferramenta o produziu.

Importante

Sempre defina mcpUrl os widgets produzidos pelas ferramentas MCP. O Teams o usa para executar o widget em um domínio dedicado, com escopo para a ID do seu agente e para a URL do servidor MCP. Isso mantém os widgets de diferentes servidores MCP isolados uns dos outros e dos próprios widgets do seu agente. Sem mcpUrl, um widget MCP é executado no domínio com escopo apenas para a ID do agente e pode chamar qualquer serviço que aceite chamadas desse domínio. Consulte Onde os widgets são executados.

Criar src/bot/mcp-widgets.ts. Suas importações cobrem o código nesta seção e, em Forward, a ferramenta do widget chama:

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,
    },
  };
}

Enviar o widget

Chame a ferramenta MCP com callMcpTool em vez de client.callTool. Se a ferramenta retornou um widget, envie-o:

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.

O HTML de um widget MCP já executa o handshake e relata sua altura. Enviá-lo inalterado. Para adicionar Markdown em torno de um widget MCP, coloque widgetMarkdown(widget) uma text matriz, conforme mostrado em Misturar markdown e widgets.

Teste o widget fornecido no Teams móvel seguindo as diretrizes de dimensionamento responsivo. Se forem necessárias alterações de layout ou interação, trabalhe com o proprietário do servidor MCP.

Observação

Se o widget fornecido incluir links profundos do Teams, verifique se eles atendem aos requisitos em Links diretos compatíveis do Teams.

Encaminhar as chamadas de ferramenta do widget

Quando um widget MCP chama uma ferramenta, o agente encaminha a chamada para o servidor MCP que forneceu o widget e retorna o resultado do servidor para o widget.

Adicione o seguinte código a 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,
    },
  };
}

Em seguida, atualize a widget.callTool rota da Etapa 6, para que ela envie chamadas de ferramenta de widgets MCP para 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 segue as mesmas regras que qualquer manipulador de ferramentas na Etapa 6 e adiciona estes requisitos:

  • Encaminhe apenas chamadas de widgets que você enviou. Uma chamada é encaminhada somente se sua ID de correlação for conhecida e pertencer à mesma conversa.
  • Somente encaminhar ferramentas que os widgets possam chamar. Uma ferramenta cuja _meta.ui.visibility área ["model"] é reservada para o modelo.
  • Remova __msteams__ dos argumentos. Ele se destina ao seu agente, não ao servidor MCP.
  • Retorne o resultado do servidor. Defina structuredContent e isError mesmo que o servidor os tenha omitido e remova resource_link itens de conteúdo, aos quais o Teams não dá suporte.

Confira também