Zdieľať cez


Notify agents

Important

You need to be part of the Frontier preview program to get early access to Microsoft Agent 365. Frontier connects you directly with Microsoft’s latest AI innovations. Frontier previews are subject to the existing preview terms of your customer agreements. As these features are still in development, their availability and capabilities may change over time.

By using the Notifications module, you can build agents that respond to events and notifications from Microsoft 365 applications. By using notifications support, agents can receive and process alerts when users interact with them through email, document comments, or other collaborative scenarios.

Notifications workflow

Follow this workflow to enable notifications for your AI agent application:

  1. Install notification packages.

  2. Import notification components

    • Import notification classes and handlers.
    • Import activity types and channel identifiers.
  3. Register notification handlers

    • Use notification handler methods to register routes.
    • Configure handlers for specific notification types, such as email, Word, Excel, or PowerPoint.
  4. Process notifications in agent code

    • The agent receives notifications from Microsoft 365 applications.
    • Handle incoming notifications and respond appropriately.

Notification types

The Agent 365 SDK supports the following notification types:

Notification type Description Sub-Channel ID
Email Agent receives an email where they're mentioned or addressed email
Word Agent is mentioned in a comment in a Word document word
Excel Agent is mentioned in a comment in an Excel document excel
PowerPoint Agent is mentioned in a comment in a PowerPoint document powerpoint
Lifecycle Events Agent lifecycle notifications (user identity created, workload onboarding, user deleted) N/A

Agent lifecycle events

Agent lifecycle events enable your agent to respond to specific system events related to agentic user identity management. The SDK currently supports three lifecycle events:

Event type Event ID Description
User Identity Created agenticUserIdentityCreated Triggered when an agentic user identity is created
Workload Onboarding Updated agenticUserWorkloadOnboardingUpdated Triggered when an agentic user's workload onboarding status is updated
User Deleted agenticUserDeleted Triggered when an agentic user identity is deleted

By using these events, agents can perform initialization tasks, cleanup operations, or state management in response to user lifecycle changes.

Notification payload reference

When your agent receives a notification, the payload contains structured data specific to the notification type. Understanding these payloads helps you extract the information you need to process notifications effectively.

Email notification payload

When a user sends an email to your agent or mentions your agent in an email, your agent receives an email notification with the following structure:

{
  "id": "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
  "timestamp": "2026-02-06T17:45:20.740Z",
  "channelId": "agents",
  "serviceUrl": "http://localhost:56150/_connector",
  "recipient": {
    "id": "AgentName@contoso.onmicrosoft.com",
    "name": "My Agent",
    "agenticUserId": "<agentic-user-id>",
    "agenticAppId": "<agentic-app-id>",
    "tenantId": "<tenant-id>",
    "role": "agenticUser"
  },
  "conversation": {
    "id": "<conversation-id>",
    "conversationType": "personal",
    "tenantId": "<tenant-id>"
  },
  "from": {
    "id": "sender@contoso.onmicrosoft.com",
    "name": "Sender Name",
    "role": "user"
  },
  "type": "message",
  "channelData": {
    "tenant": {
      "id": "<tenant-id>"
    }
  },
  "locale": "en-US",
  "name": "emailNotification",
  "entities": [
    {
      "type": "clientInfo",
      "locale": "en-US",
      "timezone": null
    },
    {
      "id": "email",
      "type": "productInfo"
    },
    {
      "type": "emailNotification",
      "id": "<email-id>",
      "conversationId": "<conversation-id>",
      "htmlBody": "<body dir=\"ltr\">\n<div class=\"elementToProof\">Your email message content here</div>\n</body>"
    }
  ]
}

Document comment notification payload (Word, Excel, PowerPoint)

When a user mentions your agent in a comment within a Word, Excel, or PowerPoint document, your agent receives a WPX (Word, PowerPoint, Excel) comment notification:

{
  "id": "bbbbbbbb-1111-2222-3333-cccccccccccc",
  "timestamp": "2026-02-06T17:46:02.248Z",
  "channelId": "agents",
  "serviceUrl": "http://localhost:56150/_connector",
  "recipient": {
    "id": "AgentName@contoso.onmicrosoft.com",
    "name": "My Agent",
    "agenticUserId": "<agentic-user-id>",
    "agenticAppId": "<agentic-app-id>",
    "tenantId": "<tenant-id>",
    "role": "agenticUser"
  },
  "conversation": {
    "id": "<conversation-id>",
    "conversationType": "personal",
    "tenantId": "<tenant-id>",
    "topic": "<document-topic>"
  },
  "from": {
    "id": "sender@contoso.onmicrosoft.com",
    "name": "Sender Name",
    "role": "user"
  },
  "type": "message",
  "channelData": {
    "tenant": {
      "id": "<tenant-id>"
    },
    "productContext": "Word"
  },
  "locale": "en-US",
  "textFormat": "plain",
  "text": "<at>My Agent</at> - Please review this section\n",
  "attachments": [
    {
      "contentUrl": "<document-url>",
      "name": "<document-name>",
      "content": {
        "uniqueId": "<document-unique-id>",
        "fileType": "docx"
      },
      "contentType": "application/vnd.microsoft.teams.file.download.info"
    }
  ],
  "entities": [
    {
      "type": "clientInfo",
      "locale": "en-US",
      "timezone": null
    },
    {
      "mentioned": {
        "id": "AgentName@contoso.onmicrosoft.com",
        "name": "@My Agent"
      },
      "text": "<at>My Agent</at>",
      "type": "mention"
    },
    {
      "id": "Word",
      "type": "productInfo"
    },
    {
      "parentCommentId": "<parent-comment-id>",
      "commentId": "<comment-id>",
      "documentId": "<document-id>",
      "type": "wpxcomment"
    }
  ]
}

