Skip to main content

Part 8: Run Your Agent in Microsoft Teams

Everything so far ran in the Agents Playground, on your own computer. In this part your agent goes to real Microsoft Teams: people install it as an app, chat with it, and see it type. To get there, Teams needs to know your agent, reach it, and trust it, and your agent needs to protect an endpoint that's now open to the internet.

This is Part 8 of the Microsoft 365 Agents SDK Fundamentals, a 26-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 (you are here)
  9. Part 9: Universal Actions: Adaptive Cards That Update (coming soon)
  10. Part 10: Teams Dialogs (coming soon)
  11. Part 11: Commands, Suggested Actions and Targeted Messages (coming soon)
  12. Part 12: Mentions, Rosters and Team Events (coming soon)
  13. Part 13: Meeting Events (coming soon)
  14. Part 14: Send and Receive Files (coming soon)
  15. Part 15: Sign People In with SSO and OAuth (coming soon)
  16. Part 16: Message Extensions and Link Unfurling (coming soon)
  17. Part 17: AI Labels, Citations and Feedback (coming soon)
  18. Part 18: Bring Your Agent to Microsoft 365 Copilot (coming soon)
  19. Part 19: Store State in Azure Blob Storage and Cosmos DB (coming soon)
  20. Part 20: Telemetry with OpenTelemetry (coming soon)
  21. Part 21: Web Chat and Direct Line (coming soon)
  22. Part 22: Reach People in Slack (coming soon)
  23. Part 23: Call a Copilot Studio Agent (coming soon)
  24. Part 24: Agent-to-Agent Communication (coming soon)
  25. Part 25: Keep Conversation Transcripts (coming soon)
  26. Part 26: Deploy Your Agent to Azure (coming soon)

By the end of this part you'll know the three registrations every Teams agent has, how a message travels from Teams to code running on your computer and back, and the four things that change once your agent's endpoint is public. You'll register a bot without an Azure subscription, run it behind a dev tunnel, install it in Teams, and lock it down so it accepts only signed requests from your own organization.

What Teams Needs Before It Talks to Your Agent​

Microsoft's guide to registering an agent for Teams lists three registrations, in three different services:

  • An Entra ID app registration is the agent's unique identity within the Microsoft 365 ecosystem, used for service authentication and consented access to user data.
  • Registering the agent with ACS enables it to participate in Teams chat and receive realtime information about user activities in Teams. ACS is the Agent Communication Service: it carries messages between Teams and your agent's endpoint.
  • An app manifest registered in Teams Developer Portal establishes an agent as a distributable, installable Teams app.

The three share one ID: the manifest's bot ID (the unique ID shared by its ACS registration and its Entra ID app registration).

There are two kinds of ACS registration. A Teams-managed one lives in the Teams Developer Portal and needs no Azure subscription; an Azure-managed one is an Azure Bot resource. Microsoft's advice: The recommended approach to agent development is to use a Teams-managed ACS registration and migrate to an Azure-managed registration only if needed, mainly for single sign-on, which Part 15 covers. This part uses a Teams-managed registration.

How a Message Travels​

Teams doesn't call your computer directly. It calls the endpoint in the bot's registration, which must be a public HTTPS address, and a dev tunnel forwards it to the agent on your machine. The agent's reply goes back the other way, to the serviceUrl the activity named, with a token from Microsoft Entra ID:

What Changes Once the Endpoint Is Public​

In the Playground, only you could reach the agent. Behind a public tunnel, anyone can, so four settings this course has left alone so far now matter:

ConcernWithout itWhat this part adds
IdentityThe agent can't reply to TeamsA client secret in a Connections section
Incoming tokensIn the Development environment, the agent accepts requests without a tokenToken validation with forceEnable: true
Reply destinationsThe agent replies to whatever serviceUrl a request namesThe outbound host validator
OrganizationsAnyone in any organization can install and use the botA middleware that accepts only your tenant

The Example: Lunch Picker​

The agent for this part is Lunch Picker. Send it lunch, and after a short pause it suggests where to eat today, by your first name: How about Spice Route today, Leo? While it "checks today's menus", Teams shows that it's typing. When someone installs it, it says hello, and anything else gets a one-line help message. You'll build it in steps:

StepYou addWhat you'll see
1The agentIt works in the Playground
2A dev tunnelA public HTTPS address for port 3978
3A bot registrationA bot ID, an endpoint and a client secret
4The agent's identityConfiguration the agent signs in with
5Token validationA request without a token gets 401
6The outbound host validatorReplies go only to Microsoft's hosts
7–8An app package, uploaded to TeamsLunch Picker installed for you
9NothingA real Teams chat, with a typing indicator
10A tenant filterMessages from other organizations are ignored

