Remarque
L’accès à cette page nécessite une autorisation. Vous pouvez essayer de vous connecter ou de modifier des répertoires.
L’accès à cette page nécessite une autorisation. Vous pouvez essayer de modifier des répertoires.
Un widget HTML généré par MCP est une interface interactive qu’un serveur MCP fournit avec un résultat d’outil. Votre agent Teams lit le code HTML du widget, l’envoie dans un message Markdown étendu et transfère les appels d’outil initiés par l’utilisateur au serveur MCP d’origine. Les utilisateurs peuvent interagir avec les résultats de l’outil directement dans la conversation.
Utilisez cette procédure pas à pas lorsqu’un serveur MCP fournit le widget plutôt que votre agent possède le code HTML. Pour créer votre propre widget, y compris sa poignée de main, son dimensionnement et son gestionnaire d’outil côté agent, consultez Envoyer un widget HTML à partir d’un agent.
Configuration requise
- Un agent du SDK TypeScript Teams fonctionnel disponible sur un point de terminaison HTTPS public.
- Client MCP connecté à un serveur qui fournit des outils d’application MCP et des ressources de widget, à partir
Clientde@modelcontextprotocol/sdk. -
L’assistant Markdown du widget et l’itinéraire d’appel d’outil à partir de la procédure pas à pas du widget appartenant à l’agent. L’itinéraire combiné ci-dessous est réutilisé pour les
handleWidgetToolappels qui ne proviennent pas de widgets MCP.
Widgets des serveurs MCP
Certains serveurs MCP renvoient un widget avec le résultat d’un outil : ces outils sont des outils d’application MCP. Votre agent peut afficher ces widgets dans Teams de la même manière que ses propres widgets. Il envoie chaque widget dans un message Markdown étendu et transfère les appels d’outil du widget au serveur MCP qui l’a fourni.
Cette section part du principe que votre agent appelle déjà des outils sur les serveurs MCP avec un Client à partir du MCP TypeScript SDK (@modelcontextprotocol/sdk). Il utilise l’ID de corrélation de Facultatif : identifiez le widget qui appelle pour acheminer les appels d’outils de chaque widget vers le bon serveur MCP.
Déclarer la prise en charge du widget
Les serveurs MCP renvoient uniquement les widgets aux clients qui les prennent en charge. Déclarez cette prise en charge lorsque vous créez le client 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"],
},
},
},
},
);
Appeler l’outil et créer le widget
Un outil d’application MCP déclare son widget avec un ui:// URI dans le champ de l’outil _meta.ui.resourceUri . Le code HTML du widget est une ressource sur le serveur MCP, que l’agent lit avec readResource. Le serveur peut également déclarer le domaine, la stratégie de sécurité et les autorisations du widget.
Un widget produit par un outil MCP doit inclure le mcpUrl champ dans sa charge utile : l’URL du serveur MCP dont l’outil l’a produit.
Importante
Toujours défini mcpUrl sur les widgets produits par les outils MCP. Teams l’utilise pour exécuter le widget sur un domaine dédié, limité à l’ID de votre agent et à l’URL de ce serveur MCP. Cela isole les widgets des différents serveurs MCP les uns des autres et des propres widgets de votre agent. Sans mcpUrl, un widget MCP s’exécute sur le domaine délimité à l’ID de votre agent uniquement, et peut appeler n’importe quel service qui accepte les appels de ce domaine. Voyez où s’exécutent les widgets.
Créer src/bot/mcp-widgets.tsdes . Ses importations couvrent le code de cette section et dans Forward, l’outil du widget appelle :
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,
},
};
}
Envoyer le widget
Appelez l’outil MCP avec callMcpTool au lieu de client.callTool. Si l’outil a renvoyé un widget, envoyez-le :
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.
Le code HTML d’un widget MCP effectue déjà la négociation et indique sa hauteur. Envoyez-le inchangé. Pour ajouter Markdown autour d’un widget MCP, placez widgetMarkdown(widget) un text tableau, comme illustré dans Mélanger Markdown et widgets.
Testez le widget fourni sur Teams mobile en suivant les instructions de mise à l’échelle réactive. Si des modifications de disposition ou d’interaction sont nécessaires, contactez le propriétaire du serveur MCP.
Remarque
Si le widget fourni inclut des liens profonds Teams, assurez-vous qu’ils répondent aux exigences de la section Liens profonds Teams pris en charge.
Transférer les appels d’outils du widget
Lorsqu’un widget MCP appelle un outil, l’agent transfère l’appel au serveur MCP qui a fourni le widget et renvoie le résultat du serveur au widget.
Ajoutez le code suivant à 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,
},
};
}
Ensuite, mettez à jour l’itinéraire de l’étape widget.callTool6, afin qu’il envoie des appels d’outils à partir de widgets MCP vers 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 suit les mêmes règles que n’importe quel gestionnaire d’outils à l’étape 6 et ajoute les exigences suivantes :
- Transférez uniquement les appels des widgets que vous avez envoyés. Un appel est transféré uniquement si son ID de corrélation est connu et appartient à la même conversation.
- Transférer uniquement les outils que les widgets peuvent appeler. Outil qui
_meta.ui.visibilityest["model"]réservé au modèle. - Supprimez
__msteams__des arguments. Il est destiné à votre agent, pas au serveur MCP. - Retourner le résultat du serveur. Définissez
structuredContentetisErrormême si le serveur les a omis, et supprimez lesresource_linkéléments de contenu, ce que Teams ne prend pas en charge.