Skip to main content

Part 10: Teams Dialogs

Part 5's cards and Part 9's Universal Actions live in the chat, next to everything else in it. Some tasks need more room and more focus: a form with several fields, a check before anything is sent, a choice in two steps. For those, Microsoft Teams opens a dialog, a window over the chat with its own Adaptive Card, and your agent decides what it shows from the moment it opens to the moment it closes.

This is Part 10 of the Microsoft 365 Agents SDK Fundamentals, a 27-part series.

  1. Part 1: Activities and the Activity Protocol
  2. Part 2: Route Activities with AgentApplication
  3. Part 3: Turn Events, Error Handling and Middleware
  4. Part 4: Conversation, User and Turn State
  5. Part 5: Send Adaptive Cards and Handle Their Actions
  6. Part 6: Send Proactive Messages
  7. Part 7: Stream Responses and Show Progress
  8. Part 8: Run Your Agent in Microsoft Teams
  9. Part 9: Universal Actions: Adaptive Cards That Update
  10. Part 10: Teams Dialogs (you are here)
  11. Part 11: Show a Web Page in a Teams Dialog (coming soon)
  12. Part 12: Commands, Suggested Actions and Targeted Messages (coming soon)
  13. Part 13: Mentions, Rosters and Team Events (coming soon)
  14. Part 14: Meeting Events (coming soon)
  15. Part 15: Send and Receive Files (coming soon)
  16. Part 16: Sign People In with SSO and OAuth (coming soon)
  17. Part 17: Message Extensions and Link Unfurling (coming soon)
  18. Part 18: AI Labels, Citations and Feedback (coming soon)
  19. Part 19: Bring Your Agent to Microsoft 365 Copilot (coming soon)
  20. Part 20: Store State in Azure Blob Storage and Cosmos DB (coming soon)
  21. Part 21: Telemetry with OpenTelemetry (coming soon)
  22. Part 22: Web Chat and Direct Line (coming soon)
  23. Part 23: Reach People in Slack (coming soon)
  24. Part 24: Call a Copilot Studio Agent (coming soon)
  25. Part 25: Agent-to-Agent Communication (coming soon)
  26. Part 26: Keep Conversation Transcripts (coming soon)
  27. Part 27: Deploy Your Agent to Azure (coming soon)

By the end of this part you'll know what a Teams dialog is, the two requests Teams sends your agent while one is open, and the three answers your agent can give. You'll build an office-supplies agent whose dialog asks what you need, checks the request, shows it back to you, and sends it, keeping what you typed whenever it has to ask again.

What a Teams Dialog Is​

A dialog is a modal window: it opens over the chat, and the person works in it until they finish or close it. Microsoft's Designing dialogs guide puts it in one line: Use this capability to display rich media and information or complete a complex task. Older documentation and the SDK call dialogs task modules, which is why the code says TaskModules.

A dialog shows one of two things:

  • An Adaptive Card, built by your agent. That's this part.
  • A web page of your own, loaded inside the dialog. It's a different tool, with a page you host and Microsoft's Teams JavaScript library, so it gets its own part, Part 11.

From an agent, a dialog opens when someone selects a card button made for it. Message extensions open dialogs too, which Part 17 shows.

What the Agent Gets and What It Sends Back​

While a dialog is open, Teams and your agent talk in invoke activities: requests that wait for the agent's answer, as Part 9's Action.Execute did. There are two:

InvokeWhen Teams sends itWhat it carries in value.data
task/fetchSomeone selects a card button with "msteams": { "type": "task/fetch" } in its dataThe button's data
task/submitSomeone selects an Action.Submit button in the dialogThe button's data, plus every input's value, by id

Your agent answers each one, and the answer decides what the dialog does next:

AnswerWhat Teams does
continue, with a title, a size and a cardOpens the dialog with that card, or puts the card in place of the one showing
message, with a textShows the text in the dialog, in place of the card
nothing: an empty answerCloses the dialog

Microsoft's Use dialogs with bots lists the same three answers to a submit: No response, a message in a pop-up message box in the dialog, and another card, which allows you to chain sequences of Adaptive Cards together in a wizard or multi-step experience.

Here's one dialog from start to end:

Closing a dialog with its X doesn't reach the agent at all: it's between the person and Teams.

Dialogs in the Agents SDK​

The Microsoft 365 Agents SDK keeps everything that works only in Teams, dialogs included, in its Teams extension, the Microsoft.Agents.Extensions.MSTeams package. Mark your agent class [TeamsExtension] and partial, and it gets a TeamsExtension property with the routes:

C#
TeamsExtension.TaskModules.OnFetch("<dialog name>", fetchHandler);
TeamsExtension.TaskModules.OnSubmit("<button name>", submitHandler);

Both match the value of a "task" key in the button's data, the default the SDK's reference recommends: it is strongly recommended to keep the default "task" for both fetch and submit — varying only the value. Both kinds of handler get the request as a TaskModuleRequest and return a TaskModuleResponse. The SDK sends the answer back to Teams for you.

The Example: Supply Desk​

The agent for this part is Supply Desk, in a one-to-one chat. Its card has a Request supplies button that opens a dialog:

In the dialogWhat the agent does
The form: Item, How many? and a note, with Review and CancelOpens it, empty, for task/fetch
ReviewChecks the request against its limits. A problem: the same form, with the problem in red and the values kept. Otherwise: a review step
The review step, with Send request and BackBack: the form again, filled in. Send request: checks once more, posts the request in the chat, and answers with a message
CancelGives no answer, so the dialog closes

In this page, Leo Martin uses Supply Desk in a developer tenant. You'll write the code first, in steps, then run it in Teams:

StepYou addWhat you'll see
1–2The project and the Teams extensionIt builds
3–5The request, the cards and the dialog answers
6The dialog routes
7–8A tunnel, a bot and an app package, then run itSupply Desk in Teams, with its card
9–13Nothing: use the dialogEach answer, from the form to the closed dialog

Prerequisites​

  • Part 9, Universal Actions: Adaptive Cards That Update. This part reuses the setup Part 8 built and Part 9 repeated: a dev tunnel, a Teams-managed bot, the agent's identity, token validation, a tenant filter and an app package.
  • The Teams developer CLI, signed in, to register the bot in one command. teams status shows whether you're signed in.

Cost: nothing in this part needs an Azure subscription, as in Part 8.

Step 1: Create the Project​

Create the project as in Part 9, with one more package: the Teams extension.

Terminal 1
dotnet new web -o SupplyDesk
cd SupplyDesk
dotnet add package Microsoft.Agents.Hosting.AspNetCore --version 1.9.205
dotnet add package Microsoft.Agents.Authentication.Msal --version 1.9.205
dotnet add package Microsoft.Agents.Extensions.MSTeams --version 1.9.205
dotnet user-secrets init
Output (first and last lines)
The template "ASP.NET Core Empty" was created successfully.
...
info : PackageReference for package 'Microsoft.Agents.Hosting.AspNetCore' version '1.9.205' added to file '/Users/you/source/SupplyDesk/SupplyDesk.csproj'.
...
info : PackageReference for package 'Microsoft.Agents.Authentication.Msal' version '1.9.205' added to file '/Users/you/source/SupplyDesk/SupplyDesk.csproj'.
...
info : PackageReference for package 'Microsoft.Agents.Extensions.MSTeams' version '1.9.205' added to file '/Users/you/source/SupplyDesk/SupplyDesk.csproj'.
...
Set UserSecretsId to '00000000-0000-0000-0000-000000000000' for MSBuild project '/Users/you/source/SupplyDesk/SupplyDesk.csproj'.

Bring over the same three things as Part 9, changing only the namespace: AspNetExtensions.cs, the token validation code from Part 8, Step 5; TenantFilterMiddleware.cs, from Part 8, Step 10, with namespace SupplyDesk;; and appsettings.json, with "StartTypingTimer": false. Set the two applicationUrl lines in Properties/launchSettings.json to port 3978, and replace Program.cs:

Program.cs
using Microsoft.Agents.Hosting.AspNetCore;
using Microsoft.Agents.Storage;
using SupplyDesk;

var builder = WebApplication.CreateBuilder(args);

string[] allowedTenants = builder.Configuration.GetSection("AllowedTenants").Get<string[]>() ?? [];
if (allowedTenants.Length == 0)
{
throw new InvalidOperationException("Add your Microsoft Entra tenant ID to AllowedTenants in appsettings.json.");
}

builder.AddAgentDefaults()
.AddAgent<SupplyDeskAgent>()
.AddAgentMiddleware(new TenantFilterMiddleware(allowedTenants))
.AddAgentAuthorization(b => b.AddAgentAspNetAuthentication(), forceEnable: true);
builder.Services.AddSingleton<IStorage, MemoryStorage>();

var app = builder.Build();

app.UseAgents();
app.MapDefaultAgentEndpoints();

app.Run();

Part 9's Program.cs, with SupplyDeskAgent, which Step 6 writes, as the agent.

Step 2: Turn On the Teams Extension​

The Teams extension works through a source generator, code that writes code while the project builds. Mark the agent class with [TeamsExtension], and declare it partial, so the generator can write the other part of it:

SupplyDeskAgent.cs (the class line)
[TeamsExtension]
public partial class SupplyDeskAgent : AgentApplication

The generator adds a property named TeamsExtension. The SDK's own documentation for the attribute calls it Teams, which doesn't build: error CS0103: The name 'Teams' does not exist in the current context. Fixed: "The name 'Teams' does not exist in the current context" with [TeamsExtension] in the Microsoft 365 Agents SDK shows how the generated file settled it. How to Add the Teams Extension to an Agent in the Microsoft 365 Agents SDK in C# covers the extension on its own.

Step 3: Describe the Request​

Two small files. SupplyRequest holds what someone asks for, and reads it from a dialog's data:

SupplyRequest.cs
using Microsoft.Agents.Extensions.MSTeams;
using Microsoft.Teams.Apps.TaskModules;

namespace SupplyDesk;

// What someone asks for in the dialog. Teams sends every input's value as text, so Quantity is text too.
public record SupplyRequest(string Item, string Quantity, string Note)
{
// What the form shows when it first opens.
public static readonly SupplyRequest Empty = new("", "1", "");

// Reads a request from the data Teams sends when someone selects a button in the dialog.
public static SupplyRequest FromDialog(TaskModuleRequest request) => new(
request.GetDataString("item"),
request.GetDataString("quantity"),
request.GetDataString("note"));
}
  • All three values are text. Teams sends every input's value as text, the number included, so Quantity is a string until the agent checks it.
  • GetDataString reads one key from the data Teams sent. A missing key gives an empty string.
  • Empty is what the form shows when it first opens: no item, one of it, no note.

