The Copilot Studio Client is for connecting to and interacting with agents created in Microsoft Copilot Studio. This library allows you to integrate Copilot Studio agents into your Python applications.
This client library provides a direct connection to Copilot Studio agents, bypassing traditional chat channels. It's perfect for integrating AI conversations into your applications, building custom UIs, or creating agent-to-agent communication flows.
What is this?
This library is part of the Microsoft 365 Agents SDK for Python - a comprehensive framework for building enterprise-grade conversational AI agents. The SDK enables developers to create intelligent agents that work across multiple platforms including Microsoft Teams, M365 Copilot, Copilot Studio, and web chat, with support for third-party integrations like Slack, Facebook Messenger, and Twilio.
For published agents without a direct_connect_url, the client first sends an
authenticated GET to
https://<environment-host>/copilotstudio/agents/<escaped-schema-name>/conversation-endpoints.
The host is selected from the configured environment and cloud. Discovery uses the
client's bearer token and the configured client_session_settings.
The client validates all advertised endpoints before storing them and uses each
operation URL as returned, preserving its query string and escaping conversation
IDs when substituting {conversationId}. createConversation, executeTurn, and
continueTurn are required; subscribe is optional and subscription fails
explicitly when the agent does not advertise it. The client has no continue-turn
operation.
Successful discovery is reused for the lifetime of the client, with concurrent
calls coordinated to avoid duplicate initialization. Failures and cancellation
allow a later call to retry. The discovered create URL is written to
settings.direct_connect_url; clearing that value triggers discovery again.
Assigning a different explicit URL switches back to legacy direct-URL routing.
Explicit direct URLs and prebuilt agents bypass discovery entirely.
DirectConnect URL Mode (Simplified Setup)
For simplified setup, you can use a DirectConnect URL instead of environment-based configuration:
def create_client_direct():
settings = ConnectionSettings(
environment_id="", # Not needed with DirectConnect URL
agent_identifier="", # Not needed with DirectConnect URL
direct_connect_url="https://api.powerplatform.com/copilotstudio/dataverse-backed/authenticated/bots/your-bot-id"
)
token = acquire_token(...)
copilot_client = CopilotClient(settings, token)
return copilot_client
Diagnostic Logging Details:
When enable_diagnostics=True, the CopilotClient logs detailed HTTP communication using Python's logging module at the DEBUG level:
Pre-request: Logs the full request URL (>>> SEND TO {url})
Post-response: Logs all HTTP response headers in a formatted table
Errors: Logs error messages with status codes
To see diagnostic output, configure your Python logging:
Experimental Endpoint Details:
When use_experimental_endpoint=True, the CopilotClient will automatically capture and use the experimental endpoint URL from the first response:
The server returns the experimental endpoint in the x-ms-d2e-experimental response header
Once captured, this URL is stored in settings.direct_connect_url and used for all subsequent requests
This feature is only active when use_experimental_endpoint=True AND direct_connect_url is not already set
The experimental endpoint allows access to pre-release features and optimizations
copilot_client = create_client()
async for activity in copilot_client.start_conversation(emit_start_conversation_event=True):
if activity.type == ActivityTypes.message:
print(f"\n{activity.text}")
# Ask questions
async for reply in copilot_client.ask_question("Who are you?", conversation_id):
if reply.type == ActivityTypes.message:
print(f"\n{reply.text}")
Start with Advanced Options (Locale Support)
from microsoft_agents.copilotstudio.client import StartRequest
# Create a start request with locale
start_request = StartRequest(
emit_start_conversation_event=True,
locale="en-US", # Optional: specify conversation locale
conversation_id="custom-conv-id" # Optional: provide your own conversation ID
)
async for activity in copilot_client.start_conversation_with_request(start_request):
if activity.type == ActivityTypes.message:
print(f"\n{activity.text}")
Send Activities
Send a Custom Activity
from microsoft_agents.activity import Activity
activity = Activity(
type="message",
text="Hello, agent!",
conversation={"id": conversation_id}
)
async for reply in copilot_client.send_activity(activity):
print(f"Response: {reply.text}")
Execute with Explicit Conversation ID
# Execute an activity with a specific conversation ID
activity = Activity(type="message", text="What's the weather?")
async for reply in copilot_client.execute(conversation_id="conv-123", activity=activity):
print(f"Response: {reply.text}")
Subscribe to Conversation Events
For real-time event streaming with resumption support:
from microsoft_agents.copilotstudio.client import SubscribeEvent
# Subscribe to conversation events
async for subscribe_event in copilot_client.subscribe(
conversation_id="conv-123",
last_received_event_id=None # Optional: resume from last event
):
activity = subscribe_event.activity
event_id = subscribe_event.event_id # Use for resumption
if activity.type == ActivityTypes.message:
print(f"[{event_id}] {activity.text}")
# Required for DirectConnect mode
DIRECT_CONNECT_URL=https://api.powerplatform.com/copilotstudio/dataverse-backed/authenticated/bots/your-bot-id
APP_CLIENT_ID=your-azure-app-client-id
TENANT_ID=your-azure-tenant-id
# Optional
CLOUD=PROD # Used for token audience resolution
Advanced Options
# Experimental and diagnostic features
USE_EXPERIMENTAL_ENDPOINT=false # Enable automatic experimental endpoint capture
ENABLE_DIAGNOSTICS=false # Enable diagnostic logging (logs HTTP requests/responses)
Experimental Endpoint: When USE_EXPERIMENTAL_ENDPOINT=true, the client automatically captures and uses the experimental endpoint URL from the server's x-ms-d2e-experimental response header. This feature:
Only activates when direct_connect_url is not already set
Captures the URL from the first response and stores it for all subsequent requests
Provides access to pre-release features and performance optimizations
Useful for testing new capabilities before general availability
Diagnostic Logging: When ENABLE_DIAGNOSTICS=true or enable_diagnostics=True, the client will log detailed HTTP request and response information including:
Request URLs before sending
All response headers with their values
Error messages for failed requests
This is useful for debugging connection issues, authentication problems, or understanding the communication flow with Copilot Studio. Diagnostic logs use Python's standard logging module at the DEBUG level.
Using Environment Variables in Code
The ConnectionSettings.populate_from_environment() helper method automatically loads these variables:
from microsoft_agents.copilotstudio.client import ConnectionSettings
# Automatically loads from environment variables
settings_dict = ConnectionSettings.populate_from_environment()
settings = ConnectionSettings(**settings_dict)
Features
Core Capabilities
✅ Real-time streaming - Server-sent events for live responses
✅ Multi-cloud support - Works across all Power Platform clouds (PROD, GOV, HIGH, DOD, MOONCAKE, etc.)
✅ Rich content - Support for cards, actions, and attachments
✅ Conversation management - Maintain context across interactions
✅ Custom activities - Send structured data to agents
✅ Async/await - Modern Python async support
Advanced Features
✅ DirectConnect URLs - Simplified connection with direct bot URLs
✅ Locale support - Specify conversation language with StartRequest
✅ Event subscription - Subscribe to conversation events with SSE resumption
✅ Multiple connection modes - Environment-based or DirectConnect URL
✅ Token audience resolution - Automatic cloud detection from URLs
✅ User-Agent tracking - Automatic SDK version and platform headers
✅ Environment configuration - Automatic loading from environment variables
✅ Experimental endpoints - Toggle experimental API features
✅ Diagnostic logging - HTTP request/response logging for debugging and troubleshooting
API Methods
Method
Description
start_conversation()
Start a new conversation with basic options
start_conversation_with_request()
Start with advanced options (locale, custom conversation ID)
ask_question()
Send a text question to the agent
ask_question_with_activity()
Send a custom Activity object
send_activity()
Send any activity (alias for ask_question_with_activity)
execute()
Execute an activity with explicit conversation ID
subscribe()
Subscribe to conversation events with resumption support
Configuration Models
Class
Description
ConnectionSettings
Main configuration class with all connection options
StartRequest
Advanced start options (locale, conversation ID)
SubscribeEvent
Event wrapper with activity and SSE event ID
PowerPlatformCloud
Enum for cloud environments
AgentType
Enum for agent types (PUBLISHED, PREBUILT)
UserAgentHelper
Utility for generating user-agent headers
Connection Modes
The client supports two connection modes:
1. Environment-Based Connection (Standard)
Uses environment ID and agent identifier to construct the connection URL: