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
feat(ai): add ai tools for notifications (#1521)
Sean Aye68e4c74dd705
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 627c926167..41e483f5da 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -6038,7 +6038,10 @@ checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8"name = "notification"version = "0.1.0"dependencies = [+ "ai",+ "anyhow","aquamarine",+ "async-trait","aws-sdk-sesv2","aws-sdk-sns","aws-sdk-sqs",@@ -6057,6 +6060,7 @@ dependencies = ["redis","reqwest","rootcause",+ "schemars","serde","serde_json","sha2",diff --git a/rust/cloud-storage/notification/Cargo.toml b/rust/cloud-storage/notification/Cargo.tomlindex 3fe1b8bfa8..bb2770fd0d 100644--- a/rust/cloud-storage/notification/Cargo.toml+++ b/rust/cloud-storage/notification/Cargo.toml@@ -6,6 +6,7 @@ version = "0.1.0"[features]+ai_tool = ["dep:ai", "dep:anyhow", "dep:async-trait", "dep:schemars"]axum = ["dep:axum","dep:model-error-response",@@ -18,7 +19,10 @@ redis-tests = []schema = ["dep:utoipa"][dependencies]+ai = { path = "../ai", optional = true }+anyhow = { workspace = true, optional = true }aquamarine = { version = "0.6", optional = true }+async-trait = { workspace = true, optional = true }aws-sdk-sesv2 = { workspace = true }aws-sdk-sns = { workspace = true }aws-sdk-sqs = { workspace = true }@@ -40,6 +44,7 @@ redis = { workspace = true, features = [] }reqwest = { workspace = true }rootcause = { workspace = true }+schemars = { workspace = true, optional = true }serde = { workspace = true }serde_json = { workspace = true }sha2 = { workspace = true }diff --git a/rust/cloud-storage/notification/src/inbound.rs b/rust/cloud-storage/notification/src/inbound.rsindex 887e8966a1..c39b6d0396 100644--- a/rust/cloud-storage/notification/src/inbound.rs+++ b/rust/cloud-storage/notification/src/inbound.rs@@ -1,2 +1,5 @@+#[cfg(feature = "ai_tool")]+pub mod ai_tool;+#[cfg(feature = "axum")]pub mod http;pub mod worker;diff --git a/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rs b/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rsnew file mode 100644index 0000000000..89a9fe2d90--- /dev/null+++ b/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rs@@ -0,0 +1,280 @@+//! This module provides the inbound adapter for ai tools using the notifications service++#[cfg(test)]+mod test;++use crate::domain::{+ models::{+ UserNotificationRow,+ request::{NotificationStatus, UpdateNotificationsRequest},+ },+ service::NotificationIngress,+};+use ai::tool::{+ AsyncTool, AsyncToolSet, RequestContext, ServiceContext, ToolCallError, ToolResult,+};+use async_trait::async_trait;+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: NotificationIngress> {+ /// The notification service instance+ pub service: Arc<T>,+}++impl<T: NotificationIngress> Clone for NotificationToolContext<T> {+ fn clone(&self) -> Self {+ Self {+ service: self.service.clone(),+ }+ }+}++impl<T: NotificationIngress> 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>() -> AsyncToolSet<NotificationToolContext<T>>+where+ T: NotificationIngress,+{+ AsyncToolSet::new()+ .add_tool::<ListNotifications, NotificationToolContext<T>>()+ .expect("failed to add ListNotifications tool")+ .add_tool::<MarkNotificationsSeen, NotificationToolContext<T>>()+ .expect("failed to add MarkNotificationsSeen tool")+ .add_tool::<MarkNotificationsDone, NotificationToolContext<T>>()+ .expect("failed to add MarkNotificationsDone tool")+}++/// 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 active (not deleted, not done) notifications. Returns notifications ordered by most recent first. Use this to show the user their unread or pending notifications."+)]+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.")]+ pub limit: Option<u32>,+}++/// 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,+ /// Whether the notification has been seen.+ pub seen: bool,+ /// Whether the notification is marked as done.+ pub done: bool,+ /// When the notification was created (ISO 8601).+ pub created_at: Option<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(),+ seen: row.viewed_at.is_some(),+ done: row.done,+ created_at: row.created_at.map(|t| t.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,+}++#[async_trait]+impl<T> AsyncTool<NotificationToolContext<T>> for ListNotifications+where+ T: NotificationIngress,+{+ 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>(+ (*request_context.user_id).as_ref(),+ Some(limit),+ models_pagination::Query::Sort(CreatedAt, ()),+ )+ .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>,+}++#[async_trait]+impl<T> AsyncTool<NotificationToolContext<T>> for MarkNotificationsSeen+where+ T: NotificationIngress,+{+ 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: (*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,+}++#[async_trait]+impl<T> AsyncTool<NotificationToolContext<T>> for MarkNotificationsDone+where+ T: NotificationIngress,+{+ 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: (*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,+ })+ }+}diff --git a/rust/cloud-storage/notification/src/inbound/ai_tool/test.rs b/rust/cloud-storage/notification/src/inbound/ai_tool/test.rsnew file mode 100644index 0000000000..20e9618cb8--- /dev/null+++ b/rust/cloud-storage/notification/src/inbound/ai_tool/test.rs@@ -0,0 +1,119 @@+use super::*;+use ai::generate_tool_input_schema;+use ai::tool::types::tool_object::validate_tool_schema;++#[test]+fn test_list_notifications_schema_validation() {+ let schema = generate_tool_input_schema!(ListNotifications);++ let result = validate_tool_schema(&schema);+ assert!(result.is_ok(), "{:?}", result);++ let (name, description) = result.unwrap();+ assert_eq!(+ name, "ListNotifications",+ "Tool name should match the schemars title"+ );+ assert!(+ description.contains("List the current user"),+ "Description should contain expected text"+ );+}++#[test]+fn test_list_notifications_deserialization() {+ // No parameters required+ let json = r#"{}"#;+ let tool: ListNotifications = serde_json::from_str(json).unwrap();+ assert_eq!(tool.limit, None);++ // With explicit limit+ let json = r#"{"limit": 10}"#;+ let tool: ListNotifications = serde_json::from_str(json).unwrap();+ assert_eq!(tool.limit, Some(10));+}++// run `cargo test -p notification --features ai_tool inbound::ai_tool::test::print_list_notifications_input_schema -- --nocapture --include-ignored`+#[test]+#[ignore = "prints the input schema"]+fn print_list_notifications_input_schema() {+ let schema = generate_tool_input_schema!(ListNotifications);+ println!("{}", serde_json::to_string_pretty(&schema).unwrap());+}++// run `cargo test -p notification --features ai_tool inbound::ai_tool::test::print_list_notifications_output_schema -- --nocapture --include-ignored`+#[test]+#[ignore = "prints the output schema"]+fn print_list_notifications_output_schema() {+ let generator = ai::tool::minimized_output_schema_generator();+ let schema = generator.into_root_schema_for::<ListNotificationsResponse>();+ println!("{}", serde_json::to_string_pretty(&schema).unwrap());+}++#[test]+fn test_mark_notifications_seen_schema_validation() {+ let schema = generate_tool_input_schema!(MarkNotificationsSeen);++ let result = validate_tool_schema(&schema);+ assert!(result.is_ok(), "{:?}", result);++ let (name, description) = result.unwrap();+ assert_eq!(+ name, "MarkNotificationsSeen",+ "Tool name should match the schemars title"+ );+ assert!(+ description.contains("Mark one or more notifications as seen"),+ "Description should contain expected text"+ );+}++#[test]+fn test_mark_notifications_done_schema_validation() {+ let schema = generate_tool_input_schema!(MarkNotificationsDone);++ let result = validate_tool_schema(&schema);+ assert!(result.is_ok(), "{:?}", result);++ let (name, description) = result.unwrap();+ assert_eq!(+ name, "MarkNotificationsDone",+ "Tool name should match the schemars title"+ );+ assert!(+ description.contains("Mark one or more notifications as done"),+ "Description should contain expected text"+ );+}++#[test]+fn test_mark_notifications_seen_deserialization() {+ let json = r#"{"notificationIds": ["550e8400-e29b-41d4-a716-446655440000", "550e8400-e29b-41d4-a716-446655440001"]}"#;+ let tool: MarkNotificationsSeen = serde_json::from_str(json).unwrap();+ assert_eq!(tool.notification_ids.len(), 2);+}++// run `cargo test -p notification --features ai_tool inbound::ai_tool::test::print_mark_seen_input_schema -- --nocapture --include-ignored`+#[test]+#[ignore = "prints the input schema"]+fn print_mark_seen_input_schema() {+ let schema = generate_tool_input_schema!(MarkNotificationsSeen);+ println!("{}", serde_json::to_string_pretty(&schema).unwrap());+}++// run `cargo test -p notification --features ai_tool inbound::ai_tool::test::print_mark_done_input_schema -- --nocapture --include-ignored`+#[test]+#[ignore = "prints the input schema"]+fn print_mark_done_input_schema() {+ let schema = generate_tool_input_schema!(MarkNotificationsDone);+ println!("{}", serde_json::to_string_pretty(&schema).unwrap());+}++// run `cargo test -p notification --features ai_tool inbound::ai_tool::test::print_output_schema -- --nocapture --include-ignored`+#[test]+#[ignore = "prints the output schema"]+fn print_output_schema() {+ let generator = ai::tool::minimized_output_schema_generator();+ let schema = generator.into_root_schema_for::<MarkNotificationsResponse>();+ println!("{}", serde_json::to_string_pretty(&schema).unwrap());+}diff --git a/rust/cloud-storage/notification/src/lib.rs b/rust/cloud-storage/notification/src/lib.rsindex dd8e42a394..d6c50a9aa5 100644--- a/rust/cloud-storage/notification/src/lib.rs+++ b/rust/cloud-storage/notification/src/lib.rs@@ -8,7 +8,6 @@/// Domain layer containing core business logic, models, and port definitions.pub mod domain;/// Inbound adapters (HTTP handlers, queue worker).-#[cfg(feature = "axum")]pub mod inbound;/// Outbound adapters (database, queue, Redis, WebSocket gateway, SNS, SES).pub mod outbound;