Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(ai): add in channel notification support for ai generated messages (#5132)

Will Hutchinsonea63cf3fb341
diff --git a/Cargo.lock b/Cargo.lock
index 9bc18fd46b..a68c4c18d5 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -186,6 +186,8 @@ dependencies = [
"chat",
"chrono",
"connection",
+ "connection_gateway_client",
+ "contacts",
"cool_asserts",
"crm",
"dateparser",
@@ -8764,6 +8766,7 @@ dependencies = [
"call",
"channels",
"chat",
+ "connection_gateway_client",
"crm",
"database_env_vars",
"documents",
diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.toml
index d1c66e30bf..a6d00a8c80 100644
--- a/crates/ai_tools/Cargo.toml
+++ b/crates/ai_tools/Cargo.toml
@@ -26,6 +26,10 @@ dateparser.workspace = true
connection = { path = "../connection", default-features = false, features = [
"ports",
] }
+connection_gateway_client = { path = "../connection_gateway_client" }
+contacts = { path = "../contacts", default-features = false, features = [
+ "outbound",
+] }
crm = { path = "../crm" }
documents = { path = "../documents", features = ["ai_tools"] }
email = { path = "../email", features = ["ai_schema", "ai_tools", "axum", "outbound"] }
@@ -69,7 +73,7 @@ serde.workspace = true
serde_json.workspace = true
properties = { path = "../properties", features = ["ai_tools"] }
soup = { path = "../soup", features = ["ai_tools", "outbound"] }
-sqs_client = { path = "../sqs_client", default-features = false, features = ["email", "gmail"] }
+sqs_client = { path = "../sqs_client", default-features = false, features = ["email", "gmail", "search"] }
teams = { path = "../teams", default-features = false, features = ["ai_tools", "outbound"] }
sqlx.workspace = true
strum.workspace = true
diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rs
index 7c20a9f48f..a711c2c424 100644
--- a/crates/ai_tools/src/build_context.rs
+++ b/crates/ai_tools/src/build_context.rs
@@ -5,13 +5,14 @@
//! instead of duplicating the wiring logic.
use crate::tool_context::{
- NoOpCallRtcClient, NoOpConnectionService, NoOpNotificationIngress, NoOpSnsEndpointManager,
- ToolImportToolContext, ToolNotificationQueue, ToolServiceContext,
+ ChannelSideEffectClients, NoOpCallRtcClient, NoOpConnectionService, NoOpNotificationIngress,
+ NoOpSnsEndpointManager, ToolImportToolContext, ToolNotificationQueue, ToolServiceContext,
};
use anthropic::toolset::AnthropicToolContext;
use anyhow::Context;
use channels::domain::list_service::ChannelListServiceImpl;
use channels::outbound::pg_channels_repo::PgChannelsRepo;
+use connection_gateway_client::ConnectionGatewayClient;
use documents::domain::models::CloudFrontConfig;
use documents::inbound::toolset::DocumentToolContext;
use documents::outbound::editing_worker_client::ReqwestEditingWorkerClient;
@@ -33,8 +34,8 @@ use lexical_client::LexicalClient;
use macro_env::Environment;
use macro_env_var::{env_var, maybe_env_var};
use macro_service_urls::{
- AiEditingWorkerUrl, DocumentStorageServiceUrl, EmailServiceUrl, LexicalServiceUrl,
- SyncServiceUrl,
+ AiEditingWorkerUrl, ConnectionGatewayUrl, DocumentStorageServiceUrl, EmailServiceUrl,
+ LexicalServiceUrl, SyncServiceUrl,
};
use notification::domain::service::{NotificationReaderService, PlatformArnConfig};
use notification::outbound::queue::SqsQueue;
@@ -57,6 +58,7 @@ env_var! {
DocumentStorageServiceCloudfrontSignerPublicKeyId,
DocumentStorageServiceCloudfrontSignerPrivateKeySecretName,
DocumentPermissionJwt,
+ InternalApiKey,
KafkaBrokers,
}
}
@@ -83,7 +85,8 @@ maybe_env_var! {
/// `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_DISTRIBUTION_URL`,
/// `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID`,
/// `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME`,
-/// `KAFKA_BROKERS`.
+/// `INTERNAL_API_KEY` (presented to the connection gateway for realtime
+/// channel side effects), `KAFKA_BROKERS`.
///
/// Service URLs are resolved through the `macro_service_urls` crate, and queue
/// names through the `macro_queues` crate (both using optional `OVERRIDE_*` env
@@ -106,6 +109,7 @@ pub async fn build_tool_service_context_from_env(
let email_service_url = EmailServiceUrl::new()?.to_string();
let lexical_service_url = LexicalServiceUrl::new()?.to_string();
let ai_editing_worker_url = AiEditingWorkerUrl::new()?.to_string();
+ let connection_gateway_url = ConnectionGatewayUrl::new()?.to_string();
let aws_config = macro_aws_config::get_macro_aws_config().await;
let aws_sqs_client = aws_sdk_sqs::Client::new(&aws_config);
@@ -140,7 +144,7 @@ pub async fn build_tool_service_context_from_env(
let notification_queue = if enable_notification_queue {
let notification_queue = macro_queues::NotificationIngressQueue::new();
ToolNotificationQueue::Sqs(SqsQueue::new(
- aws_sqs_client,
+ aws_sqs_client.clone(),
notification_queue.to_string(),
))
} else {
@@ -203,10 +207,6 @@ pub async fn build_tool_service_context_from_env(
PgChannelsRepo::new(pool.clone()),
frecency_storage,
);
- let channel_tool_context = crate::tool_context::build_channel_tool_context(
- pool.clone(),
- Arc::new(lexical_client.clone()),
- );
let email_service_for_tools: Arc<crate::tool_context::ToolEmailService> =
Arc::new(email_service.clone());
let foreign_entity_service =
@@ -255,6 +255,22 @@ pub async fn build_tool_service_context_from_env(
macro_event_broker::KafkaEventPublisher::new(env.kafka_brokers.as_ref())
.context("failed to create kafka event publisher")?,
);
+ // Channel messages sent by AI tools dispatch the same side effects as the
+ // document-storage channel API (realtime, notifications, search indexing,
+ // contact sync, broker events), so agent-sent messages notify mentioned
+ // users and stream to connected clients instead of landing silently.
+ let channel_tool_context = crate::tool_context::build_channel_tool_context_with_side_effects(
+ pool.clone(),
+ Arc::new(lexical_client.clone()),
+ ChannelSideEffectClients {
+ connection_gateway: Arc::new(ConnectionGatewayClient::new(
+ env.internal_api_key.to_string(),
+ connection_gateway_url,
+ )),
+ sqs: aws_sqs_client,
+ macro_event_broker: macro_event_broker.clone(),
+ },
+ );
let document_service = documents::domain::service::DocumentServiceImpl {
repo: document_repo,
cloudfront_config,
diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rs
index 9ab4d8b670..4eab9ad061 100644
--- a/crates/ai_tools/src/lib.rs
+++ b/crates/ai_tools/src/lib.rs
@@ -43,20 +43,21 @@ pub use search::search_toolset;
#[cfg(any(test, feature = "test-support"))]
pub use tool_context::no_op_schedule_context;
pub use tool_context::{
- NoOpCallRtcClient, NoOpConnectionService, NoOpNotificationIngress, NoOpNotificationService,
- NoOpScheduleContext, NoOpSnsEndpointManager, NoOpTaskProperties, RequestContext,
- TaskPropertiesAdapter, ToolCallRecordQueryService, ToolCallService, ToolCallToolContext,
- ToolChannelEventDispatcher, ToolChannelMessagesService, ToolChannelToolContext,
- ToolChatService, ToolChatToolContext, ToolCommsService, ToolCrmService, ToolCrmToolContext,
- ToolDocumentService, ToolDocumentToolContext, ToolEmailService, ToolEmailToolContext,
- ToolEntityAccessManagementService, ToolEntityAccessService, ToolEntityCreator,
- ToolForeignEntityService, ToolFrecencyService, ToolImportService, ToolImportToolContext,
- ToolNotificationQueue, ToolNotificationService, ToolNotificationToolContext,
- ToolPropertiesService, ToolPropertiesToolContext, ToolServiceContext, ToolSoupService,
- ToolSystemPropertiesService, ToolTeamService, ToolTeamToolContext, ToolUserEmailService,
- build_channel_tool_context, build_channel_tool_context_with_dispatcher, build_crm_tool_context,
- build_properties_service, build_properties_tool_context, build_task_properties_adapter,
- build_team_repository, build_team_tool_context,
+ ChannelSideEffectClients, NoOpCallRtcClient, NoOpConnectionService, NoOpNotificationIngress,
+ NoOpNotificationService, NoOpScheduleContext, NoOpSnsEndpointManager, NoOpTaskProperties,
+ RequestContext, TaskPropertiesAdapter, ToolCallRecordQueryService, ToolCallService,
+ ToolCallToolContext, ToolChannelEventDispatcher, ToolChannelMessagesService,
+ ToolChannelToolContext, ToolChatService, ToolChatToolContext, ToolCommsService, ToolCrmService,
+ ToolCrmToolContext, ToolDocumentService, ToolDocumentToolContext, ToolEmailService,
+ ToolEmailToolContext, ToolEntityAccessManagementService, ToolEntityAccessService,
+ ToolEntityCreator, ToolForeignEntityService, ToolFrecencyService, ToolImportService,
+ ToolImportToolContext, ToolNotificationQueue, ToolNotificationService,
+ ToolNotificationToolContext, ToolPropertiesService, ToolPropertiesToolContext,
+ ToolServiceContext, ToolSoupService, ToolSystemPropertiesService, ToolTeamService,
+ ToolTeamToolContext, ToolUserEmailService, build_channel_tool_context_with_dispatcher,
+ build_channel_tool_context_with_side_effects, build_channel_tool_context_without_side_effects,
+ build_crm_tool_context, build_properties_service, build_properties_tool_context,
+ build_task_properties_adapter, build_team_repository, build_team_tool_context,
};
pub type AiToolSet = AsyncToolCollection<ToolServiceContext>;
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index 0880228775..3968bca628 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -8,13 +8,21 @@ use call::outbound::pg_call_repo::PgCallRepo;
use call::outbound::s3_recording_storage::S3RecordingStorage;
use channels::domain::ports::ChannelEventDispatcher;
use channels::domain::service::{NoopChannelEventDispatcher, NoopChannelReferenceSharePermissions};
+use channels::domain::side_effects::{ChannelSideEffectService, SpawnedChannelEventDispatcher};
use channels::domain::{list_service::ChannelListServiceImpl, service::ChannelServiceImpl};
use channels::inbound::toolset::ChannelToolContext;
-use channels::outbound::pg_channels_repo::PgChannelsRepo;
+use channels::outbound::{
+ connection_gateway_realtime::ConnectionGatewayChannelRealtimePublisher,
+ contacts_dispatcher::ContactsChannelDispatcher, notification_sender::NotificationChannelSender,
+ pg_channels_repo::PgChannelsRepo, pg_side_effect_context::PgChannelSideEffectContext,
+ sqs_search_indexer::SqsChannelSearchIndexer,
+};
use chat::domain::service::ChatServiceImpl;
use chat::inbound::toolset::ChatToolContext;
use chat::outbound::postgres::PgChatRepo;
use connection::domain::ports::ConnectionService;
+use connection_gateway_client::ConnectionGatewayClient;
+use contacts::{domain::service::SqsContactsIngress, outbound::ingress::SqsContactsQueue};
use crm::inbound::toolset::CrmToolContext;
use documents::{domain::ports::TaskPropertiesPort, inbound::toolset::DocumentToolContext};
use email::{
@@ -27,7 +35,9 @@ use foreign_entity::{
outbound::pg_foreign_entity_repo::PgForeignEntityRepo,
};
use lexical_mention_extractor::LexicalMentionExtractor;
+use macro_event_broker::{KafkaEventPublisher, MacroEventBrokerService};
use macro_user_id::user_id::MacroUserIdStr;
+use notification::domain::service::SqsNotificationIngress;
use notification::inbound::ai_tool::NotificationToolContext;
use properties::inbound::toolset::PropertiesToolContext;
use soup::{domain::service::SoupImpl, inbound::toolset::SoupToolContext};
@@ -90,10 +100,11 @@ pub type ToolCommsService = ChannelListServiceImpl<
frecency::outbound::postgres::FrecencyPgStorage,
>;
-/// A channel event dispatcher injected into the tool service. Defaults to a
-/// no-op; hosts that own the realtime/notification clients (e.g. the
-/// document-storage service running the Macro agent) inject a real
-/// side-effect-wired dispatcher so agent-sent messages notify and broadcast.
+/// A channel event dispatcher injected into the tool service, wired via
+/// [`build_channel_tool_context_with_side_effects`] (or a host-owned
+/// side-effect service, as in the document-storage service) so agent-sent
+/// messages notify and broadcast. The no-op variant exists for tests and
+/// hosts without the side-effect clients.
pub type ToolChannelEventDispatcher = std::sync::Arc<dyn ChannelEventDispatcher>;
/// Type alias for the channel messages service implementation used by AI tools.
@@ -109,10 +120,13 @@ pub type ToolChannelToolContext =
ChannelToolContext<ToolChannelMessagesService, ToolEntityAccessService>;
/// Build the channel AI tool context from a Postgres pool, with no side
-/// effects (no notifications/realtime) for hosts that lack those clients.
+/// effects (no notifications/realtime/search indexing) — messages sent
+/// through it are persisted but never notify anyone. Only for tests and
+/// hosts that genuinely lack the side-effect clients; production hosts
+/// should use [`build_channel_tool_context_with_side_effects`].
/// `lexical_client` derives the mention list for messages the agent sends,
/// since bot-authored content arrives without the editor-tracked mentions.
-pub fn build_channel_tool_context(
+pub fn build_channel_tool_context_without_side_effects(
pool: sqlx::PgPool,
lexical_client: Arc<lexical_client::LexicalClient>,
) -> ToolChannelToolContext {
@@ -123,6 +137,61 @@ pub fn build_channel_tool_context(
)
}
+/// Clients a host provides to wire the real channel side effects for AI
+/// tools. Queue names (notification ingress, contacts, search events) are
+/// resolved through `macro_queues`, so hosts only supply the shared clients.
+pub struct ChannelSideEffectClients {
+ /// Connection gateway client used to fan realtime updates out to
+ /// connected clients.
+ pub connection_gateway: Arc<ConnectionGatewayClient>,
+ /// SQS client used for the notification-ingress, contacts, and
+ /// search-event queues.
+ pub sqs: aws_sdk_sqs::Client,
+ /// Broker publishing channel events to the `macro.channels` topic.
+ pub macro_event_broker: MacroEventBrokerService<KafkaEventPublisher>,
+}
+
+/// Build the channel AI tool context dispatching the same side effects as the
+/// document-storage channel API: realtime updates via the connection gateway,
+/// notifications via the notification-ingress queue, search indexing via the
+/// search-event queue, contact sync via the contacts queue, and channel
+/// events on the macro event broker. Hosts that let the agent send channel
+/// messages need this so mentions and replies notify their recipients.
+pub fn build_channel_tool_context_with_side_effects(
+ pool: sqlx::PgPool,
+ lexical_client: Arc<lexical_client::LexicalClient>,
+ clients: ChannelSideEffectClients,
+) -> ToolChannelToolContext {
+ let notification_ingress = Arc::new(SqsNotificationIngress {
+ queue: notification::outbound::queue::SqsQueue::new(
+ clients.sqs.clone(),
+ macro_queues::NotificationIngressQueue::new().to_string(),
+ ),
+ });
+ let contacts_ingress = Arc::new(SqsContactsIngress {
+ queue: SqsContactsQueue::new(
+ clients.sqs.clone(),
+ macro_queues::ContactsQueue::new().to_string(),
+ ),
+ });
+ let search_event_queue = macro_queues::SearchEventQueue::new();
+ let search_sqs =
+ Arc::new(sqs_client::SQS::new(clients.sqs).search_event_queue(&search_event_queue));
+ let side_effects = ChannelSideEffectService::new(
+ PgChannelSideEffectContext::new(pool.clone()),
+ ConnectionGatewayChannelRealtimePublisher::new(clients.connection_gateway),
+ NotificationChannelSender::new(notification_ingress),
+ SqsChannelSearchIndexer::new(search_sqs),
+ ContactsChannelDispatcher::new(contacts_ingress),
+ )
+ .with_macro_event_broker(clients.macro_event_broker);
+ build_channel_tool_context_with_dispatcher(
+ pool,
+ Arc::new(SpawnedChannelEventDispatcher::new(side_effects)),
+ lexical_client,
+ )
+}
+
/// Build the channel AI tool context wired to `dispatcher`, so messages sent by
/// agent tools fire the host's channel side effects (notifications, realtime,
/// search indexing).
diff --git a/infra/packages/shared/src/ai_tools.ts b/infra/packages/shared/src/ai_tools.ts
index a21be450ca..cff58007bb 100644
--- a/infra/packages/shared/src/ai_tools.ts
+++ b/infra/packages/shared/src/ai_tools.ts
@@ -33,6 +33,18 @@ export function getAiToolsInfra(): AiToolsInfra {
'ai-tools-email-service-stack',
{ name: `macro-inc/email-service/${stack}` }
);
+ const notificationServiceStack = new pulumi.StackReference(
+ 'ai-tools-notification-service-stack',
+ { name: `macro-inc/notification-service/${stack}` }
+ );
+ const searchEventQueueStack = new pulumi.StackReference(
+ 'ai-tools-search-event-queue-stack',
+ { name: `macro-inc/search-event-queue/${stack}` }
+ );
+ const contactsServiceStack = new pulumi.StackReference(
+ 'ai-tools-contacts-service-stack',
+ { name: `macro-inc/contacts-service/${stack}` }
+ );
const documentStorageBucketArn: pulumi.Output<string> = cloudStorageStack
.getOutput('documentStorageBucketArn')
@@ -52,6 +64,19 @@ export function getAiToolsInfra(): AiToolsInfra {
.getOutput('gmailOpsQueueArn')
.apply((v) => v as string);
+ const notificationIngressQueueArn: pulumi.Output<string> =
+ notificationServiceStack
+ .getOutput('notificationIngressQueueArn')
+ .apply((v) => v as string);
+
+ const searchEventQueueArn: pulumi.Output<string> = searchEventQueueStack
+ .getOutput('searchEventQueueArn')
+ .apply((v) => v as string);
+
+ const contactsQueueArn: pulumi.Output<string> = contactsServiceStack
+ .getOutput('contactsQueueArn')
+ .apply((v) => v as string);
+
const CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME = `linksharing-private-key-${stack}`;
const cloudfrontPrivateKeySecretArn: pulumi.Output<string> =
aws.secretsmanager
@@ -74,7 +99,13 @@ export function getAiToolsInfra(): AiToolsInfra {
cloudfrontPrivateKeySecretArn,
mcpCredentialsKeyArn,
],
- queueArns: [emailScheduledQueueArn, gmailOpsQueueArn],
+ queueArns: [
+ emailScheduledQueueArn,
+ gmailOpsQueueArn,
+ notificationIngressQueueArn,
+ searchEventQueueArn,
+ contactsQueueArn,
+ ],
bucketArns: [documentStorageBucketArn, docxUploadBucketArn],
};
}
diff --git a/infra/stacks/agent-schedule-service/index.ts b/infra/stacks/agent-schedule-service/index.ts
index 871f6a95a3..7fd53beb0e 100644
--- a/infra/stacks/agent-schedule-service/index.ts
+++ b/infra/stacks/agent-schedule-service/index.ts
@@ -4,7 +4,6 @@ import {
config,
getAiToolsInfra,
getMacroApiToken,
- getMacroNotify,
stack,
} from '../../packages/shared';
import { get_coparse_api_vpc } from '../../packages/vpc';
@@ -26,7 +25,6 @@ const jwtSecretKeyArn = aws.secretsmanager
.apply((secret) => secret.arn);
const MACRO_API_TOKENS = getMacroApiToken();
-const { notificationIngressQueueArn } = getMacroNotify();
// ── AI tools infra ───────────────────────────────────────────────────────────
@@ -64,7 +62,7 @@ const service = new AgentScheduleService(`agent-schedule-service-${stack}`, {
MACRO_API_TOKENS.macroApiTokenPublicKeyArn,
...aiTools.secretArns,
],
- queueArns: [notificationIngressQueueArn, ...aiTools.queueArns],
+ queueArns: [...aiTools.queueArns],
bucketArns: [...aiTools.bucketArns],
containerEnvVars: [
{
diff --git a/infra/stacks/document-cognition-service/index.ts b/infra/stacks/document-cognition-service/index.ts
index 921c479004..a453fab513 100644
--- a/infra/stacks/document-cognition-service/index.ts
+++ b/infra/stacks/document-cognition-service/index.ts
@@ -4,8 +4,6 @@ import {
config,
getAiToolsInfra,
getMacroApiToken,
- getMacroNotify,
- getSearchEventQueue,
stack,
} from '../../packages/shared';
import { Queue } from '../../packages/resources';
@@ -105,10 +103,6 @@ const cloudStorageClusterName: pulumi.Output<string> = cloudStorageStack
.getOutput('cloudStorageClusterName')
.apply((arn) => arn as string);
-const { notificationIngressQueueArn } = getMacroNotify();
-
-const { searchEventQueueArn } = getSearchEventQueue();
-
// ── AI projection queue ──────────────────────────────────────────────────────
// This service both produces (on upsert) and consumes (via the inbound worker)
// ai projection materialization messages, so the queue is owned here. The Queue
@@ -164,8 +158,6 @@ const documentCognitionService = new DocumentCognitionService(
queueArns: [
documentTextExtractorQueueArn,
deleteChatQueueArn,
- searchEventQueueArn,
- notificationIngressQueueArn,
aiProjectionQueue.queue.arn,
...aiTools.queueArns,
],
diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rs
index a8add69638..e2e496fedf 100644
--- a/services/document_cognition_service/src/api/context/test.rs
+++ b/services/document_cognition_service/src/api/context/test.rs
@@ -352,7 +352,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
notification_tool_context: notification_tool_context.clone(),
import_tool_context: ai_tools::ToolImportToolContext::unwired(),
chat_tool_context,
- channel_tool_context: ai_tools::build_channel_tool_context(
+ channel_tool_context: ai_tools::build_channel_tool_context_without_side_effects(
pool.clone(),
std::sync::Arc::new(test_lexical_client),
),
diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rs
index e128e264d1..b07d7742d4 100644
--- a/services/document_cognition_service/src/main.rs
+++ b/services/document_cognition_service/src/main.rs
@@ -416,8 +416,23 @@ async fn main() -> anyhow::Result<()> {
tracing::info!("initialized chat tool context");
- let channel_tool_context =
- ai_tools::build_channel_tool_context(db.clone(), lexical_client.clone());
+ // Channel messages sent by AI tools (chat, agents) dispatch the same side
+ // effects as the document-storage channel API, so mentions and replies
+ // notify recipients and stream to connected clients.
+ let channels_connection_gateway =
+ Arc::new(connection_gateway_client::ConnectionGatewayClient::new(
+ internal_api_key.clone(),
+ ConnectionGatewayUrl::new()?.to_string(),
+ ));
+ let channel_tool_context = ai_tools::build_channel_tool_context_with_side_effects(
+ db.clone(),
+ lexical_client.clone(),
+ ai_tools::ChannelSideEffectClients {
+ connection_gateway: channels_connection_gateway.clone(),
+ sqs: aws_sdk_sqs::Client::new(&aws_config),
+ macro_event_broker: macro_event_broker.clone(),
+ },
+ );
let recorder = ai_usage::pg_recorder(db.clone());
// The import pipeline: staged/imported external items, gather jobs over
@@ -433,12 +448,8 @@ async fn main() -> anyhow::Result<()> {
// Nudges the user's connected clients when import rows flip, so setup
// sections and chat surfaces update immediately instead of on the next
// poll (see import::outbound::gateway_notifier).
- let import_notify = import::outbound::gateway_notifier::gateway_import_notify(Arc::new(
- connection_gateway_client::ConnectionGatewayClient::new(
- internal_api_key.clone(),
- ConnectionGatewayUrl::new()?.to_string(),
- ),
- ));
+ let import_notify =
+ import::outbound::gateway_notifier::gateway_import_notify(channels_connection_gateway);
let entity_creator = ai_tools::ToolEntityCreator {
document_creator: document_tool_context.creator.clone(),
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index cb18d639e9..48aef0cce6 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -822,9 +822,10 @@ async fn main() -> anyhow::Result<()> {
let mut macro_agent_tool_context = ai_tools::build_tool_service_context_from_env(db.clone())
.await
.context("failed to build Macro agent tool context")?;
- // Wire the agent's SendChannelMessage tool to the same side-effect pipeline
- // as the HTTP API, so messages it posts fire notifications and realtime
- // updates (the generic env builder uses a no-op dispatcher otherwise).
+ // Wire the agent's SendChannelMessage tool to this service's own
+ // side-effect pipeline so agent-posted messages share the exact instance
+ // used by the HTTP API, including the in-process bot trigger sender (the
+ // env builder wires an equivalent pipeline, but without bot triggers).
macro_agent_tool_context.channel_tool_context =
ai_tools::build_channel_tool_context_with_dispatcher(
db.clone(),
diff --git a/services/mcp_service/Cargo.toml b/services/mcp_service/Cargo.toml
index 5034b018eb..e8a7207e81 100644
--- a/services/mcp_service/Cargo.toml
+++ b/services/mcp_service/Cargo.toml
@@ -26,6 +26,7 @@ call = { path = "../../crates/call", default-features = false, features = [
] }
channels = { path = "../../crates/channels", features = ["outbound"] }
chat = { path = "../../crates/chat", features = ["ai_tools", "outbound"] }
+connection_gateway_client = { path = "../../crates/connection_gateway_client" }
crm = { path = "../../crates/crm" }
database_env_vars = { path = "../../crates/database_env_vars" }
documents = { path = "../../crates/documents", features = ["ai_tools"] }
diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rs
index 96ae574eda..04e18f4d37 100644
--- a/services/mcp_service/src/context.rs
+++ b/services/mcp_service/src/context.rs
@@ -29,8 +29,8 @@ use frecency::domain::services::FrecencyQueryServiceImpl;
use frecency::outbound::postgres::FrecencyPgStorage;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_service_urls::{
- AiEditingWorkerUrl, DocumentStorageServiceUrl, EmailServiceUrl, LexicalServiceUrl,
- SyncServiceUrl,
+ AiEditingWorkerUrl, ConnectionGatewayUrl, DocumentStorageServiceUrl, EmailServiceUrl,
+ LexicalServiceUrl, SyncServiceUrl,
};
use mcp_auth_proxy::{
domain::service::McpAuthProxyServiceImpl,
@@ -70,7 +70,7 @@ pub async fn build_context(config: &Config) -> anyhow::Result<McpContext> {
let queue_aws_client = aws_sdk_sqs::Client::new(&aws_config);
let email_scheduled_queue = macro_queues::EmailScheduledQueue::new();
let gmail_ops_queue = macro_queues::GmailOpsQueue::new();
- let sqs_client = sqs_client::SQS::new(queue_aws_client)
+ let sqs_client = sqs_client::SQS::new(queue_aws_client.clone())
.email_scheduled_queue(email_scheduled_queue.as_ref())
.gmail_ops_queue(gmail_ops_queue.as_ref());
@@ -94,6 +94,7 @@ pub async fn build_context(config: &Config) -> anyhow::Result<McpContext> {
&db,
&secretsmanager_client,
sqs_client,
+ queue_aws_client,
config.document_storage_service_auth_key.as_ref().to_owned(),
sync_service_auth_key.as_ref().to_owned(),
)
@@ -120,6 +121,7 @@ async fn build_tool_context(
db: &PgPool,
secretsmanager_client: &secretsmanager_client::SecretsManager,
sqs_client: sqs_client::SQS,
+ queue_aws_client: aws_sdk_sqs::Client,
document_storage_service_auth_key: String,
sync_service_auth_key: String,
) -> anyhow::Result<ToolServiceContext> {
@@ -313,6 +315,22 @@ async fn build_tool_context(
EntityAccessServiceImpl::new(PgAccessRepository::new(db.clone())),
);
+ // Channel messages sent through MCP tools dispatch the same side effects
+ // as the document-storage channel API, so mentions and replies notify
+ // recipients and stream to connected clients.
+ let channel_tool_context = ai_tools::build_channel_tool_context_with_side_effects(
+ db.clone(),
+ lexical_client.clone(),
+ ai_tools::ChannelSideEffectClients {
+ connection_gateway: Arc::new(connection_gateway_client::ConnectionGatewayClient::new(
+ config.internal_api_key.to_string(),
+ ConnectionGatewayUrl::new()?.to_string(),
+ )),
+ sqs: queue_aws_client,
+ macro_event_broker: macro_event_broker.clone(),
+ },
+ );
+
let tool_context = ToolServiceContext {
email_service_client: Arc::new(EmailServiceClientExternal::new(
email_service_client.url().to_owned(),
@@ -327,10 +345,7 @@ async fn build_tool_context(
notification_tool_context,
import_tool_context: ToolImportToolContext::unwired(),
chat_tool_context,
- channel_tool_context: ai_tools::build_channel_tool_context(
- db.clone(),
- lexical_client.clone(),
- ),
+ channel_tool_context,
team_tool_context: ai_tools::build_team_tool_context(db.clone()),
crm_tool_context: ai_tools::build_crm_tool_context(db.clone()),
schedule_tool_context: NoOpScheduleContext,