SupplyCatalog holds the items and the agent's own rule: how many of each one request can take. Teams knows nothing about this rule, so only the agent can check it:

SupplyCatalog.cs
namespace SupplyDesk;

// The items people can ask for, and the most of each that one request can take.
public static class SupplyCatalog
{
public static readonly Dictionary<string, int> Limits = new()
{
["Notebook"] = 5,
["Pens"] = 10,
["Sticky notes"] = 5,
["Headset"] = 1,
};

// Returns what's wrong with a request, or null when there's nothing wrong.
public static string? FindProblem(SupplyRequest request)
{
if (!Limits.TryGetValue(request.Item, out int limit))
{
return "Pick an item from the list.";
}

if (!int.TryParse(request.Quantity, out int quantity) || quantity < 1)
{
return "Enter how many you need: 1 or more.";
}

if (quantity > limit)
{
return $"{request.Item}: one request can take up to {limit}.";
}

return null;
}
}

FindProblem returns null when the request is fine, and otherwise a sentence that says what to fix.

Step 4: Build the Cards​

Supply Desk has four cards: the one in the chat, the form and the review step inside the dialog, and the record of a sent request. They're built as JsonObjects, the way Part 9 built its cards:

SupplyCards.cs
using System.Text.Json.Nodes;

namespace SupplyDesk;

// Builds Supply Desk's Adaptive Cards: the one in the chat, the two inside the dialog, and the record of a sent request.
public static class SupplyCards
{
// The card in the chat. msteams.type "task/fetch" makes its button open a dialog,
// and "task" tells the agent which dialog to show.
public static JsonObject Launcher() => Card(
new JsonArray
{
Text("Supply Desk", size: "Large", bold: true),
Text("Need something for your desk? Ask here, and the office team brings it over."),
},
new JsonArray
{
Submit("Request supplies", new JsonObject
{
["msteams"] = new JsonObject { ["type"] = "task/fetch" },
["task"] = "request",
}),
});

// Step 1 in the dialog: the form. It shows the values in request, and error above them when there's one.
public static JsonObject RequestForm(SupplyRequest request, string? error)
{
JsonArray body = new();

if (error is not null)
{
body.Add(Text(error, color: "Attention"));
}

body.Add(new JsonObject
{
["type"] = "Input.ChoiceSet",
["id"] = "item",
["label"] = "Item",
["isRequired"] = true,
["errorMessage"] = "Pick an item.",
["value"] = request.Item,
["choices"] = ItemChoices(),
});

body.Add(new JsonObject
{
["type"] = "Input.Number",
["id"] = "quantity",
["label"] = "How many?",
["min"] = 1,
["max"] = 10,
["isRequired"] = true,
["errorMessage"] = "Enter a number from 1 to 10.",
["value"] = int.TryParse(request.Quantity, out int quantity) ? quantity : 1,
});

body.Add(new JsonObject
{
["type"] = "Input.Text",
["id"] = "note",
["label"] = "Note for the office team (optional)",
["isMultiline"] = true,
["maxLength"] = 200,
["value"] = request.Note,
});

return Card(body, new JsonArray
{
Submit("Review", new JsonObject { ["task"] = "review" }),
Submit("Cancel", new JsonObject { ["task"] = "cancel" }, checkInputs: false),
});
}

// Step 2 in the dialog: the request to check. This card has no inputs,
// so both buttons carry the request's values in their data.
public static JsonObject ReviewStep(SupplyRequest request) => Card(
new JsonArray
{
Text("Check your request, then send it to the office team."),
Facts(request),
},
new JsonArray
{
Submit("Send request", Carry("send", request)),
Submit("Back", Carry("back", request)),
});

// The record the agent posts in the chat once the request is sent.
public static JsonObject RequestSent(SupplyRequest request, string requester) => Card(
new JsonArray
{
Text("Supply request sent", size: "Medium", bold: true),
Text($"{requester} asked the office team for:"),
Facts(request),
},
new JsonArray());

private static JsonObject Card(JsonArray body, JsonArray actions) => new()
{
["type"] = "AdaptiveCard",
["version"] = "1.5",
["body"] = body,
["actions"] = actions,
};

private static JsonObject Text(string text, string? size = null, bool bold = false, string? color = null)
{
JsonObject block = new()
{
["type"] = "TextBlock",
["text"] = text,
["wrap"] = true,
};

if (size is not null)
{
block["size"] = size;
}

if (bold)
{
block["weight"] = "Bolder";
}

if (color is not null)
{
block["color"] = color;
}

return block;
}

// checkInputs: false sends no input values, so Cancel works even when the form isn't filled in.
private static JsonObject Submit(string title, JsonObject data, bool checkInputs = true)
{
JsonObject action = new()
{
["type"] = "Action.Submit",
["title"] = title,
["data"] = data,
};

if (!checkInputs)
{
action["associatedInputs"] = "none";
}

return action;
}

private static JsonArray ItemChoices()
{
JsonArray choices = new();

foreach (string item in SupplyCatalog.Limits.Keys)
{
choices.Add(new JsonObject { ["title"] = item, ["value"] = item });
}

return choices;
}

private static JsonObject Facts(SupplyRequest request) => new()
{
["type"] = "FactSet",
["facts"] = new JsonArray
{
Fact("Item", request.Item),
Fact("How many", request.Quantity),
Fact("Note", request.Note.Length > 0 ? request.Note : "None"),
},
};

private static JsonObject Fact(string title, string value) => new()
{
["title"] = title,
["value"] = value,
};

// The data for a button on a card without inputs: which step comes next, and the request so far.
private static JsonObject Carry(string task, SupplyRequest request) => new()
{
["task"] = task,
["item"] = request.Item,
["quantity"] = request.Quantity,
["note"] = request.Note,
};
}

