A C# console application that demonstrates how to integrate with Microsoft Copilot Studio agents using the official Microsoft DirectLine client library. This project provides a complete example of external bot communication, allowing you to programmatically interact with Copilot Studio agents from custom applications.
DirectLine is Microsoft's REST API that allows external applications to communicate with bots and AI agents. Think of it as a "phone line" between your custom application and your Copilot Studio agent. Instead of users chatting through the web interface, your application can send messages and receive responses programmatically, enabling you to integrate AI capabilities into any system, website, or workflow.
- Official Microsoft Library - Built using Microsoft's
Microsoft.Bot.Connector.DirectLinepackage - Clean Architecture - Simple, maintainable code with built-in error handling
- Type-Safe Operations - Strongly-typed
Activityobjects with IntelliSense support - Automatic Authentication - Built-in token management and refresh
- Interactive Chat - Console-based chat interface with your Copilot Studio agent
- Rich Content Support - Handles text, attachments, adaptive cards, and suggested actions
- Robust Error Handling - Comprehensive retry logic and exception management
- Async Operations - Non-blocking operations for optimal performance
- .NET 9.0 or later
- A Copilot Studio agent with DirectLine channel enabled
- DirectLine secret from your Copilot Studio agent
Microsoft.Bot.Connector.DirectLine- Official Microsoft DirectLine client libraryMicrosoft.Rest.ClientRuntime- REST client runtime (auto-installed)Microsoft.Extensions.Configuration- Configuration managementMicrosoft.Extensions.Configuration.Json- JSON configuration providerMicrosoft.Extensions.Configuration.Binder- Configuration binding
⚠️ Security Notice: This repository usesappsettings.template.jsonas a template. You must create your ownappsettings.jsonfile with your actual DirectLine secret. The actualappsettings.jsonfile is excluded from version control for security.
-
Clone the repository
git clone https://github.com/RajeevPentyala/CopilotAgentDirectlineAPI.git cd CopilotAgentDirectlineAPI -
Restore NuGet packages
# Navigate to the DirectLineConsoleApp directory cd DirectLineConsoleApp # Restore packages (includes Microsoft.Bot.Connector.DirectLine) dotnet restore
-
Create your configuration file
# Copy the template to create your actual config file copy appsettings.template.json appsettings.json -
Get your DirectLine secret from Copilot Studio
- Open your Copilot Studio agent
- Go to Settings > Security > Web channel security
- Copy either Secret 1 or Secret 2
📖 Reference: Configure DirectLine channel in Copilot Studio
-
Configure your DirectLine secret
- Open the newly created
appsettings.jsonfile - Replace
YOUR_DIRECTLINE_SECRET_HEREwith your actual DirectLine secret from Copilot Studio
{ "DirectLineSettings": { "Secret": "E7zYvyyqJ0176G4EH8M95ttrV1VbCX45ZmWUjS4bfLf...", "BotFrameworkUri": "https://directline.botframework.com" } }⚠️ Important: Theappsettings.jsonfile is excluded from version control to protect your secret! - Open the newly created
cd DirectLineConsoleApp
dotnet build
dotnet run- The application will start and display connection information
- Once connected, you can type messages to chat with your Copilot Studio agent
- Type
quitto exit the application
🤖 DirectLine Console App - Copilot Studio Integration
============================================================
🔧 Bot Framework URI: https://directline.botframework.com
🔑 Secret configured: E7zYvyyq...
🔑 Starting DirectLine conversation...
✅ Conversation started successfully - ID: 12345-67890-abcdef
🎯 Chat Session Started!
Type your questions (or 'quit' to exit):
Suggested: 'What is copilot studio?'
--------------------------------------------------
You: What is copilot studio?
📤 Sending message: 'What is copilot studio?'
✅ Message sent successfully
⏳ Waiting for bot response...
📥 Getting bot responses...
✅ Responses received successfully
🤖 Bot: Copilot Studio is a low-code platform for building AI agents...
DirectLineConsoleApp/
├── Program.cs # Main application logic
├── DirectLineApiClient.cs # DirectLine API wrapper
├── DirectLineSettings.cs # Configuration model
├── DirectLineConsoleApp.csproj # Project file
├── appsettings.template.json # Configuration template (safe to commit)
├── appsettings.json # Your actual config (excluded from Git)
└── README.md # This file
Note: The appsettings.json file will only exist after you create it from the template.
- Never commit your actual DirectLine secrets to version control
- The
.gitignorefile excludesappsettings.jsonto prevent accidental commits - Use environment variables or Azure Key Vault for production deployments
- DirectLine tokens expire (typically 30 minutes) - implement refresh logic for long-running applications
StartConversationAsync()- Initiates a new conversation with your Copilot Studio agentSendMessageAsync()- Sends messages using strongly-typed Activity objectsGetResponsesAsync()- Retrieves bot responses with watermark support for efficient polling- Automatic token management and authentication handling
- Configuration loading and validation from appsettings.json
- Interactive chat loop with intelligent retry logic
- Response parsing for text, attachments, cards, and suggested actions
- Comprehensive error handling and user-friendly display
- Initialize Client - Create DirectLineClient with your secret
- Start Conversation - Begin a conversation session with your agent
- Send Messages - Post messages using Activity objects
- Poll for Responses - Retrieve bot responses with watermark support
- Parse Responses - Process structured responses including text, cards, and attachments
Benefits: Automatic token management, built-in retry logic, and strongly-typed operations!
DirectLine provides several advantages for integrating with Copilot Studio:
- Platform Independent - Works with any programming language that can make HTTP calls
- Secure Communication - Uses tokens and HTTPS for secure data transmission
- Rich Message Types - Supports text, cards, attachments, and interactive elements
- Scalable - Handle multiple concurrent conversations
- Flexible Integration - Embed AI capabilities into existing applications and workflows
This project provides a foundation for more advanced scenarios:
- File Uploads - Send documents to your agent
- Rich Content - Handle adaptive cards and attachments
- User Authentication - Implement OAuth flows
- Webhooks - Real-time message notifications
- Integration - Embed in web applications or services
Feel free to submit issues, fork the repository, and create pull requests for any improvements.
This project is provided as-is for educational and demonstration purposes.
Created with ❤️ for the Copilot Studio community