Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
//! This module provides the inbound adapter for ai tools using the notifications service
mod mute_notifications;
#[cfg(test)]
mod test;
pub use mute_notifications::{
ItemNotificationPreferenceToolContext, MuteAction, MuteNotifications,
MuteNotificationsResponse, item_notification_preference_toolset,
};
use crate::domain::{
models::{
UserNotificationRow,
request::{
NotificationCategory, NotificationListFilters, NotificationStatus,
UpdateNotificationsRequest,
},
},
service::NotificationReader,
};
use ai_toolset::{
AsyncTool, AsyncToolCollection, RequestContext, ServiceContext, ToolCallError, ToolResult,
};
use ai_toolset::{ToolAnnotated, ToolAnnotations};
use async_trait::async_trait;
use cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::{Entity, EntityType};
use models_pagination::CreatedAt;
use rootcause::compat::boxed_error::IntoBoxedError;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use uuid::Uuid;
/// Service context for notification AI tools
pub struct NotificationToolContext<T> {
/// The notification service instance
pub service: Arc<T>,
}
impl<T> Clone for NotificationToolContext<T> {
fn clone(&self) -> Self {
Self {
service: self.service.clone(),
}
}
}
impl<T: NotificationReader> NotificationToolContext<T> {
/// Create a new notification tool context
pub fn new(service: T) -> Self {
Self {
service: Arc::new(service),
}
}
}
/// Create a notification toolset for AI agents
pub fn notification_toolset<T>() -> AsyncToolCollection<NotificationToolContext<T>>
where
T: NotificationReader,
{
AsyncToolCollection::new()
.add_tool::<ListNotifications, NotificationToolContext<T>>()
.add_tool::<MarkNotificationsSeen, NotificationToolContext<T>>()
.add_tool::<MarkNotificationsDone, NotificationToolContext<T>>()
}
/// Canonical entity types accepted by the notification-listing tool.
///
/// This mirrors [`EntityType`] because the shared model intentionally does not
/// depend on `schemars`, while AI tool inputs require [`JsonSchema`].
#[allow(missing_docs)]
#[derive(Debug, Deserialize, JsonSchema, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum NotificationEntityType {
AgentSession,
User,
Channel,
#[serde(alias = "message")]
ChannelMessage,
Document,
Project,
#[serde(alias = "email")]
EmailThread,
#[serde(alias = "calendar")]
CalendarEvent,
Team,
Call,
#[serde(alias = "github")]
ForeignEntity,
StaticFile,
CrmCompany,
CrmContact,
Reminder,
Skill,
ScheduledAction,
}
impl From<NotificationEntityType> for EntityType {
fn from(value: NotificationEntityType) -> Self {
match value {
NotificationEntityType::AgentSession => Self::AgentSession,
NotificationEntityType::User => Self::User,
NotificationEntityType::Channel => Self::Channel,
NotificationEntityType::ChannelMessage => Self::ChannelMessage,
NotificationEntityType::Document => Self::Document,
NotificationEntityType::Project => Self::Project,
NotificationEntityType::EmailThread => Self::EmailThread,
NotificationEntityType::CalendarEvent => Self::CalendarEvent,
NotificationEntityType::Team => Self::Team,
NotificationEntityType::Call => Self::Call,
NotificationEntityType::ForeignEntity => Self::ForeignEntity,
NotificationEntityType::StaticFile => Self::StaticFile,
NotificationEntityType::CrmCompany => Self::CrmCompany,
NotificationEntityType::CrmContact => Self::CrmContact,
NotificationEntityType::Reminder => Self::Reminder,
NotificationEntityType::Skill => Self::Skill,
NotificationEntityType::ScheduledAction => Self::ScheduledAction,
}
}
}
/// Notification categories available to agents.
#[derive(Debug, Deserialize, JsonSchema, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum ToolNotificationCategory {
/// Email notifications.
Email,
/// Channel message notifications.
Message,
/// Channel notifications.
Channel,
/// Document notifications.
Document,
/// Folder notifications.
Project,
/// Call notifications.
Call,
/// Task notifications.
Task,
/// GitHub notifications.
Github,
/// Reminder notifications.
Reminder,
/// Calendar notifications.
Calendar,
/// Agent session notifications.
Agent,
}
impl From<ToolNotificationCategory> for NotificationCategory {
fn from(value: ToolNotificationCategory) -> Self {
match value {
ToolNotificationCategory::Email => Self::Email,
ToolNotificationCategory::Message => Self::Message,
ToolNotificationCategory::Channel => Self::Channel,
ToolNotificationCategory::Document => Self::Document,
ToolNotificationCategory::Project => Self::Project,
ToolNotificationCategory::Call => Self::Call,
ToolNotificationCategory::Task => Self::Task,
ToolNotificationCategory::Github => Self::Github,
ToolNotificationCategory::Reminder => Self::Reminder,
ToolNotificationCategory::Calendar => Self::Calendar,
ToolNotificationCategory::Agent => Self::Agent,
}
}
}
/// User-facing reference to one specific entity to filter notifications by.
#[derive(Debug, Deserialize, JsonSchema, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct NotificationEntityFilter {
/// Canonical entity type.
pub entity_type: NotificationEntityType,
/// Canonical entity identifier.
pub id: String,
}
impl NotificationEntityFilter {
fn into_entity(self) -> Entity<'static> {
EntityType::from(self.entity_type).with_entity_string(self.id)
}
}
/// List the current user's active notifications.
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[serde(rename_all = "camelCase")]
#[schemars(
title = "ListNotifications",
description = "List the current user's notifications. By default returns active notifications (not deleted, not done), ordered by most recent first. Use `states` to select exact unseen, seen, or done states. Seen excludes done; an empty list includes all states."
)]
pub struct ListNotifications {
/// Maximum number of notifications to return. Defaults to 20, max 50.
#[schemars(description = "Maximum number of notifications to return. Defaults to 20, max 50.")]
#[serde(default)]
pub limit: Option<u32>,
/// Exact notification states to include. Omitted defaults to unseen and seen.
/// An empty list includes all states; seen never includes done.
#[schemars(
description = "Exact states to include: unseen, seen, done. Defaults to [unseen, seen]. An empty list includes all states."
)]
#[serde(default)]
pub states: Option<Vec<crate::domain::models::NotificationState>>,
/// Filter to specific notification item types. If omitted, returns all types.
#[schemars(
description = "Filter to specific notification item types. If omitted, returns all types. Example: [\"email\", \"message\"] returns only email and message notifications."
)]
#[serde(default)]
pub include_types: Option<Vec<ToolNotificationCategory>>,
/// Filter to notifications for specific entities. If omitted, returns notifications for all entities.
#[schemars(
description = "Filter to notifications for specific entities. Pair each id with its canonical entityType to avoid ambiguity. Example: [{\"entityType\":\"email_thread\",\"id\":\"...\"}] returns notifications for one email thread."
)]
#[serde(default)]
pub entities: Option<Vec<NotificationEntityFilter>>,
}
/// A single notification item in the list response.
#[derive(Debug, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct NotificationItem {
/// The notification ID.
pub id: Uuid,
/// The notification event type (e.g. "channel_mention").
pub event_type: String,
/// The type of entity this notification is about (e.g. "channel", "document").
pub entity_type: String,
/// The ID of the entity this notification is about.
pub entity_id: String,
/// The authoritative notification state.
pub state: crate::domain::models::NotificationState,
/// When the notification was created (ISO 8601).
pub created_at: String,
/// The notification metadata/payload.
pub metadata: serde_json::Value,
/// The user ID of the sender, if any.
pub sender_id: Option<String>,
}
impl From<UserNotificationRow<serde_json::Value>> for NotificationItem {
fn from(row: UserNotificationRow<serde_json::Value>) -> Self {
Self {
id: row.notification_id,
event_type: row.notification_event_type,
entity_type: row.entity.entity_type.to_string(),
entity_id: row.entity.entity_id.into_owned(),
state: row.state,
created_at: row.created_at.to_rfc3339(),
metadata: row.notification_metadata,
sender_id: row.sender_id.map(|s| (*s).as_ref().to_owned()),
}
}
}
/// Response from listing notifications.
#[derive(Debug, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct ListNotificationsResponse {
/// The list of notifications.
pub notifications: Vec<NotificationItem>,
/// Whether there are more notifications available.
pub has_more: bool,
}
impl ToolAnnotated for ListNotifications {
const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("List notifications");
}
#[async_trait]
impl<T> AsyncTool<NotificationToolContext<T>> for ListNotifications
where
T: NotificationReader,
{
type Output = ListNotificationsResponse;
#[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, limit=?self.limit), err)]
async fn call(
&self,
service_context: ServiceContext<NotificationToolContext<T>>,
request_context: RequestContext,
) -> ToolResult<Self::Output> {
let limit = self.limit.unwrap_or(20).min(50);
tracing::info!("Listing notifications");
let paginated = service_context
.service
.get_user_notifications::<serde_json::Value>(
MacroUserIdStr((*request_context.user_id).copied()),
Some(limit),
models_pagination::Query::Sort(CreatedAt, ()),
NotificationListFilters {
states: self.states.clone().unwrap_or_else(|| {
crate::domain::models::NotificationState::ACTIVE.to_vec()
}),
include_types: self
.include_types
.clone()
.filter(|types| !types.is_empty())
.map(|types| types.into_iter().map(Into::into).collect())
.unwrap_or_else(|| {
vec![
NotificationCategory::Email,
NotificationCategory::Message,
NotificationCategory::Channel,
NotificationCategory::Document,
NotificationCategory::Project,
NotificationCategory::Call,
NotificationCategory::Task,
NotificationCategory::Github,
NotificationCategory::Reminder,
NotificationCategory::Calendar,
NotificationCategory::Agent,
]
}),
entities: self
.entities
.clone()
.unwrap_or_default()
.into_iter()
.map(NotificationEntityFilter::into_entity)
.collect(),
},
)
.await
.map_err(|e| ToolCallError {
description: format!("Failed to list notifications: {e}"),
internal_error: anyhow::Error::from_boxed(e.into_boxed_error()),
})?;
let has_more = paginated.next_cursor.is_some();
let notifications = paginated
.items
.into_iter()
.map(NotificationItem::from)
.collect();
Ok(ListNotificationsResponse {
notifications,
has_more,
})
}
}
/// Response from marking notifications as seen or done.
#[derive(Debug, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct MarkNotificationsResponse {
/// Whether the operation succeeded.
pub success: bool,
/// The number of notifications updated.
pub count: usize,
}
/// Mark one or more notifications as seen for the current user.
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[serde(rename_all = "camelCase")]
#[schemars(
title = "MarkNotificationsSeen",
description = "Mark one or more notifications as seen for the current user. Use this when the user has viewed notifications but hasn't acted on them yet."
)]
pub struct MarkNotificationsSeen {
/// The IDs of the notifications to mark as seen.
#[schemars(description = "The IDs of the notifications to mark as seen.")]
pub notification_ids: Vec<Uuid>,
}
impl ToolAnnotated for MarkNotificationsSeen {
const ANNOTATIONS: ToolAnnotations =
ToolAnnotations::additive("Mark notifications seen").with_idempotent();
}
#[async_trait]
impl<T> AsyncTool<NotificationToolContext<T>> for MarkNotificationsSeen
where
T: NotificationReader,
{
type Output = MarkNotificationsResponse;
#[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, count=self.notification_ids.len()), err)]
async fn call(
&self,
service_context: ServiceContext<NotificationToolContext<T>>,
request_context: RequestContext,
) -> ToolResult<Self::Output> {
tracing::info!(notification_ids=?self.notification_ids, "Marking notifications as seen");
let count = self.notification_ids.len();
service_context
.service
.update_notifications(UpdateNotificationsRequest {
user_id: MacroUserIdStr((*request_context.user_id).clone()),
notification_ids: &self.notification_ids,
status: NotificationStatus::Seen,
})
.await
.map_err(|e| ToolCallError {
description: format!("Failed to mark notifications as seen: {e}"),
internal_error: anyhow::Error::from_boxed(e.into_boxed_error()),
})?;
Ok(MarkNotificationsResponse {
success: true,
count,
})
}
}
/// Mark one or more notifications as done or not done for the current user.
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[serde(rename_all = "camelCase")]
#[schemars(
title = "MarkNotificationsDone",
description = "Mark one or more notifications as done or not done for the current user. Use this when the user has completed the action associated with a notification."
)]
pub struct MarkNotificationsDone {
/// The IDs of the notifications to update.
#[schemars(description = "The IDs of the notifications to update.")]
pub notification_ids: Vec<Uuid>,
/// Whether to mark as done (true) or not done (false). Defaults to true.
#[schemars(description = "Whether to mark as done (true) or not done (false).")]
pub done: bool,
}
impl ToolAnnotated for MarkNotificationsDone {
const ANNOTATIONS: ToolAnnotations =
ToolAnnotations::additive("Mark notifications done").with_idempotent();
}
#[async_trait]
impl<T> AsyncTool<NotificationToolContext<T>> for MarkNotificationsDone
where
T: NotificationReader,
{
type Output = MarkNotificationsResponse;
#[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, count=self.notification_ids.len(), done=self.done), err)]
async fn call(
&self,
service_context: ServiceContext<NotificationToolContext<T>>,
request_context: RequestContext,
) -> ToolResult<Self::Output> {
tracing::info!(notification_ids=?self.notification_ids, done=self.done, "Marking notifications as done/undone");
let count = self.notification_ids.len();
service_context
.service
.update_notifications(UpdateNotificationsRequest {
user_id: MacroUserIdStr((*request_context.user_id).clone()),
notification_ids: &self.notification_ids,
status: NotificationStatus::Done(self.done),
})
.await
.map_err(|e| ToolCallError {
description: format!("Failed to mark notifications as done: {e}"),
internal_error: anyhow::Error::from_boxed(e.into_boxed_error()),
})?;
Ok(MarkNotificationsResponse {
success: true,
count,
})
}
}