The parts that make it a dialog:

  • Launcher's button has "msteams": { "type": "task/fetch" } in its data, so Teams asks the agent for a dialog instead of sending a message, and "task": "request" names the dialog.
  • RequestForm shows the values it's given in each input's value, so the form can come back filled in. Its error, when there is one, is a red TextBlock, with "color": "Attention", above the inputs. Review's data says "task": "review".
  • Cancel has "associatedInputs": "none": it sends no input values, so Teams doesn't ask for the required fields first.
  • ReviewStep has no inputs, so its buttons carry the request in their data, with Carry: "task": "send" or "task": "back", and the item, the number and the note.

The inputs use label, isRequired and errorMessage from How to Make Adaptive Card Inputs Required. The drop-down list, the number's limits, the multi-line note, the prefilled values, the facts and the red text each have their own how-to, under Related at the end of this page.

Step 5: Build the Dialog's Answers​

SupplyDialogs builds the two answers that carry something, continue and message:

SupplyDialogs.cs
using System.Text.Json.Nodes;
using Microsoft.Teams.Apps.Schema;
using Microsoft.Teams.Apps.TaskModules;

namespace SupplyDesk;

// Builds the answers the agent gives Teams while a dialog is open.
public static class SupplyDialogs
{
// "continue": show this card in the dialog, under this title.
// Teams opens the dialog with it, or puts it in place of the card that's showing.
public static TaskModuleResponse Show(string title, JsonObject card) => new()
{
Task = new Response
{
Type = TaskModuleResponseTypes.Continue,
Value = new
{
title,
width = "medium",
height = "medium",
card = new TeamsAttachment
{
ContentType = AttachmentContentTypes.AdaptiveCard,
Content = card,
},
},
},
};

// "message": show this text in the dialog, in place of the card.
public static TaskModuleResponse Message(string text) => new()
{
Task = new Response
{
Type = TaskModuleResponseTypes.Message,
Value = text,
},
};
}
  • TaskModuleResponse and Response come from the Teams SDK package, Microsoft.Teams.Apps, which the Teams extension uses.
  • Show answers continue. Its Value is an anonymous object whose property names become the JSON names Teams expects: title, width, height and card. The card goes in a TeamsAttachment, with the Adaptive Card content type.
  • width and height are "medium": half the Teams window's width. How to Set the Size of a Teams Dialog in the Microsoft 365 Agents SDK in C# compares every size.
  • Message answers message, and its Value is the text.

The third answer, nothing, needs no builder: the handler returns null.

Step 6: Route the Dialog​

The agent class connects it all. Here are its constructor and two of its handlers:

SupplyDeskAgent.cs (excerpt)
public SupplyDeskAgent(AgentApplicationOptions options, ILogger<SupplyDeskAgent> logger) : base(options)
{
_logger = logger;

OnConversationUpdate(ConversationUpdateEvents.MembersAdded, WelcomeAsync);
OnActivity(ActivityTypes.Message, ShowLauncherAsync);

// Each dialog route matches the "task" value in the button's data.
TeamsExtension.TaskModules.OnFetch("request", OpenFormAsync);
TeamsExtension.TaskModules.OnSubmit("review", ReviewAsync);
TeamsExtension.TaskModules.OnSubmit("back", BackAsync);
TeamsExtension.TaskModules.OnSubmit("send", SendAsync);
TeamsExtension.TaskModules.OnSubmit("cancel", CancelAsync);
}

// task/submit from Review: check the request. A problem shows the form again, with the values and the problem;
// otherwise the dialog moves on to the review step.
private Task<TaskModuleResponse> ReviewAsync(ITeamsTurnContext turnContext, ITurnState turnState, TaskModuleRequest request, CancellationToken cancellationToken)
{
SupplyRequest supplies = SupplyRequest.FromDialog(request);
string? problem = SupplyCatalog.FindProblem(supplies);

return Task.FromResult(problem is null
? SupplyDialogs.Show("Check your request", SupplyCards.ReviewStep(supplies))
: SupplyDialogs.Show("Request office supplies", SupplyCards.RequestForm(supplies, problem)));
}

// task/submit from Cancel: no answer, so Teams closes the dialog and shows nothing.
// The handler's type promises a response, but the SDK accepts null as "no answer": null! says that's intended.
private Task<TaskModuleResponse> CancelAsync(ITeamsTurnContext turnContext, ITurnState turnState, TaskModuleRequest request, CancellationToken cancellationToken)
{
return Task.FromResult<TaskModuleResponse>(null!);
}