Prerequisites​

  • The .NET 10 SDK. dotnet --version should print 10.0. and a patch number; this page was built with 10.0.404.
  • The Microsoft 365 Agents Playground. agentsplayground --version should print 0.2.30.
  • The dev tunnels CLI, signed in. devtunnel --version should print a Tunnel CLI version; this page used 1.0.2115. devtunnel user show tells you whether you're signed in.
  • A Microsoft 365 work or school account in an organization that lets you register apps and upload custom apps to Teams. If you don't have one, Microsoft's Teams quickstart points to the Microsoft 365 Developer Program for a sandbox. This page used a developer tenant.

Cost: nothing in this part needs an Azure subscription. The Teams-managed registration needs none, and dev tunnels need only a sign-in, within monthly limits per user.

Step 1: Create the Agent​

Create an empty ASP.NET Core project and add the Agents SDK's hosting package:

Terminal
dotnet new web -o LunchPicker
Output
The template "ASP.NET Core Empty" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/LunchPicker/LunchPicker.csproj:
Determining projects to restore...
Restored /Users/you/source/LunchPicker/LunchPicker.csproj (in 48 ms).
Restore succeeded.
Terminal
cd LunchPicker
dotnet add package Microsoft.Agents.Hosting.AspNetCore --version 1.9.205
Output (last lines)
info : PackageReference for package 'Microsoft.Agents.Hosting.AspNetCore' version '1.9.205' added to file '/Users/you/source/LunchPicker/LunchPicker.csproj'.
info : Generating MSBuild file /Users/you/source/LunchPicker/obj/LunchPicker.csproj.nuget.g.targets.
info : Writing assets file to disk. Path: /Users/you/source/LunchPicker/obj/project.assets.json
log : Restored /Users/you/source/LunchPicker/LunchPicker.csproj (in 1.27 sec).

Open Properties/launchSettings.json and set the two applicationUrl lines to port 3978, as in the earlier parts:

Properties/launchSettings.json (the two lines to change)
"applicationUrl": "http://localhost:3978",
Properties/launchSettings.json (in the https profile)
"applicationUrl": "https://localhost:3979;http://localhost:3978",

Now the agent. Create LunchAgent.cs:

LunchAgent.cs
using Microsoft.Agents.Builder;
using Microsoft.Agents.Builder.App;
using Microsoft.Agents.Builder.State;
using Microsoft.Agents.Core.Models;

namespace LunchPicker;

public class LunchAgent : AgentApplication
{
private static readonly string[] Places =
[
"Spice Route",
"The Green Bowl",
"Pasta Corner",
"Noodle House",
"Taco Stand",
];

public LunchAgent(AgentApplicationOptions options) : base(options)
{
OnConversationUpdate(ConversationUpdateEvents.MembersAdded, WelcomeAsync);
OnMessage("lunch", PickLunchAsync);
OnActivity(ActivityTypes.Message, HelpAsync, rank: RouteRank.Last);
}

private async Task WelcomeAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
foreach (ChannelAccount member in turnContext.Activity.MembersAdded)
{
// The agent is one of the members added; don't welcome it.
if (member.Id == turnContext.Activity.Recipient.Id)
{
continue;
}

await turnContext.SendActivityAsync(
$"Hi {FirstName(member.Name)}! I'm Lunch Picker. Send **lunch** and I'll pick where to eat today.",
cancellationToken: cancellationToken);
}
}

private async Task PickLunchAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
// Stands in for checking today's menus, which takes a moment.
await Task.Delay(TimeSpan.FromSeconds(3), cancellationToken);

string place = Places[Random.Shared.Next(Places.Length)];
await turnContext.SendActivityAsync(
$"How about **{place}** today, {FirstName(turnContext.Activity.From.Name)}?",
cancellationToken: cancellationToken);
}

private Task HelpAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
=> turnContext.SendActivityAsync("Send **lunch** and I'll pick where to eat today.", cancellationToken: cancellationToken);

// Teams sends the person's display name, such as "Leo Martin"; greet them by the first word.
private static string FirstName(string? name)
=> string.IsNullOrWhiteSpace(name) ? "there" : name.Split(' ', StringSplitOptions.RemoveEmptyEntries)[0];
}

Everything here comes from earlier parts:

  • OnConversationUpdate(ConversationUpdateEvents.MembersAdded, WelcomeAsync) greets people when the agent is added, skipping the agent itself, which is also in MembersAdded. How to Send a Welcome Message in the Microsoft 365 Agents SDK in C# explains the pattern.
  • OnMessage("lunch", PickLunchAsync) handles the one command. The three-second Task.Delay stands in for slow work, so there's something to wait for.
  • OnActivity(ActivityTypes.Message, HelpAsync, rank: RouteRank.Last) catches every other message, after all other routes.
  • FirstName turns a display name like Leo Martin into Leo, and falls back to there when a channel sends no name.

In Program.cs, host the agent as in the earlier parts:

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

var builder = WebApplication.CreateBuilder(args);

builder.AddAgentDefaults()
.AddAgent<LunchAgent>();
builder.Services.AddSingleton<IStorage, MemoryStorage>();

var app = builder.Build();

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

app.Run();

And turn on the typing timer in appsettings.json, which Part 7 introduced: while a turn is running, the SDK keeps sending typing activities.

appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"AgentApplication": {
"StartTypingTimer": true
}
}

How to Show a Typing Indicator in the Microsoft 365 Agents SDK in C# shows both ways to turn it on. Run the agent:

Terminal 1
dotnet run

In a second terminal, start the Playground as Teams:

Terminal 2
agentsplayground -e http://localhost:3978/api/messages -c msteams

The welcome arrives as soon as the Playground connects. Send lunch, and three seconds later Lunch Picker answers, by the Playground user's first name:

The Agents Playground chat: Test Bot says Hi there! I'm Lunch Picker. Send lunch and I'll pick where to eat today. The user sends lunch, and Test Bot answers How about Noodle House today, Alex?

The agent works. Stop the Playground and the agent with Ctrl+C: from here on, Teams plays the channel.

Step 2: Give the Agent a Public Address​

Teams can only call a public HTTPS endpoint, so the agent needs a dev tunnel. Its URL goes into the bot's registration, so use a persistent tunnel: a temporary one gets a new URL every time you start it. Create it, add port 3978, and host it:

Terminal 2
devtunnel create lunch-picker --allow-anonymous
Output
Tunnel ID : lunch-picker.inc1
Description :
Labels :
Access control : {+Anonymous [connect]}
Host connections : 0
Client connections : 0
Current upload rate : 0 MB/s (limit: 20 MB/s)
Current download rate : 0 MB/s (limit: 20 MB/s)
Tunnel Expiration : 30 days

Set default tunnel to lunch-picker.inc1.
Terminal 2
devtunnel port create lunch-picker -p 3978
Output
Tunnel ID : lunch-picker.inc1
Port Number : 3978
Protocol : auto
Access control : {Inherited: +Anonymous [connect]}
Client connections : 0
Terminal 2
devtunnel host lunch-picker
Output
Connection to host tunnel relay restored.
Hosting port: 3978
Connect via browser: https://q856tzrv-3978.inc1.devtunnels.ms
Inspect network activity: https://q856tzrv-3978-inspect.inc1.devtunnels.ms

Ready to accept connections for tunnel: lunch-picker.inc1

Leave it running. How to Create a Dev Tunnel That Keeps Its URL explains each command.

--allow-anonymous is needed because Teams can't sign in to your tunnel. That makes the tunnel itself open to anyone with the URL, which is exactly why Step 5 makes the agent check every request's token. Microsoft's guide to testing an agent through a dev tunnel says the same: A public tunnel exposes the selected local port to the internet. Run only the service you intend to test, keep authentication enabled, and stop the tunnel when testing is complete.

Step 3: Register the Bot​

Sign in to the Teams Developer Portal and select Tools, then Bot management:

The Developer Portal's Tools page with the Bot management tile highlighted: Manage the bots associated with your apps

On the Teams-managed bots tab, select New bot:

Bot management on the Teams-managed bots tab, with no bots yet and the New bot button highlighted

Name it Lunch Picker and select Create:

The Create a new bot dialog with the bot name Lunch Picker

If Create fails

If your organization doesn't let ordinary users register apps, the portal shows Failed to create Microsoft Entra app: Insufficient privileges to complete the operation. That happened to me: Fixed: "Failed to create Microsoft Entra app: Insufficient privileges to complete the operation" shows the role an admin gave my account.

The bot's Configure page opens. Under Delivery method, choose HTTPS endpoint and enter the tunnel's URL followed by the agent's message path, /api/messages. Select Save:

The Lunch Picker bot's Configure page: Delivery method HTTPS endpoint, with the endpoint https://q856tzrv-3978.inc1.devtunnels.ms/api/messages and the Save button highlighted

Socket mode, the other option, is marked New: the portal describes an outbound WebSocket connection with no public endpoint or tunnel, for development only. This course uses the HTTPS endpoint, which works for development and for published bots alike.

Now the secret the agent signs in with. Select Client secrets, then Create your first client secret:

The bot's Client secrets page: No client secrets, Create a client secret to authenticate your bot with Azure Bot Service, and the Create your first client secret button highlighted

Confirm with Create client secret:

The Create client secret dialog: Create a new client secret for your bot? The secret value will be shown only once after creation.

Copy the value with the copy icon. It's shown only once; you'll store it in Step 4:

The Client secret created dialog with the hidden secret value, the show and copy icons, and Done

Select Done. The secret expires in two years:

The Lunch Picker bot's Client secrets list: one secret, shown by its hint, expiring Nov 26, 2028

