Created
March 1, 2026 07:28
-
-
Save vman/97fe97177b8f1f950c0beaacbd5815fd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using Microsoft.Agents.CopilotStudio.Client; | |
| using Microsoft.Extensions.DependencyInjection; | |
| using Microsoft.Extensions.Logging; | |
| using Microsoft.Identity.Client; | |
| // ====== EDIT THESE VALUES ====== | |
| var directConnectUrl = "<<PASTE_FROM_COPILOT_STUDIO_CHANNEL_PAGE>>"; // Agents SDK connection value | |
| var tenantId = "<<YOUR_TENANT_ID_GUID>>"; | |
| var clientId = "<<YOUR_ENTRA_APP_CLIENT_ID>>"; | |
| // =============================== | |
| // 1) Connection settings | |
| var settings = new ConnectionSettings | |
| { | |
| DirectConnectUrl = directConnectUrl | |
| }; | |
| // 2) Acquire a user token (interactive) | |
| var scope = CopilotClient.ScopeFromSettings(settings); // derives correct scope for the Power Platform cloud | |
| var pca = PublicClientApplicationBuilder | |
| .Create(clientId) | |
| .WithTenantId(tenantId) | |
| .WithRedirectUri("http://localhost") | |
| .Build(); | |
| AuthenticationResult auth = await pca | |
| .AcquireTokenInteractive(new[] { scope }) | |
| .ExecuteAsync(); | |
| // 3) Setup DI for HttpClientFactory + basic logging | |
| var services = new ServiceCollection(); | |
| services.AddLogging(b => b.AddSimpleConsole(o => o.SingleLine = true).SetMinimumLevel(LogLevel.Information)); | |
| services.AddHttpClient("mcs"); | |
| var sp = services.BuildServiceProvider(); | |
| var logger = sp.GetRequiredService<ILoggerFactory>().CreateLogger("copilot-ui"); | |
| // 4) Create Copilot client (token provider returns the user token) | |
| var client = new CopilotClient( | |
| settings, | |
| sp.GetRequiredService<IHttpClientFactory>(), | |
| _ => Task.FromResult(auth.AccessToken), | |
| logger, | |
| httpClientName: "mcs" | |
| ); | |
| // 5) Start conversation | |
| string conversationId = ""; | |
| await foreach (var act in client.StartConversationAsync()) | |
| { | |
| conversationId = act.Conversation?.Id ?? conversationId; | |
| } | |
| Console.WriteLine($"Connected. ConversationId={conversationId}"); | |
| Console.WriteLine("Type a message and press Enter. Type 'exit' to quit."); | |
| while (true) | |
| { | |
| Console.Write("> "); | |
| var input = Console.ReadLine(); | |
| if (string.IsNullOrWhiteSpace(input)) continue; | |
| if (input.Equals("exit", StringComparison.OrdinalIgnoreCase)) break; | |
| await foreach (var act in client.AskQuestionAsync(input, conversationId)) | |
| { | |
| if (act.Type == "message" && !string.IsNullOrWhiteSpace(act.Text)) | |
| Console.WriteLine($"Agent: {act.Text}"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment