Microsoft.Teams.Apps
2.2.1
Prefix Reserved
dotnet add package Microsoft.Teams.Apps --version 2.2.1
NuGet\Install-Package Microsoft.Teams.Apps -Version 2.2.1
<PackageReference Include="Microsoft.Teams.Apps" Version="2.2.1" />
<PackageVersion Include="Microsoft.Teams.Apps" Version="2.2.1" />
<PackageReference Include="Microsoft.Teams.Apps" />
paket add Microsoft.Teams.Apps --version 2.2.1
#r "nuget: Microsoft.Teams.Apps, 2.2.1"
#:package Microsoft.Teams.Apps@2.2.1
#addin nuget:?package=Microsoft.Teams.Apps&version=2.2.1
#tool nuget:?package=Microsoft.Teams.Apps&version=2.2.1
Microsoft.Teams.Apps
A high-level framework for building Microsoft Teams bots in .NET. Built on top of Microsoft.Teams.Core, it provides Teams-specific activity types, a typed routing and handler system, OAuth authentication flows, Teams API clients, and streaming message support.
Key Features
- Typed Activity Routing — Register handlers for specific activity types (
OnMessage,OnAdaptiveCardAction,OnQuery, etc.) with type-safe contexts - Teams Activity Schema — Rich type hierarchy (
MessageActivity,InvokeActivity<T>,ConversationUpdateActivity, etc.) with polymorphic deserialization - OAuth Flows — Built-in SSO token exchange, sign-in cards, and token management via
OAuthFlow - Teams API Clients — Typed clients for conversations, members, teams, channels, meetings, and batch operations
- Streaming Messages — Progressive response updates via
TeamsStreamingWriter - Plans (experimental) — Explicit, prompt-bound progress and completion via standalone
Plan - Conversation Helpers — Send, reply, quote, and typing helpers for reactive and proactive messaging
- Turn State — Conversation and user state backed by
IDistributedCache - Targeted Messages — Send messages visible only to a selected participant in supported conversations
- Observability — OpenTelemetry spans, metrics, and Agent 365 baggage propagation
- Fluent Configuration — Chainable handler registration and options-based service configuration
- Socket Mode — Receive activities over an outbound WebSocket during development, with no public endpoint or tunnel
Installation
dotnet add package Microsoft.Teams.Apps
Quick Start
using Microsoft.Teams.Apps;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTeamsBotApplication();
var app = builder.Build();
var teams = app.UseTeamsBotApplication(); // maps POST /api/messages
teams.OnMessage(async (context, ct) =>
{
await context.SendAsync($"You said: {context.Activity.Text}", ct);
});
app.Run();
Handler Registration
Handlers are registered as extension methods on TeamsBotApplication and can be chained:
Messages
// All messages
teams.OnMessage(async (context, ct) => { ... });
// Regex pattern match
teams.OnMessage(@"^help$", async (context, ct) =>
{
await context.SendAsync("Here's how to use the bot...", ct);
});
Conversation Helpers
teams.OnMessage(async (context, ct) =>
{
await context.TypingAsync(ct);
await context.ReplyAsync("This reply quotes the incoming message.", ct);
await context.QuoteAsync(context.Activity.Id!, "Explicitly quoted reply.", ct);
});
Invoke Activities
// Adaptive card actions
teams.OnAdaptiveCardAction(async (context, ct) =>
{
var value = context.Activity.Value;
return AdaptiveCardResponse.CreateMessageResponse("Action received.");
});
// Message extension search
teams.OnQuery(async (context, ct) =>
{
var query = context.Activity.Value;
var searchText = query?.Parameters
.FirstOrDefault(parameter => parameter.Name == "queryText")?
.Value;
return MessageExtensionResponse.CreateBuilder()
.WithType(MessageExtensionResponseTypes.Message)
.WithText($"Searching for: {searchText}")
.Build();
});
// Task modules
teams.OnFetchTask(async (context, ct) => { ... });
teams.OnTaskSubmit(async (context, ct) => { ... });
// Link unfurling
teams.OnQueryLink(async (context, ct) => { ... });
Other message extension handlers include OnSubmitAction, OnSelectItem,
OnAnonQueryLink, OnQuerySettingUrl, OnSetting, and
OnCardButtonClicked.
Plans (experimental)
Opt in with <NoWarn>$(NoWarn);ExperimentalTeamsPlan</NoWarn> in your project.
Create a standalone helper; Context does not own or automatically complete a plan.
using Microsoft.Teams.Apps.Schema.Entities;
var plan = Plan.CreateFromContext(context);
await plan.StartAsync([
new PlanStep { Id = "lookup", Version = 1, Title = "Find sources", Status = PlanStepStatuses.Active }
], ct);
await plan.UpdateAsync([
new PlanStep { Id = "lookup", Version = 2, Title = "Find sources", Status = PlanStepStatuses.Completed }
], ct);
await plan.CompleteAsync("The answer is ready.", ct);
Applications own stable step IDs and increment versions for every change, including sources
and descriptions. Updates affect only supplied steps; the helper does not merge or cache history.
StartAsync, UpdateAsync, StopAsync, and ErrorAsync POST typing activities. CompleteAsync
POSTs a message, preserves caller content without mutation, and returns its send response.
Sent fires only after successful sends; typing acknowledgements have no message response.
For delayed work, serialize a PlanOptions with ConversationId (including any thread suffix)
and ReplyToId, then reconstruct with new Plan(scopedApiClient, options).
Both options and helper serialization include only those two IDs. The already service-scoped
client is supplied separately at runtime; do not persist a Context or credentials.
Streaming stays with TeamsStreamingWriter. plan.Completion() builds a fresh final message
with completion metadata and the Plan's originating prompt; it does not send anything.
Use a writer targeting the same conversation and attach any final cards or citations to that message:
await writer.FinalizeResponseAsync(plan.Completion(), ct);
An explicit final ReplyToId is preserved; when absent, it defaults to the writer's originating prompt.
Targeted Plan scenarios are not supported: Plan activities use ordinary create routing,
and Completion() does not inherit targeting from the originating context.
Plan completion cannot use the writer's ordinary PUT timeout fallback: it throws
TimeoutException and discards the failed cycle. Recover with a separate Plan.CompleteAsync
message containing the full response and metadata using the right binding. Further finalization
calls do nothing; the next append or informative update starts a fresh stream and clears TimedOut.
HTTP 409 with exact error.code: PlanConflict instead throws Microsoft.Teams.Core.PlanConflictException
(an HttpRequestException). Core classifies it once; Plan lifecycle calls and streaming propagate
it unchanged, as do direct Core client calls. It exposes StatusCode,
ErrorCode, ErrorMessage, and the raw ResponseBody, with the original HTTP failure as
InnerException. It is not retried or treated as a timeout; a rejected Plan-bearing final message
retires the writer's cycle before rethrowing, so explicit repeated finalization sends nothing.
Do not blindly complete again after a service rejection. Other HTTP failures retain their ordinary exception behavior.
See PlanBot for all lifecycle calls, sources, and delayed continuation.
State and OAuth
Enable distributed turn state and register OAuth flows when adding the application:
builder.Services.AddTeamsBotApplication(options =>
{
options.UseState();
options.AddOAuthFlow("graph");
});
UseState() uses an in-memory IDistributedCache by default. Register another
IDistributedCache implementation, such as Redis, for state that must survive
process restarts or be shared across instances.
Socket Mode
Socket Mode receives activities over outbound WebSocket connections that the bot opens to the Teams service, instead of an HTTP messaging endpoint, so there is no public URL or dev tunnel to expose. Only inbound delivery changes: handlers and outbound sends work the same way.
WebSocket is only recommended for use when developing agents. Socket Mode bots should not be submitted to Marketplace for publishing.
Socket Mode is experimental, and its API may change. UseSocketMode and SocketModeOptions report the
ExperimentalTeamsSocketMode diagnostic, which fails the build until you suppress it, for example with
<NoWarn>$(NoWarn);ExperimentalTeamsSocketMode</NoWarn> in the project file.
Socket Mode runs on a generic host with no web server:
using Microsoft.Extensions.Hosting;
using Microsoft.Teams.Apps;
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddTeamsBotApplication(options => options.UseSocketMode());
var host = builder.Build();
var teams = host.UseTeamsBotApplication();
teams.OnMessage(async (context, ct) =>
{
await context.ReplyAsync($"You said: {context.Activity.Text}", ct);
});
host.Run();
- One connection per geo — The bot connects to
amer,emea, andapacby default. Startup waits until every geo is ready and fails if any geo cannot connect within 30 seconds. Dropped connections reconnect automatically, and connection tokens are rotated before they expire. - No web server —
UseSocketModeis the only switch;UseTeamsBotApplication()is the same call for both transports. With Socket Mode enabled it throws on aWebApplication, and a host that includes a web server fails to start. Tabs, OAuth callbacks, health endpoints, and other HTTP routes are unavailable. - Public cloud only — Registration fails for bots configured for another cloud.
- Classic bot identity only — The connection is negotiated with the bot's app ID and credentials. Agentic identities are not supported.
- Rejected credentials are not retried — If negotiation returns HTTP 401 or 403, startup fails immediately. After startup, the affected geo stops reconnecting until the app restarts.
- Throttling respects the service — On HTTP 429, the service's
Retry-Afterdelay takes precedence over reconnect backoff. - Idempotent handlers — The service can redeliver an activity, for example after a reconnect, so handlers should tolerate running more than once for the same activity.
Subscribe to teams.SocketMode.Events.Ready, .Disconnected, and .Reconnected before starting the host
to observe each geo's socket lifecycle. Ready carries the geo and ready frame and fires for each ready
connection, including token rotation. Disconnected carries the geo, error, and Terminal flag: automatic
recovery continues unless negotiation rejects the bot with HTTP 401/403. A terminal event means credentials
or access must be fixed and the app restarted. Reconnected fires after readiness when delivery resumes
following an unexpected interruption, not an uninterrupted rotation. Initial startup failures are thrown
from host startup; normal shutdown does not raise a disconnect event.
These events are experimental and observational. Handlers run synchronously, may run concurrently across
geos, and should be short and thread-safe. Observer failures are logged without interrupting delivery or
other observers. SocketMode is null when Socket Mode is disabled. Read-only diagnostics are available through
SocketMode.Status (aggregate), SocketMode.GeoStatuses (a per-geo snapshot), and SocketMode.GeoList.
Negotiation failures expose SocketModeNegotiateException.StatusCode, .RetryAfter (a nullable TimeSpan),
and .IsAuthError for HTTP 401/403. Downstream SignalR negotiation errors are not classified as terminal
service-negotiation rejections.
UseSocketMode(configure) accepts a SocketModeOptions callback to change only Geos.
Use this setting to target specific geos from the three defaults: amer, emea, and apac.
An empty geo list uses all three defaults.
Each geo's resolved connect/negotiate URL is logged at Information level during startup
under Microsoft.Teams.Apps.SocketMode.SocketModeTransport. The SignalR URL returned by negotiation is used unchanged.
Startup and readiness timeouts and reconnect backoff are managed internally by the SDK.
Keep-alive and server timeout use the SignalR client defaults of 15 and 30 seconds, respectively.
UseSocketMode(bool) turns Socket Mode on with the defaults, or off with false, which clears any earlier
configuration so the bot uses HTTP.
Main Types
| Type | Description |
|---|---|
TeamsBotApplication |
Main entry point — extends BotApplication with Teams-specific routing and features |
Context<TActivity> |
Per-turn context providing typed activity access, API clients, and helper methods |
TeamsActivity |
Base Teams activity with polymorphic deserialization into specific subtypes |
MessageActivity |
Text and attachment messages |
InvokeActivity<T> |
Invoke operations (adaptive cards, task modules, message extensions) |
ConversationUpdateActivity |
Membership, channel, and team lifecycle events |
OAuthFlow |
OAuth sign-in, token exchange (SSO), and sign-out management |
ApiClient |
Facade for Teams conversation, member, team, meeting, and bot APIs |
TeamsStreamingWriter |
Progressive message streaming with rate limiting |
Plan |
Experimental standalone prompt-bound progress and explicit completion |
MessageActivityInput |
Fluent outbound message model for text, cards, mentions, citations, and actions |
TurnStateContainer |
Per-turn access to conversation and user state |
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Microsoft.AspNetCore.SignalR.Client (>= 10.0.13)
- Microsoft.Teams.Core (>= 2.2.1)
- OpenTelemetry.Api (>= 1.15.3)
-
net8.0
- Microsoft.AspNetCore.SignalR.Client (>= 8.0.32)
- Microsoft.Teams.Core (>= 2.2.1)
- OpenTelemetry.Api (>= 1.15.3)
NuGet packages (11)
Showing the top 5 NuGet packages that depend on Microsoft.Teams.Apps:
| Package | Downloads |
|---|---|
|
Microsoft.Teams.Extensions.Hosting
Teams Hosting Extensions |
|
|
Microsoft.Teams.Extensions.Configuration
Teams Configuration Extensions |
|
|
Microsoft.Teams.Plugins.AspNetCore
Teams AspNetCore Plugin |
|
|
Microsoft.Teams.Plugins.AspNetCore.BotBuilder
Teams AspNetCore BotBuilder Plugin |
|
|
Microsoft.Teams.Plugins.AspNetCore.DevTools
[DEPRECATED] Teams AspNetCore DevTools Plugin. Use Microsoft 365 Agents Playground instead. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 2.2.1 | 619 | 11/10/2026 |
| 2.2.0 | 2,174 | 11/6/2026 |
| 2.1.2 | 13,420 | 10/16/2026 |
| 2.1.1 | 25,242 | 9/22/2026 |
| 2.1.0 | 34,581 | 8/3/2026 |
| 2.1.0-preview-0011 | 421 | 7/13/2026 |
| 2.1.0-preview-0010 | 136 | 7/7/2026 |
| 2.1.0-preview-0009 | 135 | 6/30/2026 |
| 2.1.0-preview-0008 | 174 | 6/26/2026 |
| 2.1.0-preview-0007 | 196 | 6/5/2026 |
| 2.1.0-preview-0006 | 142 | 5/28/2026 |
| 2.1.0-preview-0002 | 195 | 5/15/2026 |
| 2.0.9 | 27,069 | 6/5/2026 |
| 2.0.8 | 3,844 | 5/28/2026 |
| 2.0.7 | 9,161 | 5/15/2026 |
| 2.0.6 | 14,192 | 4/2/2026 |
| 2.0.6-preview-0046-g482dcafac4 | 288 | 4/2/2026 |
| 2.0.6-preview-0014 | 445 | 3/11/2026 |
| 2.0.6-preview-0010 | 316 | 2/25/2026 |
| 2.0.5 | 33,335 | 12/10/2025 |