Go back to Bot management and note the bot's ID from the Bot Id column. On this page it's shown as 22222222-2222-2222-2222-222222222222. How to Register a Bot in the Teams Developer Portal covers these screens in more detail.

The agent also needs your organization's tenant ID. In the Microsoft Entra admin center, it's on Entra ID > Overview, as How to Find Your Microsoft Entra Tenant ID shows:

The Microsoft Entra admin center's Basic information: Name Contoso, the Tenant ID 11111111-1111-1111-1111-111111111111 highlighted with its copy icon, Primary domain example.com and License Microsoft Entra ID P2

On this page, the tenant ID is shown as 11111111-1111-1111-1111-111111111111. You now have everything the agent needs from Microsoft: a bot ID, a client secret and a tenant ID.

Step 4: Give the Agent Its Identity​

To reply, the agent asks Microsoft Entra ID for a token as its bot, with the client secret. That's the job of the Agents SDK's MSAL package:

Terminal 1
dotnet add package Microsoft.Agents.Authentication.Msal --version 1.9.205
Output (last lines)
info : Package 'Microsoft.Agents.Authentication.Msal' is compatible with all the specified frameworks in project '/Users/you/source/LunchPicker/LunchPicker.csproj'.
info : PackageReference for package 'Microsoft.Agents.Authentication.Msal' version '1.9.205' added to file '/Users/you/source/LunchPicker/LunchPicker.csproj'.
info : Writing assets file to disk. Path: /Users/you/source/LunchPicker/obj/project.assets.json
log : Restored /Users/you/source/LunchPicker/LunchPicker.csproj (in 661 ms).

Add two sections to appsettings.json, with your bot ID and tenant ID:

appsettings.json (two new sections)
"Connections": {
"ServiceConnection": {
"Settings": {
"AuthType": "ClientSecret",
"ClientId": "22222222-2222-2222-2222-222222222222",
"AuthorityEndpoint": "https://login.microsoftonline.com/11111111-1111-1111-1111-111111111111",
"Scopes": [
"https://api.botframework.com/.default"
]
}
}
},
"ConnectionsMap": [
{
"ServiceUrl": "*",
"Connection": "ServiceConnection"
}
]
  • Connections:ServiceConnection is a named connection: how the agent gets tokens. AuthType: ClientSecret signs in with a client secret, ClientId is the bot ID, and AuthorityEndpoint is your tenant's sign-in address. Scopes asks for a token for the Bot Framework API, which accepts the agent's replies. This is the single-tenant example from Microsoft's reference for configuring authentication in a .NET agent.
  • ConnectionsMap says which connection to use for which service URL. * means all of them.

The secret itself doesn't belong in appsettings.json. Keep it in .NET's user secrets, which live in your user profile, outside the project folder:

Terminal 1
dotnet user-secrets init
Output
Set UserSecretsId to '00000000-0000-0000-0000-000000000000' for MSBuild project '/Users/you/source/LunchPicker/LunchPicker.csproj'.
Terminal 1
dotnet user-secrets set "Connections:ServiceConnection:Settings:ClientSecret" "<your client secret>"
Output
Successfully saved Connections:ServiceConnection:Settings:ClientSecret to the secret store.

In the Development environment, ASP.NET Core reads user secrets on top of appsettings.json, so the setting completes the ServiceConnection. How to Store Secrets with .NET C# User Secrets Instead of appsettings.json explains how. Microsoft's reference adds a warning about client secrets: this should only be used for testing and development purposes. For a deployed agent, the same reference lists managed identities and federated credentials instead.

Step 5: Validate Every Incoming Token​

Every request Teams sends carries a token issued for your bot. Token validation checks it before the agent sees the message. The Agents SDK leaves that check to ASP.NET Core, through a sample file, AspNetExtensions.cs. Download the version that matches the SDK into the project:

Terminal 1
curl -sSLO https://raw.githubusercontent.com/microsoft/Agents-for-net/v1.9.205/src/samples/Shared/AspNetExtensions.cs

Tell it which tokens to accept, in appsettings.json:

appsettings.json (new section)
"TokenValidation": {
"Audiences": [
"22222222-2222-2222-2222-222222222222"
],
"TenantId": "11111111-1111-1111-1111-111111111111"
}

Audiences is your bot ID: a token must be issued for it. Then register the validation in Program.cs:

Program.cs (the AddAgentAuthorization line)
builder.AddAgentDefaults()
.AddAgent<LunchAgent>()
.AddAgentAuthorization(b => b.AddAgentAspNetAuthentication(), forceEnable: true);

forceEnable: true is the important part. Without it, AddAgentAuthorization follows its default, which its API reference describes: When null (the default), authorization is enabled in all environments except Development. dotnet run runs in Development, so the default would leave your public tunnel unprotected.

