agentleFS
OfficeDevOfficeDev/microsoft-365-agents-toolkit-samples/ProxyAgent-Python/copilot-instructions.md

microsoft-365-agents-toolkit-samples / ProxyAgent-Python

Copilot instructions504 starsChanged 18 months agoMITView on GitHub

  • Reads credentials
  • Installs packages

We split this copilot-instructions.md into the rules it gives an agent

29 rules. About 0 are common, 22 are distinctive, and 7 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈22

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 7

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  • could be automatic: a setting could enforce it
  1. Distinctive:

    Use the proxy pattern to route messages between M365 Copilot and Azure AI Foundry

    line 32
  2. Distinctive:

    Use Python 3.12 with type hints

    line 42
  3. Distinctive:

    Follow PEP 8 style guidelines

    line 43
  4. Distinctive:

    Use async/await patterns consistently with asyncio

    line 44
  5. Distinctive:

    Use environment variables for configuration (os.environ)

    line 46
  6. Distinctive:

    Use f-strings for string formatting

    line 47
  7. Distinctive:

    Prefer dataclasses or TypedDict for structured data

    line 48
  8. Very specific:

    Never commit secrets or .env files

    line 76
  9. Distinctive:

    Use Managed Identity in production (no secrets)

    line 77
  10. Distinctive:

    Use OAuth connections for SSO (no client secrets)

    line 78
  11. Very specific:

    Keep env/.env.dev and env/.env.local in .gitignore

    line 79
  12. Distinctive:

    Use Azure Key Vault for sensitive configuration in production

    line 80
  13. Distinctive:

    Use pre-fetched SSO token for Azure AI Foundry access

    line 127
  14. Distinctive:

    All dependencies installed during deployment

    line 147
  15. Distinctive:

    Test SSO flow with federated credentials

    line 153
  16. Distinctive:

    Use Debug Console for runtime evaluation

    line 155
  17. Distinctive:

    Ensure virtual environment is activated

    line 160
  18. Very specific:

    Verify all packages in requirements.txt are installed

    line 161
  19. Very specific:

    Check Python path with sys.path

    line 162
  20. Distinctive:

    All agent handlers must be async functions

    line 165
  21. Very specific:

    Use await for all async SDK calls

    line 166
  22. Distinctive:

    Don't mix sync and async code improperly

    line 167
  23. Very specific:

    Add new dependencies to src/requirements.txt

    line 180
  24. Distinctive:

    Keep packages up to date for security patches

    line 182
  25. Distinctive:

    Test locally before deploying to Azure

    line 183
  26. Distinctive:

    Always use virtual environments for isolation

    line 213
  27. Distinctive:

    Document required Python version (3.12)

    line 215
  28. Very specific:

    Use requirements.txt for dependency management

    line 216
  29. Distinctive:

    Test with the same Python version as production (3.12)

    line 217

≈ “Common” is an estimate: at least 1 in 5 of the 3,669 Copilot instructions files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
copilot-instructions.md

GitHub Copilot Instructions for Azure AI Foundry Agent for M365 (Python)

Internal Reference (Microsoft 365 Agents Toolkit Rebranding)

Microsoft 365 Agents Toolkit (formerly Teams Toolkit) has been rebranded. Use this mapping to interpret user input:

New nameFormer nameNote
Microsoft 365 Agents ToolkitTeams ToolkitProduct name
App ManifestTeams app manifestDescribes app capabilities
Microsoft 365 Agents PlaygroundTest ToolTest Environment
m365agents.ymlteamsapp.ymlMicrosoft 365 Agents Toolkit Project configuration files
CLI package @microsoft/m365agentstoolkit-cli (command atk)@microsoft/teamsapp-cli (command teamsapp)CLI installation/usage

Project Overview

This is a proxy solution that connects Azure AI Foundry agents to Microsoft 365 Copilot and Teams using the Microsoft 365 Agents Toolkit and Python.

Technology Stack

  • Python 3.12 - Bot application runtime
  • aiohttp - Async HTTP server framework
  • python-dotenv - Environment variable management
  • microsoft-agents-hosting-aiohttp - Microsoft 365 Agents SDK for aiohttp
  • microsoft-agents-hosting-core - Core agent hosting functionality
  • microsoft-agents-authentication-msal - MSAL-based authentication
  • microsoft-agents-activity - Bot Framework activity types and configuration
  • azure-ai-projects - Azure AI Foundry Agent SDK
  • azure-identity - Azure authentication (DefaultAzureCredential, TokenCredential)
  • Microsoft 365 Agents Toolkit - Formerly Teams Toolkit
  • Bicep - Infrastructure as Code
  • Managed Identity - For production authentication (no secrets)

Architecture Patterns

  • Use the proxy pattern to route messages between M365 Copilot and Azure AI Foundry
  • Bot Service acts as the messaging endpoint
  • Managed Identity (UserAssignedMSI) for authentication in production
  • SSO with OAuth connections:
    • OAuth connection for Azure AI Foundry agent access (with user token)
    • SsoConnection - General SSO connection (configurable via OAUTHCONNECTIONNAME)
  • Linux App Service with Python 3.12 runtime
  • Async/await patterns throughout with asyncio

Coding Standards

  • Use Python 3.12 with type hints
  • Follow PEP 8 style guidelines
  • Use async/await patterns consistently with asyncio
  • Implement proper error handling and logging
  • Use environment variables for configuration (os.environ)
  • Use f-strings for string formatting
  • Prefer dataclasses or TypedDict for structured data