SupplyDeskAgent.cs in a macOS-style editor window: the constructor routes messages to the launcher card and registers TeamsExtension.TaskModules.OnFetch for request and OnSubmit for review, back, send and cancel; ReviewAsync returns the review step or the form with the problem; CancelAsync returns null! so Teams closes the dialog

  • OnFetch("request", OpenFormAsync) answers the launcher's button with the empty form.
  • OnSubmit("review", ReviewAsync) checks the request. A problem gives the form again, with the values and the problem; otherwise, the review step. Each answer is a continue, so the dialog stays open.
  • OnSubmit("back", BackAsync) returns the form, filled in from the data Back carried.
  • OnSubmit("send", SendAsync) checks again, because a button's data comes from the person's Teams client, not from the agent. Then it posts the request in the chat with SendActivityAsync, while the dialog is still open, and answers with a message.
  • OnSubmit("cancel", CancelAsync) returns null: no answer, so Teams closes the dialog.

CancelAsync writes null!, not null. The SDK's handler type, TaskSubmitHandler, returns Task<TaskModuleResponse>, which says the answer is never null, so a plain null builds with warning CS8625: Cannot convert null literal to non-nullable reference type. The SDK's code sends a null answer as an empty HTTP 200, and Teams closes the dialog. Changing the method's return type to Task<TaskModuleResponse?> instead gave warning CS8621, on the line that registers it.

The whole class is in The Complete Code. How to Read the Values Submitted from a Teams Dialog in the Microsoft 365 Agents SDK in C# shows OnSubmit with a single input.

With the routes in place, the agent's code is complete, and the rest is registering it and trying it.

Step 7: Register Supply Desk in Teams​

Supply Desk needs what Treat Poll had in Part 9: a public address, a bot registration and an app package.

A dev tunnel, in a second terminal:

Terminal 2
devtunnel create supply-desk --allow-anonymous
devtunnel port create supply-desk -p 3978
devtunnel host supply-desk
Output (the last command)
Connection to host tunnel relay restored.
Hosting port: 3978
Connect via browser: https://1ttjtj67-3978.inc1.devtunnels.ms
Inspect network activity: https://1ttjtj67-3978-inspect.inc1.devtunnels.ms

Ready to accept connections for tunnel: supply-desk.inc1

A bot, registered with the Teams developer CLI in a third terminal, as in How to Register a Bot with the Teams Developer CLI. Use your tunnel's address, keep the credentials in a file outside the project, and give it the icons from your app package:

Terminal 3
teams app create --name "Supply Desk" --endpoint "https://1ttjtj67-3978.inc1.devtunnels.ms/api/messages" --env ./supplydesk.json --color-icon color.png --outline-icon outline.png
Output
- Acquiring tokens...
✔ Tokens acquired
- Creating Azure AD app...
✔ Created Azure AD app (00000000-0000-0000-0000-000000000000)
- Generating client secret...
✔ Generated client secret
- Creating Teams app...
✔ Created Teams app (00000000-0000-0000-0000-000000000000)
- Registering bot...
✔ Bot registered

App created successfully!
Name: Supply Desk
Teams App ID: 00000000-0000-0000-0000-000000000000
Bot ID: 00000000-0000-0000-0000-000000000000
Endpoint: https://1ttjtj67-3978.inc1.devtunnels.ms/api/messages

▸ Install in Teams → https://teams.microsoft.com/l/app/00000000-0000-0000-0000-000000000000?installAppPackage=true&appTenantId=11111111-1111-1111-1111-111111111111
▸ Developer Portal → https://dev.teams.microsoft.com/apps/00000000-0000-0000-0000-000000000000
Credentials written to ./supplydesk.json

The agent's identity, in user secrets, with the values from the file, exactly as in Part 9:

Terminal 1
dotnet user-secrets set "Connections:ServiceConnection:Settings:ClientId" "<bot ID>"
dotnet user-secrets set "Connections:ServiceConnection:Settings:ClientSecret" "<client secret>"
dotnet user-secrets set "Connections:ServiceConnection:Settings:AuthorityEndpoint" "https://login.microsoftonline.com/<tenant ID>"
dotnet user-secrets set "TokenValidation:Audiences:0" "<bot ID>"
dotnet user-secrets set "TokenValidation:TenantId" "<tenant ID>"
dotnet user-secrets set "AllowedTenants:0" "<tenant ID>"

Then delete supplydesk.json: the secret shouldn't sit in a file.

An app package. Supply Desk works in a one-to-one chat, so its bot's scopes are personal:

appPackage/manifest.json
{
"$schema": "https://developer.microsoft.com/json-schemas/teams/v1.30/MicrosoftTeams.schema.json",
"manifestVersion": "1.30",
"version": "1.0.0",
"id": "22222222-2222-2222-2222-222222222222",
"developer": {
"name": "Contoso",
"websiteUrl": "https://www.example.com",
"privacyUrl": "https://www.example.com/privacy",
"termsOfUseUrl": "https://www.example.com/terms"
},
"name": {
"short": "Supply Desk",
"full": "Supply Desk"
},
"description": {
"short": "Asks the office team for desk supplies.",
"full": "Chat with Supply Desk and select Request supplies: a dialog asks what you need and how many, checks the request, and sends it to the office team. A sample agent built with the Microsoft 365 Agents SDK."
},
"icons": {
"color": "color.png",
"outline": "outline.png"
},
"accentColor": "#00796B",
"bots": [
{
"botId": "22222222-2222-2222-2222-222222222222",
"scopes": [
"personal"
],
"supportsFiles": false,
"isNotificationOnly": false
}
]
}

