m365-agents-dotnet について
m365-agents-dotnetは、Microsoft.Agents SDKでMicrosoft 365、Teams、Copilot Studio向けエージェントを開発する.NET開発者向けスキルです。ASP.NET Coreでのホスティング、ルーティング、MSAL認証の手法を扱います。
主な機能
- 01ASP.NET Coreでのエージェントホスティング
- 02AgentApplicationのルーティング案内
- 03MSAL認証パターン
- 04Copilot Studioクライアント連携
- 05本番環境のセキュリティ対策
活用シーン
- 01.NETでのMicrosoft 365エージェント開発
- 02ASP.NET Coreによるエージェントのホスティング
- 03.NETアプリとCopilot Studioの接続
MCP 対応
実装前にmicrosoft-docs MCPで最新のSDK APIを確認するよう案内します。MCPサーバーについての説明はありません。
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ sickn33/ agentic-awesome-skills --skill m365-agents-dotnetインストール後、Claude Code で/m365-agents-dotnetを入力して読み込まれたか確認します。
詳細
補足資料の利用可否
このカタログのコピーには、以下のインラインガイダンスが含まれていますが、次の補足パスは含まれていません。これらは外部の前提条件であり、同梱ファイルではありません。
<support-root>/references/acceptance-criteria.md
これらのパスに依存する手順を実行する前に、元の補足資料または既存のインストール環境を求めてください。このカタログには、検証済みのダウンロード元が記載されていません。各パスをそのインストール環境を基準に解決し、内容を確認したうえで、該当するライセンスと実行上の前提条件を検証してください。必要なファイルが存在することを確認するまでは、コマンドを実行したり、参照されている手順を実施したと主張したりしないでください。不足しているスクリプトを捏造したり、同じ名前の無関係なファイルを同等のものとして扱ったりしないでください。ここに完全な手順が記載されている独立したステップは、ユーザーが許可した範囲内で実行できます。依存するステップを利用できない場合は、その旨を報告してください。
Microsoft 365 Agents SDK (.NET)
概要
ASP.NET Core ホスティング、エージェントのルーティング、MSAL ベースの認証を利用して、Microsoft 365、Teams、Copilot Studio 向けのエンタープライズエージェントを構築します。
実装前
- microsoft-docs MCP を使用して、AddAgent、AgentApplication、認証オプションの最新 API を確認してください。
- 使用する予定の Microsoft.Agents.* パッケージのバージョンを NuGet で確認してください。
インストール
dotnet add package Microsoft.Agents.Hosting.AspNetCore
dotnet add package Microsoft.Agents.Authentication.Msal
dotnet add package Microsoft.Agents.Storage
dotnet add package Microsoft.Agents.CopilotStudio.Client
dotnet add package Microsoft.Identity.Client.Extensions.Msal
構成(appsettings.json)
{
"TokenValidation": {
"Enabled": true,
"Audiences": [
"{{ClientId}}"
],
"TenantId": "{{TenantId}}"
},
"AgentApplication": {
"StartTypingTimer": false,
"RemoveRecipientMention": false,
"NormalizeMentions": false
},
"Connections": {
"ServiceConnection": {
"Settings": {
"AuthType": "ClientSecret",
"ClientId": "{{ClientId}}",
"ClientSecret": "{{ClientSecret}}",
"AuthorityEndpoint": "https://login.microsoftonline.com/{{TenantId}}",
"Scopes": [
"https://api.botframework.com/.default"
]
}
}
},
"ConnectionsMap": [
{
"ServiceUrl": "*",
"Connection": "ServiceConnection"
}
],
"CopilotStudioClientSettings": {
"DirectConnectUrl": "",
"EnvironmentId": "",
"SchemaName": "",
"TenantId": "",
"AppClientId": "",
"AppClientSecret": ""
}
}
コアワークフロー:ASP.NET Core エージェントホスト
using Microsoft.Agents.Builder;
using Microsoft.Agents.Hosting.AspNetCore;
using Microsoft.Agents.Storage;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient();
builder.AddAgentApplicationOptions();
builder.AddAgent<MyAgent>();
builder.Services.AddSingleton<IStorage, MemoryStorage>();
builder.Services.AddControllers();
builder.Services.AddAgentAspNetAuthentication(builder.Configuration);
WebApplication app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/", () => "Microsoft Agents SDK Sample");
var incomingRoute = app.MapPost("/api/messages",
async (HttpRequest request, HttpResponse response, IAgentHttpAdapter adapter, IAgent agent, CancellationToken ct) =>
{
await adapter.ProcessAsync(request, response, agent, ct);
});
if (!app.Environment.IsDevelopment())
{
incomingRoute.RequireAuthorization();
}
else
{
app.Urls.Add("http://localhost:3978");
}
app.Run();
AgentApplication のルーティング
using Microsoft.Agents.Builder;
using Microsoft.Agents.Builder.App;
using Microsoft.Agents.Builder.State;
using Microsoft.Agents.Core.Models;
using System;
using System.Threading;
using System.Threading.Tasks;
public sealed class MyAgent : AgentApplication
{
public MyAgent(AgentApplicationOptions options) : base(options)
{
OnConversationUpdate(ConversationUpdateEvents.MembersAdded, WelcomeAsync);
OnActivity(ActivityTypes.Message, OnMessageAsync, rank: RouteRank.Last);
OnTurnError(OnTurnErrorAsync);
}
private static async Task WelcomeAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken ct)
{
foreach (ChannelAccount member in turnContext.Activity.MembersAdded)
{
if (member.Id != turnContext.Activity.Recipient.Id)
{
await turnContext.SendActivityAsync(
MessageFactory.Text("Welcome to the agent."),
ct);
}
}
}
private static async Task OnMessageAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken ct)
{
await turnContext.SendActivityAsync(
MessageFactory.Text($"You said: {turnContext.Activity.Text}"),
ct);
}
private static async Task OnTurnErrorAsync(
ITurnContext turnContext,
ITurnState turnState,
Exception exception,
CancellationToken ct)
{
await turnState.Conversation.DeleteStateAsync(turnContext, ct);
var endOfConversation = Activity.CreateEndOfConversationActivity();
endOfConversation.Code = EndOfConversationCodes.Error;
endOfConversation.Text = exception.Message;
await turnContext.SendActivityAsync(endOfConversation, ct);
}
}
Copilot Studio のダイレクト・ツー・エンジン クライアント
トークン取得用 DelegatingHandler(対話型フロー)
using System.Net.Http.Headers;
using Microsoft.Agents.CopilotStudio.Client;
using Microsoft.Identity.Client;
internal sealed class AddTokenHandler : DelegatingHandler
{
private readonly SampleConnectionSettings _settings;
public AddTokenHandler(SampleConnectionSettings settings) : base(new HttpClientHandler())
{
_settings = settings;
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (request.Headers.Authorization is null)
{
string[] scopes = [CopilotClient.ScopeFromSettings(_settings)];
IPublicClientApplication app = PublicClientApplicationBuilder
.Create(_settings.AppClientId)
.WithAuthority(AadAuthorityAudience.AzureAdMyOrg)
.WithTenantId(_settings.TenantId)
.WithRedirectUri("http://localhost")
.Build();
AuthenticationResult authResponse;
try
{
var account = (await app.GetAccountsAsync()).FirstOrDefault();
authResponse = await app.AcquireTokenSilent(scopes, account).ExecuteAsync(cancellationToken);
}
catch (MsalUiRequiredException)
{
authResponse = await app.AcquireTokenInteractive(scopes).ExecuteAsync(cancellationToken);
}
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResponse.AccessToken);
}
return await base.SendAsync(request, cancellationToken);
}
}
CopilotClient を使用したコンソールホスト
using Microsoft.Agents.CopilotStudio.Client;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
var settings = new SampleConnectionSettings(
builder.Configuration.GetSection("CopilotStudioClientSettings"));
builder.Services.AddHttpClient("mcs").ConfigurePrimaryHttpMessageHandler(() =>
{
return new AddTokenHandler(settings);
});
builder.Services
.AddSingleton(settings)
.AddTransient<CopilotClient>(sp =>
{
var logger = sp.GetRequiredService<ILoggerFactory>().CreateLogger<CopilotClient>();
return new CopilotClient(settings, sp.GetRequiredService<IHttpClientFactory>(), logger, "mcs");
});
IHost host = builder.Build();
var client = host.Services.GetRequiredService<CopilotClient>();
await foreach (var activity in client.StartConversationAsync(emitStartConversationEvent: true))
{
Console.WriteLine(activity.Type);
}
await foreach (var activity in client.AskQuestionAsync("Hello!", null))
{
Console.WriteLine(activity.Type);
}
ベストプラクティス
- AgentApplication のサブクラスを使用して、ルーティングとエラー処理を一元化します。
- MemoryStorage は開発時のみ使用し、本番環境では永続化ストレージを使用します。
- 本番環境では TokenValidation を有効にし、/api/messages で認証を必須にします。
- 認証シークレットは構成プロバイダー(Key Vault、マネージド ID、環境変数)に保管します。
- IHttpClientFactory の HttpClient を再利用し、MSAL トークンをキャッシュします。
- 非同期ハンドラーを優先し、SDK 呼び出しに CancellationToken を渡します。
参照ファイル
| ファイル | 内容 |
|---|---|
| references/acceptance-criteria.md | インポートパス、ホスティングパイプライン、Copilot Studio クライアントのパターン、アンチパターン |
参照リンク
使用する場合
このスキルは、概要で説明されているワークフローまたはアクションを実行する場合に適用できます。
制限事項
- このスキルは、タスクが上記の範囲に明確に該当する場合にのみ使用してください。
- 出力を、環境固有の検証、テスト、または専門家によるレビューの代替として扱わないでください。
- 必要な入力、権限、安全上の境界、または成功基準が不足している場合は、作業を中断して確認を求めてください。