Add notifications to your agent

Follow these steps to enable notification handling in your existing agent:

Import notification components

Add these imports to your agent file:

from microsoft_agents_a365 import AgentApplication
from microsoft_agents_a365.notifications import (
    AgentNotification,
    AgentNotificationActivity,
    NotificationTypes
)
from microsoft_agents.activity import ChannelId
from microsoft_agents.hosting.core import Authorization, TurnContext
  • AgentApplication: Base class for building Agent365 applications. It provides core functionality for routing activities, managing state, and processing requests.
  • AgentNotification: Class for registering notification handlers with decorator methods. It provides on_agent_notification(), on_email(), on_word(), and other convenience decorators.
  • AgentNotificationActivity: Wrapper containing parsed notification data with typed properties like email_notification and wpx_comment_notification that contain notification-specific metadata such as IDs, conversation details, and document references.
  • NotificationTypes: Enum of supported notification types like EMAIL_NOTIFICATION, WPX_COMMENT.
  • ChannelId: Use to specify notification channels, for example, ChannelId(channel="agents", sub_channel="*").
  • Authorization: Authorization context for processing notifications.
  • TurnContext: Current conversation turn context from the Agents SDK.

Register notification handlers in your agent

Add notification handlers to your agent's initialization:

class YourAgent(AgentApplication):
    def __init__(self, app):
        # Create notification handler
        agent_notification = AgentNotification(app)
        
        # Register handler for all notifications
        @agent_notification.on_agent_notification(
            ChannelId(channel="agents", sub_channel="*")
        )
        async def handle_all_notifications(context, state, notification):
            # Route based on notification type
            if notification.notification_type == NotificationTypes.EMAIL_NOTIFICATION:
                await self.handle_email_notification(context, state, notification)
            elif notification.notification_type == NotificationTypes.WPX_COMMENT:
                await self.handle_comment_notification(context, state, notification)
            else:
                await context.send_activity('Notification type not yet implemented.')

Implement specific notification handlers

Add handler methods for each notification type:

class YourAgent(AgentApplication):
    # ... __init__ from above ...
    
    async def handle_email_notification(self, context, state, notification):
        """Handle email notifications"""
        email = notification.email_notification
        
        if not email:
            await context.send_activity('No email data found')
            return
        
        # Process the email
        await context.send_activity(
            f'Received email notification. Email ID: {email.id}'
        )
        
        # Your email processing logic here
    
    async def handle_comment_notification(self, context, state, notification):
        """Handle document comment notifications"""
        comment = notification.wpx_comment_notification
        
        if not comment:
            await context.send_activity('No comment data found')
            return
        
        # Process the comment
        await context.send_activity(
            f'Received comment notification. Document ID: {comment.document_id}'
        )
        
        # Your comment processing logic here

Identify the sender

Every notification activity includes Activity.From. The A365 platform populates this property with the sender's basic identity, so you don't need any API calls or token acquisition. Access it inside any notification handler:

async def handle_email_notification(self, context, state, notification):
    from_prop = context.activity.from_property
    logger.info(
        "Notification from — DisplayName: '%s', UserId: '%s', AadObjectId: '%s'",
        getattr(from_prop, "name", None) or "(unknown)",
        getattr(from_prop, "id", None) or "(unknown)",
        getattr(from_prop, "aad_object_id", None) or "(none)",
    )
    display_name = getattr(from_prop, "name", None) or "unknown"
    # Use display_name in your response or LLM prompt

Activity.from_property is a ChannelAccount class instance that has the following properties:

Property Description
name Display name
id Channel user ID
aad_object_id Entra Object ID

Important

The display name is user-controlled text. Sanitize it (strip control characters, enforce a maximum length) before injecting it into LLM system prompts to prevent prompt injection attacks.

Tip

Use aadObjectId with the Microsoft Graph API to retrieve extended profile data (job title, manager, department) when your agent has appropriate permissions.

Specialized notification handlers

After setting up the basic notification routing, use specialized handler methods for more granular control. By using these methods, you can:

  • Register multiple handlers for the same notification type.
  • Set handler priority by using ranking.
  • Configure auto authentication per handler.

Note

For most use cases, the generic handler pattern is sufficient. Use these specialized handlers when you need advanced routing or multiple handlers for the same notification type.