Put your bot ID in id and botId, add a 192×192 color.png and a 32×32 outline.png, and zip the three files, as in How to Create a Teams App Package for a Bot. Dialogs need nothing extra in the manifest: the bot is enough.

Step 8: Run the Agent and Add It​

In Terminal 1:

Terminal 1
dotnet run
Output
Using launch settings from /Users/you/source/SupplyDesk/Properties/launchSettings.json...
info: Microsoft.Agents.Authentication.ConfigurationConnections[0]
No assembly name given in config for connection `ServiceConnection`. Using default assembly lib: `Microsoft.Agents.Authentication.Msal`
info: Microsoft.Agents.Authentication.ConfigurationConnections[0]
No type name given in config for connection `ServiceConnection`. Using default type name: `MsalAuth`
info: Microsoft.Agents.Hosting.AspNetCore.BackgroundQueue.HostedActivityService[0]
Queued Hosted Service is running.
info: Microsoft.Agents.Hosting.AspNetCore.BackgroundQueue.HostedTaskService[0]
Queued Hosted Service is running.

info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:3978
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: /Users/you/source/SupplyDesk

Upload the package as a custom app, as in How to Upload a Custom App in Microsoft Teams: Store, Manage your apps, Upload an app, Upload a custom app. Teams shows Supply Desk's details:

The Supply Desk dialog by Contoso with an Add button, 0 installs in the last month, Works in Teams, Free, and the description Asks the office team for desk supplies.

Select Add, then Open. Adding the app starts the chat, and Supply Desk answers that with its card:

Supply Desk's card in its chat: Supply Desk, Need something for your desk? Ask here, and the office team brings it over, and a Request supplies button

Step 9: Open the Dialog​

Select Request supplies. Teams asks the agent for the dialog, and opens what it gets:

A Teams dialog with the Supply Desk icon and name, the title Request office supplies and an X, and a form: an empty required Item list, How many? with 1, an optional note box, and Review and Cancel buttons

Teams added the app's icon and name above the title, and an X to close it. The task/fetch invoke's value, from the agent's log:

task/fetch value
{
"data": {
"task": "request",
"type": "task/fetch"
},
"context": {
"theme": "default"
}
}

The button's data arrived with the msteams object turned into "type": "task/fetch". The agent answered with continue:

The answer (the card shortened)
{
"status": 200,
"body": {
"task": {
"type": "continue",
"value": {
"title": "Request office supplies",
"width": "medium",
"height": "medium",
"card": {
"contentType": "application/vnd.microsoft.card.adaptive",
"content": { "type": "AdaptiveCard", "version": "1.5", "body": [ ... ], "actions": [ ... ] }
}
}
}
}
}

The Item list holds the catalog's four items:

The same dialog with the Item list open: Notebook, Pens, Sticky notes and Headset

Step 10: Let Teams Check the Required Fields​

Select Review before picking an item:

The form with Pick an item. in red under the empty Item list

Teams showed the list's errorMessage itself. The agent's log had the task/fetch from opening the dialog, and nothing from Review: an empty required input stops the submit before it leaves Teams.

Step 11: Ask for More Than the Limit​

Pick Headset, set How many? to 2, and add a note:

The form filled in: Headset, 2, and the note My headset microphone stopped working.

Select Review. This time Teams sent task/submit, with the button's data and the three inputs:

task/submit value
{
"data": {
"task": "review",
"item": "Headset",
"quantity": "2",
"note": "My headset microphone stopped working."
},
"context": {
"theme": "default"
}
}

"quantity": "2" is text, as Step 3 expected. A request can take one headset, so FindProblem found a problem, and the agent answered with the form again:

The form again, with Headset: one request can take up to 1. in red at the top, and Headset, 2 and the note still filled in

Everything is as Leo typed it, with the problem on top. How to Show an Error in a Teams Dialog in the Microsoft 365 Agents SDK in C# shows the pattern on its own.

Step 12: Review, Go Back and Send​

Change How many? to 1, and select Review. The request passes, and the dialog moves to the review step, with a new title:

The dialog titled Check your request: Check your request, then send it to the office team, the facts Item Headset, How many 1 and the note, and Send request and Back buttons

Select Back. The form returns, filled in from the data Back carried:

The form titled Request office supplies again, with Headset, 1 and the note filled in, and no error

Select Review again, then Send request. The agent posted the request in the chat and answered with a message, which took the card's place in the dialog:

The dialog, still titled Check your request, showing only Your request is with the office team. You'll find a copy in the chat.

The message stays until the dialog is closed. Close it with its X, and the request is in the chat, under the card:

The chat with the Supply Desk card, and below it the Supply request sent card: Leo asked the office team for: Item Headset, How many 1, Note My headset microphone stopped working.

The agent's answer to Send request, from its log:

The answer
{
"status": 200,
"body": {
"task": {
"type": "message",
"value": "Your request is with the office team. You'll find a copy in the chat."
}
}
}

How to Build a Multi-Step Teams Dialog in the Microsoft 365 Agents SDK in C# and How to Close a Teams Dialog with a Message in the Microsoft 365 Agents SDK in C# show steps and messages on their own.