Here's what that looks like. Before adding forceEnable, I ran the agent with Microsoft's quickstart line, .AddAgentAuthorization(b => b.AddAgentAspNetAuthentication()), and sent it a made-up Teams message through the tunnel, with no token at all:

anon-activity.json
{
"type": "message",
"id": "1",
"channelId": "msteams",
"serviceUrl": "https://smba.trafficmanager.net/teams/",
"from": { "id": "anyone" },
"recipient": { "id": "lunch-picker" },
"conversation": { "id": "made-up-conversation" },
"text": "lunch"
}
Terminal 3
curl -s -i -X POST https://q856tzrv-3978.inc1.devtunnels.ms/api/messages -H "Content-Type: application/json" --data @anon-activity.json

-i prints the response's status and headers. The status:

Output (status line)
HTTP/2 202

The agent accepted it, logged Anonymous access is enabled for channel: msteams., and went on to answer: it got a token with its client secret and posted to the made-up conversation on Teams' servers:

Terminal 1
info: System.Net.Http.HttpClient.Microsoft.Agents.Builder.RestChannelServiceClientFactory.LogicalHandler[100]
Start processing HTTP request POST https://smba.trafficmanager.net/teams/v3/conversations/made-up-conversation/activities/1

Teams turned it away (The Access Token created to respond to a request from the agent was rejected by the remote endpoint), because the conversation doesn't exist. But a stranger had made the agent run its code and use its credentials. With forceEnable: true, the same request gets:

Output (status line and the www-authenticate header)
HTTP/2 401
www-authenticate: Bearer

401 Unauthorized before the agent's code runs, and www-authenticate: Bearer says a bearer token is required. How to Turn On Token Validation in Development in the Microsoft 365 Agents SDK in C# walks through AddAgentAuthorization, AspNetExtensions.cs and the settings on their own.

Step 6: Limit Where Replies Go​

The agent sends its replies to the serviceUrl each activity names. A real Teams activity names Teams' servers, but nothing stops a request from naming another host. Turn on the SDK's outbound host validator in appsettings.json:

appsettings.json (new section)
"OutboundHostValidator": {
"Enabled": true,
"IncludeDefaultMicrosoftHosts": true
}

With it on, the agent replies only to Microsoft's own hosts, which include smba.trafficmanager.net, the host Teams uses. A request that names any other host is refused with 400 before the agent's code runs. How to Turn On the Outbound Host Validator in the Microsoft 365 Agents SDK in C# shows a forged service URL being turned away.

Testing in the Playground again

The Playground's service URL is on localhost, which the validator refuses, and it sends no token in its default mode. To test locally with these settings, allow localhost in appsettings.Development.json as Fixed: "ServiceUrl host is not in the configured allowed hosts" for localhost shows, and start the Playground with authentication, as How to Test an Agent with Authentication in the Microsoft 365 Agents Playground explains.

Step 7: Build the App Package​

Teams installs an agent from an app package: a zip with a manifest.json and two icons. Make an appPackage folder in the project, and put the manifest in it:

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": "Lunch Picker",
"full": "Lunch Picker"
},
"description": {
"short": "Picks where to eat lunch today.",
"full": "Send lunch, and Lunch Picker suggests a place to eat today. A sample agent built with the Microsoft 365 Agents SDK."
},
"icons": {
"color": "color.png",
"outline": "outline.png"
},
"accentColor": "#E8590C",
"bots": [
{
"botId": "22222222-2222-2222-2222-222222222222",
"scopes": [
"personal"
],
"supportsFiles": false,
"isNotificationOnly": false
}
]
}

The manifest uses schema 1.30, the newest one Microsoft lists as generally available. botId is your bot ID, and I used the same ID for the app's id. scopes: ["personal"] makes Lunch Picker a one-to-one chat. Add the two icons next to it: color.png, 192 x 192 pixels, a white fork and knife on a solid orange square (#E8590C, the accentColor), and outline.png, 32 x 32 pixels, the same symbol in white on transparency. How to Create a Teams App Package for a Bot explains every field and Microsoft's icon rules.

Zip the three files, not the folder:

Terminal 3
cd appPackage
zip ../LunchPicker.zip manifest.json color.png outline.png
Output
adding: manifest.json (deflated 53%)
adding: color.png (deflated 14%)
adding: outline.png (stored 0%)

LunchPicker.zip is the package.

Step 8: Upload Lunch Picker to Teams​

Start the agent again (dotnet run), with the tunnel still hosting. In Teams, select Apps in the left rail, then the settings icon at the Store's top right:

The Teams Store with the Apps button highlighted in the left rail and the settings icon highlighted at the top right

On Manage your apps, select Upload an app:

Manage your apps with Upload an app highlighted

Choose Upload a custom app and pick LunchPicker.zip:

The Upload an app dialog with Upload a custom app highlighted above Submit an app to your org

Teams reads the manifest and shows the app's details, with its icon, developer and descriptions, and Bot under Capabilities in Teams. Select Add:

The Lunch Picker details dialog: the orange fork-and-knife icon, developer Contoso, the Add button highlighted, the short and full descriptions, and Bot under Capabilities in Teams

Then Open:

The Added successfully dialog for Lunch Picker, with the Open button highlighted

If Upload an app is missing, your account isn't allowed to upload custom apps: How to Check If Custom Apps Are Allowed in Microsoft Teams shows the admin settings, and How to Upload a Custom App in Microsoft Teams shows the upload on its own.

Step 9: Chat with Lunch Picker​

Lunch Picker's chat opens with its welcome. Send lunch:

The Lunch Picker chat in Teams: Hi there! I'm Lunch Picker. Send lunch and I'll pick where to eat today. Then lunch, and the answer How about The Green Bowl today, Leo?

Two details are worth a closer look.

The welcome says there, not Leo. When Teams installed the app, the membersAdded list held two members, the person and the bot, and neither had a name, so FirstName fell back to there. Messages do carry the sender's name, which is why the answer says Leo. Here's part of the message activity Teams sent, with IDs replaced:

The message activity (excerpt)
{
"type": "message",
"serviceUrl": "https://smba.trafficmanager.net/in/11111111-1111-1111-1111-111111111111/",
"channelId": "msteams",
"from": {
"id": "29:1a2b3c...",
"name": "Leo Martin"
},
"conversation": {
"conversationType": "personal",
"tenantId": "11111111-1111-1111-1111-111111111111",
"id": "a:1Xy9..."
},
"recipient": {
"id": "28:22222222-2222-2222-2222-222222222222",
"name": "Lunch Picker"
},
"text": "lunch",
"channelData": {
"tenant": {
"id": "11111111-1111-1111-1111-111111111111"
}
}
}

serviceUrl is where the reply goes, on the host the outbound validator allows. conversation.tenantId and channelData.tenant.id name the organization, which Step 10 uses. And recipient.id is your bot ID with a 28: prefix.

The typing indicator works here. The Playground can't show it, but Teams does. During the three-second pause, Lunch Picker's icon appears with Teams' typing animation:

The Lunch Picker chat while it works: the message lunch, and below it Lunch Picker's icon with the typing animation

Then the answer replaces it:

The answer after the pause: How about Spice Route today, Leo?

Step 10: Accept Only Your Organization​

A bot registered in the Developer Portal is multitenant: people in other organizations can install it too. Microsoft's guidance on agent tenancy is clear about who has to stop them: Agents intended for use only in a single tenant, or a known set of tenants, should always validate the tenant ID of incoming activity payloads in their application code. Configuring an agent to be single-tenant or configuring sign in audience restrictions are not substitutes for performing tenant validation in code.

Add a middleware that checks every activity's tenant. Create TenantFilterMiddleware.cs:

TenantFilterMiddleware.cs
using System.Text.Json;
using Microsoft.Agents.Builder;
using Microsoft.Agents.Core.Models;
using IMiddleware = Microsoft.Agents.Builder.IMiddleware;

namespace LunchPicker;

// Lets in only activities from the Microsoft Entra tenants you allow; the agent never sees the rest.
public class TenantFilterMiddleware(IEnumerable<string> allowedTenants) : IMiddleware
{
private readonly HashSet<string> _allowedTenants = new(allowedTenants, StringComparer.OrdinalIgnoreCase);

public async Task OnTurnAsync(ITurnContext turnContext, NextDelegate next, CancellationToken cancellationToken = default)
{
string? tenantId = GetTenantId(turnContext.Activity);

if (tenantId is null || !_allowedTenants.Contains(tenantId))
{
turnContext.Adapter.Logger?.LogWarning(
"Ignored {ActivityType} from tenant {TenantId}.",
turnContext.Activity.Type,
tenantId ?? "(none)");
return;
}

await next(cancellationToken);
}

// Teams puts the tenant in conversation.tenantId, and some activities only in channelData.tenant.id.
private static string? GetTenantId(IActivity activity)
{
if (!string.IsNullOrEmpty(activity.Conversation?.TenantId))
{
return activity.Conversation.TenantId;
}

if (activity.ChannelData is JsonElement channelData
&& channelData.ValueKind == JsonValueKind.Object
&& channelData.TryGetProperty("tenant", out JsonElement tenant)
&& tenant.ValueKind == JsonValueKind.Object
&& tenant.TryGetProperty("id", out JsonElement id)
&& id.ValueKind == JsonValueKind.String)
{
return id.GetString();
}

return null;
}
}

It reads the tenant from conversation.tenantId, or from channelData.tenant.id when that's empty, and calls next only for tenants on the list. For any other, it logs a warning and stops: no route runs and nothing is sent back. How to Accept Activities Only from Your Tenant in the Microsoft 365 Agents SDK in C# explains each part.

