Servir widgets HTML generados por MCP

Un widget HTML generado por MCP es una interfaz interactiva que proporciona un servidor MCP junto con un resultado de la herramienta. El agente de Teams lee el código HTML del widget, lo envía en un mensaje de Markdown extendido y reenvía las llamadas de herramienta iniciadas por el usuario al servidor MCP de origen. Los usuarios pueden interactuar con los resultados de la herramienta directamente en la conversación.

Use este tutorial cuando un servidor MCP proporcione el widget en lugar de que su agente sea el propietario del HTML. Para crear su propio widget, incluido su protocolo de enlace, tamaño y controlador de herramientas del lado del agente, consulte Enviar un widget HTML desde un agente.

Requisitos previos

  • Un agente del SDK de Teams de TypeScript en funcionamiento disponible en un punto de conexión HTTPS público.
  • Un cliente MCP conectado a un servidor que proporciona herramientas de la aplicación MCP y recursos de widgets, mediante Client desde @modelcontextprotocol/sdk.
  • El asistente Markdown del widget y la ruta de llamada a la herramienta del tutorial del widget propiedad del agente. La siguiente ruta combinada se reutiliza handleWidgetTool para las llamadas que no provienen de widgets de MCP.

Widgets de servidores MCP

Algunos servidores MCP devuelven un widget junto con el resultado de una herramienta: estas herramientas son herramientas de la aplicación MCP. El agente puede mostrar esos widgets en Teams de la misma manera que sus propios widgets. Envía cada widget en un mensaje extendido de Markdown y reenvía las llamadas a la herramienta del widget al servidor MCP que lo proporcionó.

En esta sección se supone que el agente ya llama a herramientas en los servidores MCP con un Client del SDK de MCP TypeScript (@modelcontextprotocol/sdk). Utiliza el ID de correlación de Opcional: identifique qué widget está llamando para enrutar las llamadas a herramientas de cada widget al servidor MCP correcto.

Declarar compatibilidad con widgets

Los servidores MCP solo devuelven widgets a los clientes que los admiten. Declare ese soporte al crear el 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"],
        },
      },
    },
  },
);

Llame a la herramienta y cree el widget

Una herramienta de la aplicación MCP declara su widget con un ui:// URI en el campo de _meta.ui.resourceUri la herramienta. El HTML del widget es un recurso en el servidor MCP, que el agente lee con readResource. El servidor también puede declarar el dominio, la directiva de seguridad y los permisos del widget.

Un widget producido por una herramienta MCP debe incluir el mcpUrl campo en su carga útil: la URL del servidor MCP cuya herramienta lo produjo.

Importante

Establecer mcpUrl siempre los widgets producidos por las herramientas de MCP. Teams lo usa para ejecutar el widget en un dominio dedicado, con ámbito al identificador del agente y a la dirección URL de ese servidor MCP. Esto mantiene los widgets de diferentes servidores MCP aislados entre sí y de los propios widgets del agente. Sin mcpUrl, un widget de MCP se ejecuta en el dominio con el ámbito del ID del agente únicamente y puede llamar a cualquier servicio que acepte llamadas de ese dominio. Vea dónde se ejecutan los widgets.

Crear src/bot/mcp-widgets.ts Sus importaciones cubren el código en esta sección y en Reenviar la herramienta del widget llama:

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 el widget

Llame a la herramienta MCP con callMcpTool en lugar de client.callTool. Si la herramienta devolvió un widget, envíelo:

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.

El HTML de un widget MCP ya realiza el protocolo de enlace e informa de su altura. Enviarlo sin cambios. Para agregar Markdown alrededor de un widget MCP, coloque widgetMarkdown(widget) una text matriz, como se muestra en Mix markdown y widgets.

Pruebe el widget suministrado en Teams para dispositivos móviles siguiendo la guía de escalado dinámico. Si se necesitan cambios en el diseño o en la interacción, trabaje con el propietario del servidor MCP.

Nota:

Si el widget suministrado incluye vínculos profundos de Teams, asegúrese de que cumplen los requisitos de los vínculos profundos de Teams admitidos.

Reenviar las llamadas de herramientas del widget

Cuando un widget de MCP llama a una herramienta, el agente reenvía la llamada al servidor MCP que proporcionó el widget y devuelve el resultado del servidor al widget.

Agregue el siguiente 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,
    },
  };
}

A continuación, actualice la widget.callTool ruta del paso 6, para que envíe llamadas de herramienta desde los widgets de MCP a 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 sigue las mismas reglas que cualquier controlador de herramientas en el paso 6 y agrega estos requisitos:

  • Solo reenvíe las llamadas de los widgets que envió. Una llamada se reenvía solo si se conoce el identificador de correlación y pertenece a la misma conversación.
  • Solo las herramientas de reenvío a las que pueden llamar los widgets. Una herramienta que _meta.ui.visibility["model"] está reservada para el modelo.
  • Quitar __msteams__ de los argumentos. Está diseñado para el agente, no para el servidor MCP.
  • Devolver el resultado del servidor. Establezca structuredContent e isError incluso si el servidor los omitió, y quite resource_link los elementos de contenido, que Teams no admite.

Vea también