Step 13: Cancel​

Open the dialog again and select Cancel. It closes, and nothing appears. The agent's answer was:

The answer
{
"status": 200
}

A 200 with no body: the SDK's answer for the null that CancelAsync returned. How to Close a Teams Dialog Without a Message in the Microsoft 365 Agents SDK in C# shows it on its own.

That's the dialog's whole life: it opens, checks, steps forward and back, and ends with a message or with nothing at all.

When the Agent Can't Answer​

With the agent stopped, selecting Request supplies opened this:

A dialog with the Supply Desk icon and name and a red message: Unable to reach app. Please try again.

Teams showed the same message for a running agent in another test, when the button's task value matched no route: the invoke reached the agent, no handler answered it, and the SDK responds to an unanswered invoke with HTTP 501, Not Implemented. So when you see Unable to reach app. Please try again., look in the agent's log first. No invoke there: the agent or the tunnel isn't running. An invoke there: its task value has no route.

The Complete Code​

SupplyDeskAgent.cs
using Microsoft.Agents.Builder;
using Microsoft.Agents.Builder.App;
using Microsoft.Agents.Builder.State;
using Microsoft.Agents.Core.Models;
using Microsoft.Agents.Extensions.MSTeams;
using Microsoft.Teams.Apps.TaskModules;

namespace SupplyDesk;

// [TeamsExtension] gives this class a TeamsExtension property, which holds the Teams-only features, dialogs among them.
// The class must be partial: the SDK writes that property into the other part of the class when it builds.
[TeamsExtension]
public partial class SupplyDeskAgent : AgentApplication
{
private readonly ILogger<SupplyDeskAgent> _logger;

public SupplyDeskAgent(AgentApplicationOptions options, ILogger<SupplyDeskAgent> logger) : base(options)
{
_logger = logger;

OnConversationUpdate(ConversationUpdateEvents.MembersAdded, WelcomeAsync);
OnActivity(ActivityTypes.Message, ShowLauncherAsync);

// Each dialog route matches the "task" value in the button's data.
TeamsExtension.TaskModules.OnFetch("request", OpenFormAsync);
TeamsExtension.TaskModules.OnSubmit("review", ReviewAsync);
TeamsExtension.TaskModules.OnSubmit("back", BackAsync);
TeamsExtension.TaskModules.OnSubmit("send", SendAsync);
TeamsExtension.TaskModules.OnSubmit("cancel", CancelAsync);
}

// When someone adds Supply Desk, the agent itself is among the members added.
private async Task WelcomeAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
if (turnContext.Activity.MembersAdded.Any(member => member.Id == turnContext.Activity.Recipient.Id))
{
await turnContext.SendActivityAsync(LauncherMessage(), cancellationToken);
}
}

// Any message gets the card with the button that opens the dialog.
private Task ShowLauncherAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
return turnContext.SendActivityAsync(LauncherMessage(), cancellationToken);
}

// task/fetch: Teams asks what to show in the dialog. The answer is the empty form.
private Task<TaskModuleResponse> OpenFormAsync(ITeamsTurnContext turnContext, ITurnState turnState, TaskModuleRequest request, CancellationToken cancellationToken)
{
return Task.FromResult(SupplyDialogs.Show("Request office supplies", SupplyCards.RequestForm(SupplyRequest.Empty, error: null)));
}

// task/submit from Review: check the request. A problem shows the form again, with the values and the problem;
// otherwise the dialog moves on to the review step.
private Task<TaskModuleResponse> ReviewAsync(ITeamsTurnContext turnContext, ITurnState turnState, TaskModuleRequest request, CancellationToken cancellationToken)
{
SupplyRequest supplies = SupplyRequest.FromDialog(request);
string? problem = SupplyCatalog.FindProblem(supplies);

return Task.FromResult(problem is null
? SupplyDialogs.Show("Check your request", SupplyCards.ReviewStep(supplies))
: SupplyDialogs.Show("Request office supplies", SupplyCards.RequestForm(supplies, problem)));
}

// task/submit from Back: the form again, filled in with what was there.
private Task<TaskModuleResponse> BackAsync(ITeamsTurnContext turnContext, ITurnState turnState, TaskModuleRequest request, CancellationToken cancellationToken)
{
return Task.FromResult(SupplyDialogs.Show("Request office supplies", SupplyCards.RequestForm(SupplyRequest.FromDialog(request), error: null)));
}

// task/submit from Send request: check again, because a button's data comes from the client,
// post the request in the chat, and close the dialog with a message.
private async Task<TaskModuleResponse> SendAsync(ITeamsTurnContext turnContext, ITurnState turnState, TaskModuleRequest request, CancellationToken cancellationToken)
{
SupplyRequest supplies = SupplyRequest.FromDialog(request);
string? problem = SupplyCatalog.FindProblem(supplies);

if (problem is not null)
{
return SupplyDialogs.Show("Request office supplies", SupplyCards.RequestForm(supplies, problem));
}

string requester = FirstName(turnContext.Activity.From.Name);
await turnContext.SendActivityAsync(CardMessage(SupplyCards.RequestSent(supplies, requester)), cancellationToken);
_logger.LogInformation("Supply request sent: {Quantity} x {Item}.", supplies.Quantity, supplies.Item);

return SupplyDialogs.Message("Your request is with the office team. You'll find a copy in the chat.");
}