List your tenant in appsettings.json:

appsettings.json (new section)
"AllowedTenants": [
"11111111-1111-1111-1111-111111111111"
]

And register the middleware in Program.cs. A missing list would quietly lock everyone out, so the app refuses to start without one:

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

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<LunchAgent>()
.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();

The final Program.cs of Lunch Picker: it reads AllowedTenants and throws if the list is empty, then registers the agent, the TenantFilterMiddleware, and AddAgentAuthorization with forceEnable: true

To see the filter work, I started the agent once with a different tenant on the list, set through an environment variable that overrides the first entry:

Terminal 1
AllowedTenants__0=00000000-0000-0000-0000-000000000000 dotnet run

In Teams, lunch went unanswered:

The Lunch Picker chat: its last answer at 4:36 AM, How about Taco Stand today, Leo?, then the message lunch at 4:37 AM and again at 5:03 AM, both without a reply

And the agent's console said why:

Terminal 1
warn: Microsoft.Agents.Hosting.AspNetCore.CloudAdapter[0]
Ignored message from tenant 11111111-1111-1111-1111-111111111111.

My own organization wasn't on the list that time. Started normally, with dotnet run, the list has my tenant again, and Lunch Picker answers as before.

Do It with the CLI​

The Teams developer CLI, teams, can do Step 3 and most of Step 7 in one command. It's an npm package. Install it and sign in:

Terminal
npm install -g --allow-scripts=@azure/msal-node-extensions,keytar @microsoft/teams.cli@3.1.0
teams login --device-code

On npm 12, --allow-scripts lets the two install scripts run that the CLI needs to save your sign-in. Without it, the CLI forgets you right after teams login, which happened to me: Fixed: Teams Developer CLI Says "Not logged in" Right After teams login.

Then create the app and the bot, with the tunnel's endpoint, and write the credentials to appsettings.json:

Terminal
teams app create --name "Lunch Picker CLI" --endpoint https://q856tzrv-3978.inc1.devtunnels.ms/api/messages --env appsettings.json
Output
✔ Tokens acquired
✔ Created Azure AD app (33333333-3333-3333-3333-333333333333)
✔ Generated client secret
✔ Created Teams app (33333333-3333-3333-3333-333333333333)
✔ Bot registered

App created successfully!
Name: Lunch Picker CLI
Teams App ID: 33333333-3333-3333-3333-333333333333
Bot ID: 33333333-3333-3333-3333-333333333333
Endpoint: https://q856tzrv-3978.inc1.devtunnels.ms/api/messages

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

The CLI writes a Teams section with ClientId, ClientSecret and TenantId. The Agents SDK reads its identity from Connections and TokenValidation instead, so copy ClientId and TenantId into those sections as in Steps 4 and 5, move the secret into user secrets, and delete the Teams section. teams app doctor checks the registration:

Terminal
teams app doctor 33333333-3333-3333-3333-333333333333
Output
Diagnosing: Lunch Picker CLI (33333333-3333-3333-3333-333333333333)

Bot Registration
✔ Bot registered (33333333-3333-3333-3333-333333333333)
✔ Bot location: Teams (managed)
✔ Bot details fetchable
✔ Teams channel enabled
✔ Messaging mode: HTTP endpoint
✔ Endpoint: https://q856tzrv-3978.inc1.devtunnels.ms/api/messages
✔ Endpoint reachable

AAD App
✔ AAD app found (33333333-3333-3333-3333-333333333333)
✔ 1 active secret (nearest expiry: 11/26/2028)
ℹ Sign-in audience: AzureADMultipleOrgs

Manifest
✔ Bot ID matches app ID
✔ Endpoint domain in validDomains
✔ *.botframework.com in validDomains
ℹ webApplicationInfo not configured (SSO not set up)

No issues found.

Sign-in audience: AzureADMultipleOrgs confirms the multitenant app registration that makes Step 10 necessary. How to Register a Bot with the Teams Developer CLI covers the CLI on its own.

The Complete Code​

LunchAgent.cs is the one from Step 1, TenantFilterMiddleware.cs and Program.cs are the ones from Step 10, and the app package is from Step 7. The complete appsettings.json:

appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"AgentApplication": {
"StartTypingTimer": true
},
"AllowedTenants": [
"11111111-1111-1111-1111-111111111111"
],
"TokenValidation": {
"Audiences": [
"22222222-2222-2222-2222-222222222222"
],
"TenantId": "11111111-1111-1111-1111-111111111111"
},
"Connections": {
"ServiceConnection": {
"Settings": {
"AuthType": "ClientSecret",
"ClientId": "22222222-2222-2222-2222-222222222222",
"AuthorityEndpoint": "https://login.microsoftonline.com/11111111-1111-1111-1111-111111111111",
"Scopes": [
"https://api.botframework.com/.default"
]
}
}
},
"ConnectionsMap": [
{
"ServiceUrl": "*",
"Connection": "ServiceConnection"
}
],
"OutboundHostValidator": {
"Enabled": true,
"IncludeDefaultMicrosoftHosts": true
}
}