Specialized handler for all notifications

Register more handlers that process all notification types:

from microsoft_agents_a365.notifications import (
    AgentNotification,
    NotificationTypes
)
from microsoft_agents.activity import ChannelId

# Create notification handler
agent_notification = AgentNotification(app)

# Register handler for all notifications
@agent_notification.on_agent_notification(
    ChannelId(channel="agents", sub_channel="*")
)
async def handle_all_notifications(context, state, notification):
    if notification.notification_type == NotificationTypes.EMAIL_NOTIFICATION:
        if notification.email_notification:
            await context.send_activity(f"Received email: {notification.email_notification.id}")
    elif notification.notification_type == NotificationTypes.WPX_COMMENT:
        if notification.wpx_comment_notification:
            await context.send_activity(f"Received comment: {notification.wpx_comment_notification.comment_id}")

Specialized handler for email notifications

Register more handlers specifically for email notifications:

from microsoft_agents_a365.notifications import AgentNotification
from microsoft_agents.activity import ChannelId, AgentSubChannel

# Create notification handler
agent_notification = AgentNotification(app)

# Use the convenience method for email notifications
@agent_notification.on_email()
async def handle_email(context, state, notification):
    email = notification.email_notification
    
    if not email:
        await context.send_activity('No email found')
        return
    
    # Process the email
    email_id = email.id
    conversation_id = email.conversation_id
    
    # Send response
    await context.send_activity('Thank you for your email!')

Specialized handlers for document comments

Register more handlers for Word, Excel, and PowerPoint comment notifications:

from microsoft_agents_a365.notifications import AgentNotification

# Create notification handler
agent_notification = AgentNotification(app)

# Use convenience methods for document notifications
@agent_notification.on_word()
async def handle_word(context, state, notification):
    comment = notification.wpx_comment_notification
    
    if comment:
        document_id = comment.document_id
        comment_id = comment.comment_id
        await context.send_activity(f'Processing Word comment: {comment_id}')

@agent_notification.on_excel()
async def handle_excel(context, state, notification):
    comment = notification.wpx_comment_notification
    
    if comment:
        await context.send_activity('Processing Excel comment')

@agent_notification.on_powerpoint()
async def handle_powerpoint(context, state, notification):
    comment = notification.wpx_comment_notification
    
    if comment:
        await context.send_activity('Processing PowerPoint comment')

Specialized handlers for lifecycle events

Register more handlers for agent lifecycle events, such as user identity creation, workload onboarding, and user deletion:

from microsoft_agents_a365.notifications import AgentNotification

# Create notification handler
agent_notification = AgentNotification(app)

# Handle all lifecycle events
@agent_notification.on_agent_lifecycle_notification("*")
async def handle_lifecycle(context, state, notification):
    lifecycle_notification = notification.agent_lifecycle_notification
    if lifecycle_notification:
        event_type = lifecycle_notification.lifecycle_event_type
        
        if event_type == "agenticUserIdentityCreated":
            await context.send_activity('User identity created')
        elif event_type == "agenticUserWorkloadOnboardingUpdated":
            await context.send_activity('Workload onboarding completed')
        elif event_type == "agenticUserDeleted":
            await context.send_activity('User identity deleted')

Advanced configuration

This section covers advanced configuration options for fine-tuning your notification handlers. By using these configurations, you can control the handler execution order, manage authentication requirements, and optimize notification processing for complex scenarios.

Handler priority and ranking

When you use multiple specialized handlers, specify the priority order by using rank values. Lower rank values indicate higher priority:

from microsoft_agents_a365.notifications import AgentNotification
from microsoft_agents.activity import ChannelId, AgentSubChannel

# Create notification handler
agent_notification = AgentNotification(app)

# Higher priority handler (processed first)
@agent_notification.on_email(rank=100)
async def high_priority_email(context, state, notification):
    # Handle with high priority
    pass

# Lower priority handler (processed after higher priority)
@agent_notification.on_email(rank=200)
async def low_priority_email(context, state, notification):
    # Handle with lower priority
    pass

Authentication handlers

Configure auto sign-in handlers for notifications that require authentication:

from microsoft_agents_a365.notifications import AgentNotification
from microsoft_agents.activity import ChannelId, AgentSubChannel

# Create notification handler
agent_notification = AgentNotification(app)

# Handler with automatic authentication
@agent_notification.on_email(auto_sign_in_handlers=['agentic'])
async def authenticated_email(context, state, notification):
    # Authentication is handled automatically
    pass

Sample code

For complete working examples of notification handling across all supported frameworks, see the Agent 365 Samples.

Test your agent with notifications

After implementing notification handlers, test your agent to ensure it correctly receives and processes different notification types. Follow the testing guide to set up your environment, and then focus primarily on the Test with notification activities section to validate your notifications by using agentic authentication.

Monitor notification handling

Add observability capabilities to monitor your agent's notification handling. Track notification processing, response times, and error rates to understand agent performance. Learn more about implementing tracing and monitoring.