// task/submit from Cancel: no answer, so Teams closes the dialog and shows nothing.
// The handler's type promises a response, but the SDK accepts null as "no answer": null! says that's intended.
private Task<TaskModuleResponse> CancelAsync(ITeamsTurnContext turnContext, ITurnState turnState, TaskModuleRequest request, CancellationToken cancellationToken)
{
return Task.FromResult<TaskModuleResponse>(null!);
}

private static IActivity LauncherMessage() => CardMessage(SupplyCards.Launcher());

private static IActivity CardMessage(object card) =>
MessageFactory.Attachment(new Attachment { ContentType = ContentTypes.AdaptiveCard, Content = card });

private static string FirstName(string? name) =>
string.IsNullOrWhiteSpace(name) ? "Someone" : name.Split(' ')[0];
}

Program.cs, SupplyRequest.cs, SupplyCatalog.cs, SupplyCards.cs, SupplyDialogs.cs and appPackage/manifest.json are complete in Steps 1 to 7.

Stop and Clean Up​

Everything this part created outside your project folder stays until you remove it:

  1. Stop the agent and the tunnel host with Ctrl+C in their terminals.

  2. Uninstall Supply Desk in Teams: How to Uninstall an App in Microsoft Teams.

  3. Delete the app under Apps in the Teams Developer Portal: How to Delete an App in the Teams Developer Portal.

  4. Delete the bot under Tools > Bot management: How to Delete a Bot in the Teams Developer Portal.

  5. Delete the app registration, which neither of the portal's deletes removes: How to Delete an App Registration in Microsoft Entra ID.

  6. Delete the tunnel:

    Terminal
    devtunnel delete supply-desk -f
    Output
    Deleted: supply-desk.inc1
  7. Remove the client secret from your machine: dotnet user-secrets clear, in the project folder, deletes the project's user secrets and prints nothing.

What You Can Do Now​

  • Turn on the Teams extension with [TeamsExtension] on a partial agent class, and use its TeamsExtension property.
  • Open a dialog from a card button with "msteams": { "type": "task/fetch" }, and answer task/fetch with TeamsExtension.TaskModules.OnFetch.
  • Handle the dialog's buttons with OnSubmit, read their values, and answer with another card, a message or nothing.
  • Check a dialog's values in the agent, and send the form back with the problem and what was typed.
  • Lead someone through steps, carrying earlier answers in the buttons' data.
  • Tell an agent that's down from a route that's missing, when Teams says Unable to reach app.

Common Mistakes​

MistakeWhat happensDo this instead
Writing Teams.TaskModules, as the SDK's documentation sayserror CS0103: The name 'Teams' does not exist in the current contextWrite TeamsExtension.TaskModules
Leaving partial off the agent classerror MAA001: '...' must be declared as 'partial' to use an AgentExtension attributeDeclare it partial
No msteams object in the launcher's button dataThe button sends a message, and no dialog opensAdd "msteams": { "type": "task/fetch" }
Different task values in a button and in its routeUnable to reach app. Please try again.Use one name in both places
Sending the form back empty after a problemThe person types everything againSet each input's value
Trusting the values a button carriesA client can send anythingCheck them again before acting, as SendAsync does
return null; in a submit handlerWarning CS8625null!

Troubleshooting​

SymptomLikely causeFix
Unable to reach app. Please try again., nothing in the agent's logThe agent or the tunnel isn't runningStart both, and check the bot's endpoint
Unable to reach app. Please try again., with the invoke in the logNo route matched its task valueFix the name, or add the route
The required-field message shows, and the agent gets nothingTeams checks required inputs before sendingExpected
The dialog doesn't close after a buttonThe handler answered with a card or a messageReturn null! to close it
A number arrives as "2"Card values are textParse it, as SupplyCatalog does

FAQ​

When should I use a dialog instead of a card in the chat?​

When the task needs room or several steps, or when it shouldn't leave traces in the chat until it's done. For one or two buttons, a card in the chat is simpler, and Part 9's Universal Actions can update it in place.

Does the agent hear about the X?​

No. Closing a dialog with its X sent the agent nothing at all. If you need to know whether someone finished, record it when they select your own buttons.

Can I use attributes instead of the fluent routes?​

Yes: [TeamsTaskFetchRoute("request")] and [TeamsTaskSubmitRoute("review")] on the handler methods do the same as OnFetch and OnSubmit. Microsoft's dialog sample for the Agents SDK uses them.

Can a dialog show my own web page?​

Yes: a continue answer can carry a url instead of a card, and the page talks back to Teams through Microsoft's Teams JavaScript library. That's Part 11.

Conclusion​

A Teams dialog is a conversation of two invokes. task/fetch, from a card button with "msteams": { "type": "task/fetch" }, opens it, and task/submit, from a button inside it, moves it on. Your agent answers each with another card, a message, or nothing, which closes it. In the Agents SDK, [TeamsExtension] gives the agent TeamsExtension.TaskModules, whose OnFetch and OnSubmit route both on the task value in the button's data.

Next: Part 11: Show a Web Page in a Teams Dialog (coming soon). A dialog can also show a page you build, for what an Adaptive Card can't do.

Additional Resources​