The client secret is in user secrets, and LunchPicker.csproj references Microsoft.Agents.Hosting.AspNetCore and Microsoft.Agents.Authentication.Msal, both version 1.9.205.

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 Lunch Picker in Teams: How to Uninstall an App in Microsoft Teams.

  3. Delete the bots in the Developer Portal's Bot management, Lunch Picker and Lunch Picker CLI if you tried the CLI: How to Delete a Bot in the Teams Developer Portal. Delete the CLI's app under Apps too.

  4. Delete the app registrations, which the portal doesn't delete with the bot: How to Delete an App Registration in Microsoft Entra ID.

  5. Delete the tunnel:

    Terminal
    devtunnel delete lunch-picker -f
    Output
    Deleted: lunch-picker.inc1
  6. 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​

  • Explain the three registrations a Teams agent has, and choose between a Teams-managed and an Azure-managed one.
  • Register a Teams-managed bot in the Developer Portal or with the Teams developer CLI, and give it a dev tunnel endpoint.
  • Configure the agent's identity with a ServiceConnection, and keep its secret in user secrets.
  • Validate every incoming token, also in Development, with forceEnable: true.
  • Limit the agent's replies to Microsoft's hosts with the outbound host validator.
  • Build a Teams app package, upload it, and chat with your agent in Teams.
  • Accept activities only from your own organization with a tenant middleware.

Common Mistakes​

MistakeWhat happensDo this instead
Using a temporary dev tunnelThe endpoint in the bot's registration breaks every time the tunnel restartsCreate a persistent tunnel
Leaving out forceEnable: trueAnyone with the tunnel URL can make your agent run and replyValidate tokens in Development too
Putting the client secret in appsettings.jsonThe secret ends up in source controlUse user secrets
A bot ID in the manifest that doesn't match the registrationTeams can't connect the app to your botUse the bot ID from Bot management in id and botId
Relying on the app registration's audience to keep other organizations outMicrosoft says it's no substitute for a check in codeKeep the tenant middleware

Troubleshooting​

SymptomLikely causeFix
Lunch Picker never answers, and the agent logs nothingThe tunnel isn't hosted, or the bot's endpoint has the wrong URLHost the tunnel, and compare its URL with the endpoint on Configure
The tunnel host prints ClientSSH: PortForwardingService connection to localhost:3978 failed: Connection refusedA request arrived while the agent wasn't runningStart the agent
The agent logs Ignored message from tenant …That tenant isn't in AllowedTenantsAdd the tenant ID, or check you used your own
No connections map found in configuration at startupThe ConnectionsMap section is missingAdd the ConnectionsMap section
401 for every request from TeamsTokenValidation:Audiences isn't your bot IDUse the bot ID from Bot management
Stopping a long-running tunnel host prints Error disposing host: … UnauthorizedThe host process couldn't clean up on its way out; it happened to me after a long sessionThe persistent tunnel is unaffected: host it again, or delete it with devtunnel delete

FAQ​

Do I need an Azure subscription for this?​

No. The bot registration is Teams-managed, and dev tunnels need only a sign-in. An Azure subscription comes in with an Azure-managed registration, which single sign-on needs, and when you deploy the agent to Azure.

Why did the welcome message say "there"?​

Teams' membersAdded list had no names when the app was installed, so FirstName used its fallback. The sender's name does arrive with each message, in from.name.

Can I keep the Playground for testing?​

Yes, but with these settings it needs the localhost exception for the outbound host validator, in appsettings.Development.json, and the Playground's authenticated mode, because the agent now rejects requests without a token.

Can colleagues use my Lunch Picker?​

Only while the agent and the tunnel run on your computer, and only people in your own organization, because of the tenant filter. Each colleague can upload the same package as a custom app, if they're allowed to. For everyone at once, a Teams admin can upload the package to the organization's app catalog, which Microsoft's admin documentation describes as Available to entire org.

Conclusion​

A Teams agent needs three registrations that share one ID: an app registration for its identity, a bot registration for its endpoint, and an app manifest to install it. With a Teams-managed bot, a persistent dev tunnel and a client secret in user secrets, Lunch Picker ran in real Teams, typing indicator included. And because its endpoint was public, it got the protections a production agent needs: token validation even in Development, replies only to Microsoft's hosts, and a tenant check that keeps every other organization out.

Next: Part 9: Universal Actions: Adaptive Cards That Update (coming soon). Part 5's cards answered with new messages. In Teams, a card can update itself in place, differently for each person who sees it.

Additional Resources​