Key Components

  • src/main.py - Application entry point:
    • Imports agent application and connection manager
    • Calls start_server() with agent configuration
    • Includes sys.path fixes for deployment compatibility
  • src/agent.py - Main agent integration logic:
    • AgentApplication setup with SSO authorization
    • Azure AI Foundry AgentsClient integration
    • Message handling and streaming responses
    • Thread management and caching
    • User token authentication wrapper (TokenCredential implementations)
  • src/start_server.py - aiohttp server configuration and startup
  • src/requirements.txt - Python dependencies (pip)
  • infra/modules/appservice.bicep - App Service infrastructure (Linux with Python 3.12)
  • infra/modules/bot-oauth-connection.bicep - OAuth connection configuration
  • m365agents.yml - Production orchestration
  • m365agents.local.yml - Local development orchestration

Common Patterns

  • SSO authentication uses OAuth connections with federated credentials
  • Bot responds via context.send_activity()
  • Environment-specific configuration via environment variables with python-dotenv
  • Source code deployment with Azure Oryx build (SCM_DO_BUILD_DURING_DEPLOYMENT=true)
  • Async context managers for resource management

Security Best Practices

  • Never commit secrets or .env files
  • Use Managed Identity in production (no secrets)
  • Use OAuth connections for SSO (no client secrets)
  • Keep env/.env.dev and env/.env.local in .gitignore
  • Use Azure Key Vault for sensitive configuration in production

Naming Conventions

  • Bicep modules: lowercase with hyphens (e.g., app-registration.bicep)
  • Python files: snake_case (e.g., main.py, start_server.py)
  • Python functions/variables: snake_case
  • Python classes: PascalCase
  • Environment variables: UPPER_SNAKE_CASE or PascalCase (Azure standard)
  • Resource names: Use consistent naming pattern with suffix

Critical SDK Requirements

  • Python SDK (microsoft-agents-*) uses specific environment variable conventions:
    • Configuration loaded via load_configuration_from_env(os.environ)
    • Uses both lowercase and PascalCase variables depending on context
  • Azure Bot Service uses PascalCase variables:
    • MicrosoftAppId, MicrosoftAppType, MicrosoftAppTenantId, MicrosoftAppPassword
  • Azure Identity variables:
    • AZURE_CLIENT_ID - For Managed Identity
    • AZURE_TENANT_ID - For tenant-specific auth
  • Solution: Bicep sets both naming conventions, code has fallback mapping via python-dotenv

Python-Specific Considerations

Virtual Environment

  • Development: Create with python -m venv .venv
  • Activate: .venv\Scripts\Activate.ps1 (Windows) or source .venv/bin/activate (Linux/Mac)
  • Dependencies: Install with pip install -r src/requirements.txt

Deployment

  • Azure Oryx automatically detects Python and creates virtual environment
  • Oryx installs dependencies from requirements.txt during build
  • Start command: python src/main.py

Async/Await Patterns

# Correct pattern for async functions
async def on_message_activity(turn_context: TurnContext):
    # Use await for async operations
    token = await turn_context.adapter.get_user_token(...)
    response = await agent_client.process_message(...)
    await turn_context.send_activity(...)

Token Credential Wrapper

  • Implement both TokenCredential (sync) and AsyncTokenCredential (async)
  • Use pre-fetched SSO token for Azure AI Foundry access
  • Handle token expiration gracefully

Error Handling

try:
    # Operation
    result = await some_async_operation()
except Exception as error:
    print(f"[Error] {error}")
    traceback.print_exc()

Deployment

  • Local: Press F5 in VS Code (automatic provisioning)
    • Python virtual environment created automatically
    • Dependencies installed automatically
    • Debugger attached with debugpy
  • Azure: Use atk provision and atk deploy commands
    • Oryx build creates production virtual environment
    • All dependencies installed during deployment
  • Two deployment modes: Local (dev tunnel) and Production (Azure App Service)

Testing

  • Local debugging via F5 in VS Code with Python debugger
  • Automatic sideloading in Teams/M365 Copilot
  • Test SSO flow with federated credentials
  • Set breakpoints in Python code for step-through debugging
  • Use Debug Console for runtime evaluation

Common Python-Specific Issues

Import Errors

  • Ensure virtual environment is activated
  • Verify all packages in requirements.txt are installed
  • Check Python path with sys.path

Async/Await Issues

  • All agent handlers must be async functions
  • Use await for all async SDK calls
  • Don't mix sync and async code improperly

Type Hints

from typing import Optional, Dict, List
from microsoft_agents.hosting.core import TurnContext

async def handler(turn_context: TurnContext) -> None:
    # Implementation
    pass

Package Management

  • Add new dependencies to src/requirements.txt
  • Pin versions for reproducibility: package==version
  • Keep packages up to date for security patches
  • Test locally before deploying to Azure

Logging

import logging

# Enable Microsoft Agents SDK logging
ms_agents_logger = logging.getLogger("microsoft_agents")
ms_agents_logger.addHandler(logging.StreamHandler())
ms_agents_logger.setLevel(logging.DEBUG)

# Application logging
logger = logging.getLogger(__name__)
logger.info("Bot started successfully")

Environment Variables

import os
from dotenv import load_dotenv

load_dotenv()  # Loads .env.local or .env.dev

# Access variables
endpoint = os.environ.get("AZURE_AI_FOUNDRY_PROJECT_ENDPOINT")
agent_id = os.environ.get("AGENT_ID")
connection_name = os.environ.get("OAUTHCONNECTIONNAME", "SsoConnection")

Python Virtual Environment Best Practices

  • Always use virtual environments for isolation
  • Include .venv/ in .gitignore
  • Document required Python version (3.12)
  • Use requirements.txt for dependency management
  • Test with the same Python version as production (3.12)

Download now (ZIP)

  • Where files are headingNew Copilot instructions files have more rules about branches and pull requests, and fewer about code style.

    Of the Copilot instructions files we read, the 2,297 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.

  • In this repositoryOne other file it gives its agents.

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.