Skip to content

Add TeamsExtension sample #219

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 39 commits into from
Jun 10, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
f378598
Add TeamsExtension sample
rido-min Apr 22, 2025
46317a7
Merge branch 'main' into users/rido/teams-samples
rido-min Apr 22, 2025
9400b77
Return Card on Selected Item
rido-min Apr 25, 2025
b2387f2
Merge branch 'main' into users/rido/teams-samples
rido-min Apr 25, 2025
455d362
Add NuGetPackageName check and update cardValue formatting
rido-min Apr 28, 2025
5b2d4ab
Merge branch 'users/rido/teams-samples' of https://github.com/microso…
rido-min Apr 28, 2025
3964448
check commandId
rido-min Apr 28, 2025
01637ed
Merge branch 'main' into users/rido/teams-samples
rido-min Apr 29, 2025
4efec1c
merge
rido-min May 5, 2025
2efb444
add Teams Sample to SLN
rido-min May 5, 2025
bd592bc
fix ns
rido-min May 5, 2025
f8ca766
Merge branch 'main' into users/rido/teams-samples
rido-min May 6, 2025
5f0577c
apply code style to teamsagent sample
rido-min May 6, 2025
7f62f93
Merge branch 'users/rido/teams-samples' of https://github.com/microso…
rido-min May 6, 2025
b47598f
Merge branch 'main' into users/rido/teams-samples
rido-min May 6, 2025
22aab35
Merge branch 'main' of https://github.com/microsoft/Agents-for-net in…
rido-min May 7, 2025
cb25cb8
Merge branch 'main' into users/rido/teams-samples
rido-min May 8, 2025
e2a3927
Merge branch 'users/rido/teams-samples' of https://github.com/microso…
rido-min May 8, 2025
08824e9
rm TeamsApplicationOptions
rido-min May 8, 2025
3927793
Merge branch 'main' of https://github.com/microsoft/Agents-for-net in…
rido-min May 8, 2025
c0be831
rm allowedcallers from aspnetExt
rido-min May 8, 2025
82cd143
Merge branch 'main' into users/rido/teams-samples
rido-min May 9, 2025
651b425
Merge branch 'main' of https://github.com/microsoft/Agents-for-net in…
rido-min May 13, 2025
4d3e7c4
merging
rido-min May 13, 2025
fcb461e
add teams sample to sln
rido-min May 13, 2025
445c6c2
Merge branch 'main' of https://github.com/microsoft/Agents-for-net in…
rido-min May 13, 2025
afe4cd7
Merge branch 'main' into users/rido/teams-samples
rido-min May 14, 2025
1fa65cd
Merge branch 'main' of https://github.com/microsoft/Agents-for-net in…
rido-min May 14, 2025
6e095b5
test attachments
rido-min May 16, 2025
a892f36
merging from main
rido-min May 16, 2025
637d12e
add teams agent sample to the sln
rido-min May 16, 2025
5f73efb
Merge remote-tracking branch 'origin' into users/rido/teams-samples
rido-min May 27, 2025
e86a813
Enhance build configs and improve error handling
rido-min May 27, 2025
cd01432
Add OnQueryLink handler for message extensions
rido-min May 28, 2025
d90be87
Merge branch 'main' of https://github.com/microsoft/Agents-for-net in…
rido-min May 28, 2025
ed3665b
Merge branch 'main' into users/rido/teams-samples
rido-min May 30, 2025
3969454
Merge branch 'main' into users/rido/teams-samples
rido-min Jun 3, 2025
8d2adca
Merge branch 'main' into users/rido/teams-samples
rido-min Jun 9, 2025
f43c3bc
Merge branch 'main' into users/rido/teams-samples
MattB-msft Jun 10, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/Microsoft.Agents.SDK.sln
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Authorization", "Authorizat
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ManualSignIn", "samples\Authorization\ManualSignIn\ManualSignIn.csproj", "{72503E70-31C3-82E3-1E1D-52A6B0C5A808}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Teams", "Teams", "{6162C41F-018F-4564-91B3-E89C02E5E77C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TeamsAgent", "samples\Teams\TeamsAgent\TeamsAgent.csproj", "{94FCA3BC-0A7A-4F09-B237-D5C73CF521A0}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -304,6 +308,10 @@ Global
{72503E70-31C3-82E3-1E1D-52A6B0C5A808}.Debug|Any CPU.Build.0 = Debug|Any CPU
{72503E70-31C3-82E3-1E1D-52A6B0C5A808}.Release|Any CPU.ActiveCfg = Release|Any CPU
{72503E70-31C3-82E3-1E1D-52A6B0C5A808}.Release|Any CPU.Build.0 = Release|Any CPU
{94FCA3BC-0A7A-4F09-B237-D5C73CF521A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{94FCA3BC-0A7A-4F09-B237-D5C73CF521A0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{94FCA3BC-0A7A-4F09-B237-D5C73CF521A0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{94FCA3BC-0A7A-4F09-B237-D5C73CF521A0}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -366,6 +374,8 @@ Global
{2D522479-7808-6236-5B86-F9653C2F2D0A} = {AD743B78-D61F-4FBF-B620-FA83CE599A50}
{0F9D3F0D-C131-4D3B-A86F-59CC781E8A02} = {674A812C-7287-4883-97F9-697D83750648}
{72503E70-31C3-82E3-1E1D-52A6B0C5A808} = {0F9D3F0D-C131-4D3B-A86F-59CC781E8A02}
{6162C41F-018F-4564-91B3-E89C02E5E77C} = {674A812C-7287-4883-97F9-697D83750648}
{94FCA3BC-0A7A-4F09-B237-D5C73CF521A0} = {6162C41F-018F-4564-91B3-E89C02E5E77C}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {F1E8E538-309A-46F8-9CE7-AEC6589FAE60}
Expand Down
32 changes: 14 additions & 18 deletions src/samples/Shared/AspNetExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Microsoft.Agents.Samples;
Expand Down Expand Up @@ -64,12 +65,12 @@ public static class AspNetExtensions
/// `AzureBotServiceTokenHandling` defaults to true and should always be true until Azure Bot Service sends Entra ID token.
/// `AllowedCallers` is optional and defaults to "*". Otherwise, a list of AppId's the Agent will accept requests from.
/// </remarks>
public static void AddAgentAspNetAuthentication(this IServiceCollection services, IConfiguration configuration, string tokenValidationSectionName = "TokenValidation", ILogger logger = null)
public static void AddAgentAspNetAuthentication(this IServiceCollection services, IConfiguration configuration, string tokenValidationSectionName = "TokenValidation", ILogger logger = null!)
{
IConfigurationSection tokenValidationSection = configuration.GetSection(tokenValidationSectionName);
List<string> validTokenIssuers = tokenValidationSection.GetSection("ValidIssuers").Get<List<string>>();
List<string> allowedCallers = tokenValidationSection.GetSection("AllowedCallers").Get<List<string>>();
List<string> audiences = tokenValidationSection.GetSection("Audiences").Get<List<string>>();
List<string> validTokenIssuers = tokenValidationSection.GetSection("ValidIssuers")!.Get<List<string>>()!;
List<string> allowedCallers = tokenValidationSection.GetSection("AllowedCallers")!.Get<List<string>>()!;
List<string> audiences = tokenValidationSection.GetSection("Audiences")!.Get<List<string>>()!;

if (!tokenValidationSection.Exists())
{
Expand All @@ -91,7 +92,7 @@ public static void AddAgentAspNetAuthentication(this IServiceCollection services
"https://login.microsoftonline.com/69e9b82d-4842-4902-8d1e-abc5b98a55e8/v2.0",
];

string tenantId = tokenValidationSection["TenantId"];
string tenantId = tokenValidationSection["TenantId"]!;
if (!string.IsNullOrEmpty(tenantId))
{
validTokenIssuers.Add(string.Format(CultureInfo.InvariantCulture, AuthenticationConstants.ValidTokenIssuerUrlTemplateV1, tenantId));
Expand All @@ -108,14 +109,14 @@ public static void AddAgentAspNetAuthentication(this IServiceCollection services
bool azureBotServiceTokenHandling = tokenValidationSection.GetValue("AzureBotServiceTokenHandling", true);

// If the `AzureBotServiceOpenIdMetadataUrl` setting is not specified, use the default based on `IsGov`. This is what is used to authenticate ABS tokens.
string azureBotServiceOpenIdMetadataUrl = tokenValidationSection["AzureBotServiceOpenIdMetadataUrl"];
string azureBotServiceOpenIdMetadataUrl = tokenValidationSection["AzureBotServiceOpenIdMetadataUrl"]!;
if (string.IsNullOrEmpty(azureBotServiceOpenIdMetadataUrl))
{
azureBotServiceOpenIdMetadataUrl = isGov ? AuthenticationConstants.GovAzureBotServiceOpenIdMetadataUrl : AuthenticationConstants.PublicAzureBotServiceOpenIdMetadataUrl;
}

// If the `OpenIdMetadataUrl` setting is not specified, use the default based on `IsGov`. This is what is used to authenticate Entra ID tokens.
string openIdMetadataUrl = tokenValidationSection["OpenIdMetadataUrl"];
string openIdMetadataUrl = tokenValidationSection["OpenIdMetadataUrl"]!;
if (string.IsNullOrEmpty(openIdMetadataUrl))
{
openIdMetadataUrl = isGov ? AuthenticationConstants.GovOpenIdMetadataUrl : AuthenticationConstants.PublicOpenIdMetadataUrl;
Expand Down Expand Up @@ -166,7 +167,7 @@ public static void AddAgentAspNetAuthentication(this IServiceCollection services
return;
}

string[] parts = authorizationHeader?.Split(' ');
string[] parts = authorizationHeader?.Split(' ')!;
if (parts.Length != 2 || parts[0] != "Bearer")
{
// Default to AadTokenValidation handling
Expand All @@ -176,7 +177,7 @@ public static void AddAgentAspNetAuthentication(this IServiceCollection services
}

JwtSecurityToken token = new(parts[1]);
string issuer = token.Claims.FirstOrDefault(claim => claim.Type == AuthenticationConstants.IssuerClaim)?.Value;
string issuer = token.Claims.FirstOrDefault(claim => claim.Type == AuthenticationConstants.IssuerClaim)?.Value!;

if (azureBotServiceTokenHandling && AuthenticationConstants.BotFrameworkTokenIssuer.Equals(issuer))
{
Expand Down Expand Up @@ -222,14 +223,9 @@ public static void AddAgentAspNetAuthentication(this IServiceCollection services
});
}

class AllowedCallersPolicy : IAuthorizationHandler, IAuthorizationRequirement
class AllowedCallersPolicy(IList<string> allowedCallers) : IAuthorizationHandler, IAuthorizationRequirement
{
private readonly IList<string> _allowedCallers;

public AllowedCallersPolicy(IList<string> allowedCallers)
{
_allowedCallers = allowedCallers ?? [];
}
private readonly IList<string> _allowedCallers = allowedCallers ?? [];

public Task HandleAsync(AuthorizationHandlerContext context)
{
Expand All @@ -239,7 +235,7 @@ public Task HandleAsync(AuthorizationHandlerContext context)
return Task.CompletedTask;
}

var claims = context.User.Claims.ToList();
List<Claim> claims = [.. context.User.Claims];

// allow ABS
var issuer = claims.SingleOrDefault(claim => claim.Type == AuthenticationConstants.IssuerClaim);
Expand All @@ -254,7 +250,7 @@ public Task HandleAsync(AuthorizationHandlerContext context)
party ??= claims.SingleOrDefault(claim => claim.Type == AuthenticationConstants.AppIdClaim);

// party must be in allowed list
var isAllowed = party != null && _allowedCallers.Where(allowed => allowed == party.Value).Any();
bool isAllowed = party != null && _allowedCallers.Where(allowed => allowed == party.Value).Any();
if (isAllowed)
{
context.Succeed(this);
Expand Down
136 changes: 136 additions & 0 deletions src/samples/Teams/TeamsAgent/MyAgent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
using AdaptiveCards.Rendering;
using Microsoft.Agents.Builder;
using Microsoft.Agents.Builder.App;
using Microsoft.Agents.Builder.App.AdaptiveCards;
using Microsoft.Agents.Builder.State;
using Microsoft.Agents.Core.Models;
using Microsoft.Agents.Core.Serialization;
using Microsoft.Agents.Extensions.Teams.App;
using Microsoft.Agents.Extensions.Teams.Connector;
using Microsoft.Agents.Extensions.Teams.Models;
using System.Text.Json;
using System.Text.Json.Nodes;

namespace TeamsAgent
{
public class MyAgent : AgentApplication
{
public MyAgent(AgentApplicationOptions options) : base(options)
{
RegisterExtension(new TeamsAgentExtension(this), tae =>
{
tae.OnMessageEdit(MessageEdited);
tae.MessageExtensions.OnSelectItem(OnSelectItem);
tae.MessageExtensions.OnQuery("findNuGetPackage", OnQuery);
});
OnMessageReactionsAdded(OnMessageReaction);
OnConversationUpdate(ConversationUpdateEvents.MembersAdded, WelcomeMessageAsync);
OnActivity(ActivityTypes.Message, OnMessageAsync);
}

private async Task<MessagingExtensionResult> OnSelectItem(ITurnContext turnContext, ITurnState turnState, object item, CancellationToken cancellationToken)
{
string jsonItem = JsonSerializer.Serialize(item);
await turnContext.SendActivityAsync("select item " + jsonItem, cancellationToken: cancellationToken);
return new MessagingExtensionResult() { ActivityPreview = new Activity() { Type = ActivityTypes.Message, Text = jsonItem } };
}

private async Task<MessagingExtensionResult> OnQuery(ITurnContext turnContext, ITurnState turnState, Query<IDictionary<string, object>> query, CancellationToken cancellationToken)
{

JsonElement el = query.Parameters.TryGetValue<JsonElement>("NuGetPackageName");

string text = el.GetString() ?? string.Empty;


IEnumerable<PackageItem> packages = await FindPackages(text);
List<MessagingExtensionAttachment> attachments = [.. packages.Select(package =>
{
string cardValue = $"{{\"packageId\": \"{package.Id}\", \"version\": \"{package.Version}\", \"description\": \"{PackageItem.NormalizeString(package.Description!)}\", \"projectUrl\": \"{package.ProjectUrl}\", \"iconUrl\": \"{package.IconUrl}\"}}";

ThumbnailCard previewCard = new() { Title = package.Id, Tap = new CardAction { Type = "invoke", Value = cardValue } };
if (!string.IsNullOrEmpty(package.IconUrl))
{
previewCard.Images = [new CardImage(package.IconUrl, "Icon")];
}

MessagingExtensionAttachment attachment = new()
{
ContentType = HeroCard.ContentType,
Content = new HeroCard { Title = package.Id },
Preview = previewCard.ToAttachment()
};

return attachment;
})];

return new MessagingExtensionResult
{
Type = "result",
AttachmentLayout = "list",
Attachments = attachments

};
}

private static async Task<IEnumerable<PackageItem>> FindPackages(string text)
{
JsonNode? obj = JsonObject.Parse(await new HttpClient().GetStringAsync($"https://azuresearch-usnc.nuget.org/query?q=id:{text}&prerelease=true"));
List<JsonObject> items = ProtocolJsonSerializer.ToObject<List<JsonObject>>(obj?["data"]!);
return items.Select(item => new PackageItem()
{
Id = item["id"]?.ToString(),
Version = item["version"]?.ToString(),
Description = item["description"]?.ToString(),
ProjectUrl = item["projectUrl"]?.ToString(),
IconUrl = item["iconUrl"]?.ToString()
});
}

private async Task OnMessageReaction(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
await turnContext.SendActivityAsync("Message Reaction" + turnContext.Activity.ReactionsAdded[0].Type, cancellationToken: cancellationToken);
}

private async Task MessageEdited(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
await turnContext.SendActivityAsync("Message Edited", cancellationToken: cancellationToken);
}

private async Task WelcomeMessageAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
foreach (ChannelAccount member in turnContext.Activity.MembersAdded)
{
if (member.Id != turnContext.Activity.Recipient.Id)
{
await turnContext.SendActivityAsync(MessageFactory.Text("Hello and Welcome!"), cancellationToken);
}
}
}

private async Task OnMessageAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
TeamsChannelAccount member = await TeamsInfo.GetMemberAsync(turnContext, turnContext.Activity.From.Id, cancellationToken);
await turnContext.SendActivityAsync(member.Email, cancellationToken: cancellationToken);

}
}

class PackageItem
{
public string? Id;
public string? Version;
public string? Description;
public string? ProjectUrl;
public string? IconUrl;

public static string NormalizeString(string value)
{
return value
.Replace("\r\n", " ")
.Replace("\r", " ")
.Replace("\n", " ")
.Replace("\"", "\\\"");
}
}
}
27 changes: 27 additions & 0 deletions src/samples/Teams/TeamsAgent/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using Microsoft.Agents.Builder;
using Microsoft.Agents.Hosting.AspNetCore;
using Microsoft.Agents.Samples;
using Microsoft.Agents.Storage;
using TeamsAgent;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddHttpClient();
builder.Logging.AddConsole();

builder.Services.AddAgentAspNetAuthentication(builder.Configuration);

builder.AddAgentApplicationOptions();

builder.AddAgent<MyAgent>();

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

var app = builder.Build();

app.MapPost("/api/messages", async (HttpRequest request, HttpResponse response, IAgentHttpAdapter adapter, IAgent agent, CancellationToken cancellationToken) =>
{
await adapter.ProcessAsync(request, response, agent, cancellationToken);
});
app.Run();
15 changes: 15 additions & 0 deletions src/samples/Teams/TeamsAgent/TeamsAgent.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\libraries\Authentication\Authentication.Msal\Microsoft.Agents.Authentication.Msal.csproj" />
<ProjectReference Include="..\..\..\libraries\Extensions\Microsoft.Agents.Extensions.Teams\Microsoft.Agents.Extensions.Teams.csproj" />
<ProjectReference Include="..\..\..\libraries\Hosting\AspNetCore\Microsoft.Agents.Hosting.AspNetCore.csproj" />
</ItemGroup>

</Project>
9 changes: 9 additions & 0 deletions src/samples/Teams/TeamsAgent/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Loading
Loading