Skip to content

RajeevPentyala/CopilotAgentDirectlineAPI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 

Repository files navigation

Copilot Studio DirectLine API Console Application

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.

🤖 What is DirectLine?

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.

🚀 Features

  • Official Microsoft Library - Built using Microsoft's Microsoft.Bot.Connector.DirectLine package
  • Clean Architecture - Simple, maintainable code with built-in error handling
  • Type-Safe Operations - Strongly-typed Activity objects 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

🛠️ Prerequisites

  • .NET 9.0 or later
  • A Copilot Studio agent with DirectLine channel enabled
  • DirectLine secret from your Copilot Studio agent

📦 Dependencies

  • Microsoft.Bot.Connector.DirectLine - Official Microsoft DirectLine client library
  • Microsoft.Rest.ClientRuntime - REST client runtime (auto-installed)
  • Microsoft.Extensions.Configuration - Configuration management
  • Microsoft.Extensions.Configuration.Json - JSON configuration provider
  • Microsoft.Extensions.Configuration.Binder - Configuration binding

🔧 Setup

⚠️ Security Notice: This repository uses appsettings.template.json as a template. You must create your own appsettings.json file with your actual DirectLine secret. The actual appsettings.json file is excluded from version control for security.

  1. Clone the repository

    git clone https://github.com/RajeevPentyala/CopilotAgentDirectlineAPI.git
    cd CopilotAgentDirectlineAPI
  2. Restore NuGet packages

    # Navigate to the DirectLineConsoleApp directory
    cd DirectLineConsoleApp
    
    # Restore packages (includes Microsoft.Bot.Connector.DirectLine)
    dotnet restore
  3. Create your configuration file

    # Copy the template to create your actual config file
    copy appsettings.template.json appsettings.json
  4. 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

  5. Configure your DirectLine secret

    • Open the newly created appsettings.json file
    • Replace YOUR_DIRECTLINE_SECRET_HERE with your actual DirectLine secret from Copilot Studio
    {
      "DirectLineSettings": {
        "Secret": "E7zYvyyqJ0176G4EH8M95ttrV1VbCX45ZmWUjS4bfLf...",
        "BotFrameworkUri": "https://directline.botframework.com"
      }
    }

    ⚠️ Important: The appsettings.json file is excluded from version control to protect your secret!

🏃‍♂️ Running the Application

cd DirectLineConsoleApp
dotnet build
dotnet run

💬 Usage

  1. The application will start and display connection information
  2. Once connected, you can type messages to chat with your Copilot Studio agent
  3. Type quit to exit the application

Example Session

🤖 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...

📁 Project Structure

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.

🔐 Security Notes

  • Never commit your actual DirectLine secrets to version control
  • The .gitignore file excludes appsettings.json to 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

🎯 Key Components

DirectLineApiClient

  • StartConversationAsync() - Initiates a new conversation with your Copilot Studio agent
  • SendMessageAsync() - Sends messages using strongly-typed Activity objects
  • GetResponsesAsync() - Retrieves bot responses with watermark support for efficient polling
  • Automatic token management and authentication handling

Program.cs

  • 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

🔄 DirectLine API Flow

  1. Initialize Client - Create DirectLineClient with your secret
  2. Start Conversation - Begin a conversation session with your agent
  3. Send Messages - Post messages using Activity objects
  4. Poll for Responses - Retrieve bot responses with watermark support
  5. Parse Responses - Process structured responses including text, cards, and attachments

Benefits: Automatic token management, built-in retry logic, and strongly-typed operations!

💡 Why DirectLine?

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

�🚀 Next Steps

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

🤝 Contributing

Feel free to submit issues, fork the repository, and create pull requests for any improvements.

📄 License

This project is provided as-is for educational and demonstration purposes.

🔗 Related Links


Created with ❤️ for the Copilot Studio community

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages