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(call): ai toolset (#2802)
Will Hutchinsona1f7a84a35f5
diff --git a/js/app/packages/core/component/AI/component/tool/ListCallRecords.tsx b/js/app/packages/core/component/AI/component/tool/ListCallRecords.tsxnew file mode 100644index 0000000000..c913f4a7fc--- /dev/null+++ b/js/app/packages/core/component/AI/component/tool/ListCallRecords.tsx@@ -0,0 +1,20 @@+import PhoneList from '@phosphor-icons/core/regular/phone-list.svg';+import { BaseTool } from './BaseTool';+import { createToolRenderer } from './ToolRenderer';++const handler = createToolRenderer({+ name: 'ListCallRecords',+ render: (ctx) => (+ <BaseTool type="call" icon={PhoneList} renderContext={ctx.renderContext}>+ List call records+ {ctx.tool.data.channelId ? (+ <>+ {' '}+ in <span class="text-accent">channel {ctx.tool.data.channelId}</span>+ </>+ ) : null}+ </BaseTool>+ ),+});++export const listCallRecordsHandler = handler;diff --git a/js/app/packages/core/component/AI/component/tool/ReadCallRecord.tsx b/js/app/packages/core/component/AI/component/tool/ReadCallRecord.tsxnew file mode 100644index 0000000000..7ac8c8951a--- /dev/null+++ b/js/app/packages/core/component/AI/component/tool/ReadCallRecord.tsx@@ -0,0 +1,15 @@+import Microphone from '@phosphor-icons/core/regular/microphone.svg';+import { BaseTool } from './BaseTool';+import { createToolRenderer } from './ToolRenderer';++const handler = createToolRenderer({+ name: 'ReadCallRecord',+ render: (ctx) => (+ <BaseTool type="call" icon={Microphone} renderContext={ctx.renderContext}>+ Read call transcript{' '}+ <span class="text-accent">{ctx.tool.data.callId}</span>+ </BaseTool>+ ),+});++export const readCallRecordHandler = handler;diff --git a/js/app/packages/core/component/AI/component/tool/handler.tsx b/js/app/packages/core/component/AI/component/tool/handler.tsxindex 6383c98813..47ee5498ed 100644--- a/js/app/packages/core/component/AI/component/tool/handler.tsx+++ b/js/app/packages/core/component/AI/component/tool/handler.tsx@@ -8,11 +8,13 @@ import { Dynamic } from 'solid-js/web';import { bashCodeExecutionHandler } from './BashCodeExecution';import { createDocumentHandler } from './CreateDocument';import { getThreadHandler } from './GetThread';+import { listCallRecordsHandler } from './ListCallRecords';import { listEntitiesHandler } from './ListEntities';import {getEntityPropertiesHandler,setEntityPropertyHandler,} from './Properties';+import { readCallRecordHandler } from './ReadCallRecord';import { readContentHandler } from './ReadContent';import { readMetadataHandler } from './ReadMetadata';import { readThreadHandler } from './ReadThread';@@ -32,12 +34,14 @@ import { webSearchHandler } from './WebSearch';const toolHandlers: ToolHandlerMap<RenderContext> = {GetEntityProperties: getEntityPropertiesHandler,+ ListCallRecords: listCallRecordsHandler,ListEntities: listEntitiesHandler,bash_code_execution: bashCodeExecutionHandler,ContentSearch: contentSearchHandler,CreateDocument: createDocumentHandler,GetThread: getThreadHandler,NameSearch: nameSearchHandler,+ ReadCallRecord: readCallRecordHandler,ReadThread: readThreadHandler,ReadContent: readContentHandler,ReadMetadata: readMetadataHandler,diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.tsindex badebba6c0..b63ac8069f 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts@@ -412,6 +412,31 @@ export const GetThreadResponse = z.object({threadId: z.string().uuid(),});+export const ListCallRecords = z+ .object({+ attended: z.union([z.boolean(), z.null()]),+ channelId: z.union([z.string().uuid(), z.null()]),+ })+ .strict();++export const ListCallRecordsResponse = z.object({+ records: z.array(+ z.object({+ callId: z.string().uuid(),+ channelId: z.string().uuid(),+ channelName: z.union([z.string(), z.null()]).optional(),+ createdBy: z.string(),+ durationMs: z.union([z.number().int(), z.null()]).optional(),+ endedAt: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ isActive: z.boolean(),+ participants: z.array(z.string()),+ startedAt: z.string().datetime({ offset: true }),+ })+ ),+});+export const ListEntities = z.object({includeTypes: z.union([@@ -495,6 +520,22 @@ export const NameSearch = z}).strict();+export const ReadCallRecord = z.object({ callId: z.string().uuid() }).strict();++export const ReadCallRecordResponse = z.object({+ callId: z.string().uuid(),+ transcript: z.array(+ z.object({+ content: z.string(),+ endedAt: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ speakerId: z.string(),+ startedAt: z.string().datetime({ offset: true }),+ })+ ),+});+export const ReadContent = z.object({ documentId: z.string().uuid() }).strict();export const ReadContentResponse = z.object({diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts b/js/app/packages/service-clients/service-cognition/generated/tools/tool.tsindex 2cbdec4bba..27429352a6 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts@@ -25,11 +25,19 @@ type ToolParserMap = {response: types.GetEntityPropertiesResponse;};GetThread: { call: types.GetThread; response: types.GetThreadResponse };+ ListCallRecords: {+ call: types.ListCallRecords;+ response: types.ListCallRecordsResponse;+ };ListEntities: {call: types.ListEntities;response: types.ListEntitiesResponse;};NameSearch: { call: types.NameSearch; response: types.SearchToolResponse };+ ReadCallRecord: {+ call: types.ReadCallRecord;+ response: types.ReadCallRecordResponse;+ };ReadContent: { call: types.ReadContent; response: types.ReadContentResponse };ReadMetadata: {call: types.ReadMetadata;@@ -74,6 +82,10 @@ const toolParserMap = {response: schemas.GetEntityPropertiesResponse,},GetThread: { call: schemas.GetThread, response: schemas.GetThreadResponse },+ ListCallRecords: {+ call: schemas.ListCallRecords,+ response: schemas.ListCallRecordsResponse,+ },ListEntities: {call: schemas.ListEntities,response: schemas.ListEntitiesResponse,@@ -82,6 +94,10 @@ const toolParserMap = {call: schemas.NameSearch,response: schemas.SearchToolResponse,},+ ReadCallRecord: {+ call: schemas.ReadCallRecord,+ response: schemas.ReadCallRecordResponse,+ },ReadContent: {call: schemas.ReadContent,response: schemas.ReadContentResponse,@@ -140,11 +156,19 @@ type ToolDataMap = {response: types.GetEntityPropertiesResponse;};GetThread: { call: types.GetThread; response: types.GetThreadResponse };+ ListCallRecords: {+ call: types.ListCallRecords;+ response: types.ListCallRecordsResponse;+ };ListEntities: {call: types.ListEntities;response: types.ListEntitiesResponse;};NameSearch: { call: types.NameSearch; response: types.SearchToolResponse };+ ReadCallRecord: {+ call: types.ReadCallRecord;+ response: types.ReadCallRecordResponse;+ };ReadContent: { call: types.ReadContent; response: types.ReadContentResponse };ReadMetadata: {call: types.ReadMetadata;diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.tsindex 632bc91164..67fd9933b9 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts@@ -821,6 +821,81 @@ export interface GetThreadResponse {threadId: string;}+/* eslint-disable */+/**+ * This file was automatically generated by json-schema-to-typescript.+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,+ * and run json-schema-to-typescript to regenerate this file.+ */++/**+ * List recent call records the user can access, ordered by start time descending. Results are scoped to channels the user is a member of. Transcripts are NOT included — call ReadCallRecord with a specific callId to fetch a transcript.+ */+export interface ListCallRecords {+ /**+ * Optional filter on whether the caller joined the call. true = only calls the user attended; false = only calls the user did not attend; omit to include both.+ */+ attended: boolean | null;+ /**+ * Optional channel id. When provided, only calls from that channel are returned.+ */+ channelId: string | null;+}++/* eslint-disable */+/**+ * This file was automatically generated by json-schema-to-typescript.+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,+ * and run json-schema-to-typescript to regenerate this file.+ */++/**+ * Response for [`ListCallRecords`].+ */+export interface ListCallRecordsResponse {+ /**+ * Call records ordered by start time descending.+ */+ records: {+ /**+ * The call's unique identifier.+ */+ callId: string;+ /**+ * The channel the call belongs to.+ */+ channelId: string;+ /**+ * The channel's display name, if resolvable.+ */+ channelName?: string | null;+ /**+ * The user who created the call.+ */+ createdBy: string;+ /**+ * Call duration in milliseconds. Absent if the call is still active.+ */+ durationMs?: number | null;+ /**+ * When the call ended. Absent if the call is still active.+ */+ endedAt?: string | null;+ /**+ * True if the call is currently active.+ */+ isActive: boolean;+ /**+ * IDs of users who participated in the call.+ */+ participants: string[];+ /**+ * When the call started.+ */+ startedAt: string;+ }[];+}+/* eslint-disable *//*** This file was automatically generated by json-schema-to-typescript.@@ -915,6 +990,61 @@ export interface NameSearch {name: string;}+/* eslint-disable */+/**+ * This file was automatically generated by json-schema-to-typescript.+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,+ * and run json-schema-to-typescript to regenerate this file.+ */++/**+ * Retrieve the transcript for a specific call record. Use ListCallRecords first to find the callId. Only the transcript is returned — other metadata (participants, duration, etc.) is already available from ListCallRecords.+ */+export interface ReadCallRecord {+ /**+ * The id of the call whose transcript you want to retrieve.+ */+ callId: string;+}++/* eslint-disable */+/**+ * This file was automatically generated by json-schema-to-typescript.+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,+ * and run json-schema-to-typescript to regenerate this file.+ */++/**+ * Response for [`ReadCallRecord`] — the transcript of the requested call.+ */+export interface ReadCallRecordResponse {+ /**+ * The call id the transcript belongs to.+ */+ callId: string;+ /**+ * Transcript segments in chronological order.+ */+ transcript: {+ /**+ * The transcribed text.+ */+ content: string;+ /**+ * When the speaker stopped (if known).+ */+ endedAt?: string | null;+ /**+ * The speaker's user id.+ */+ speakerId: string;+ /**+ * When the speaker started this segment.+ */+ startedAt: string;+ }[];+}+/* eslint-disable *//*** This file was automatically generated by json-schema-to-typescript.diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex a35a259233..18688ece28 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -130,6 +130,7 @@ dependencies = ["rand 0.9.3","readonly_pool","remote_env_var",+ "rootcause","schemars","scribe","search_service_client",@@ -1774,7 +1775,9 @@ dependencies = [name = "call"version = "0.1.0"dependencies = [+ "ai","anyhow",+ "async-trait","aws-sdk-s3","axum","chrono",@@ -1796,6 +1799,7 @@ dependencies = ["models_pagination","models_permissions","notification",+ "schemars","serde","serde_json","sqlx",diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.tomlindex 282d321f9d..fc2d98b3ce 100644--- a/rust/cloud-storage/ai_tools/Cargo.toml+++ b/rust/cloud-storage/ai_tools/Cargo.toml@@ -16,7 +16,7 @@ anyhow.workspace = trueasync-trait.workspace = trueaxum = { workspace = true, features = ["macros"] }aws-sdk-sqs.workspace = true-call = { path = "../call", default-features = false, features = ["ports"] }+call = { path = "../call", default-features = false, features = ["ai_tools", "outbound", "ports"] }chrono.workspace = truedateparser.workspace = truecomms = { path = "../comms", features = ["outbound"] }@@ -48,6 +48,7 @@ models_properties = { path = "../models_properties" }models_search = { path = "../models_search" }rand.workspace = truereadonly_pool = { path = "../readonly_pool" }+rootcause = { workspace = true }schemars.workspace = truescribe = { path = "../scribe", features = ["channel",diff --git a/rust/cloud-storage/ai_tools/src/build_context.rs b/rust/cloud-storage/ai_tools/src/build_context.rsindex d8ce3f7215..fbea768c81 100644--- a/rust/cloud-storage/ai_tools/src/build_context.rs+++ b/rust/cloud-storage/ai_tools/src/build_context.rs@@ -5,7 +5,8 @@//! instead of duplicating the wiring logic.use crate::tool_context::{- NoOpConnectionService, NoOpNotificationService, NoOpTaskProperties, ToolServiceContext,+ NoOpCallRtcClient, NoOpConnectionService, NoOpNotificationIngress, NoOpNotificationService,+ NoOpTaskProperties, ToolServiceContext,};use anyhow::Context;use comms::domain::service::ChannelServiceImpl;@@ -250,6 +251,24 @@ pub async fn build_tool_service_context_from_env())),);+ let call_service = call::domain::service::CallServiceImpl::new(+ call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),+ NoOpCallRtcClient,+ NoOpConnectionService,+ (*entity_access_service).clone(),+ NoOpNotificationIngress,+ None::<call::outbound::s3_recording_storage::S3RecordingStorage>,+ String::new(),+ );+ let call_query_service = call::domain::service::CallRecordQueryServiceImpl::new(+ call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),+ );+ let call_tool_context = call::inbound::toolset::CallToolContext::new(+ call_service,+ call_query_service,+ (*entity_access_service).clone(),+ );+Ok(ToolServiceContext {search_service_client: search_client,email_service_client: email_ext_client,@@ -259,6 +278,7 @@ pub async fn build_tool_service_context_from_env(document_tool_context,properties_tool_context,email_tool_context,+ call_tool_context,schedule_tool_context: crate::NoOpScheduleContext,})}diff --git a/rust/cloud-storage/ai_tools/src/lib.rs b/rust/cloud-storage/ai_tools/src/lib.rsindex 76a839fe93..098a7b1d56 100644--- a/rust/cloud-storage/ai_tools/src/lib.rs+++ b/rust/cloud-storage/ai_tools/src/lib.rs@@ -12,6 +12,7 @@ pub mod search;pub mod serde_utils;mod tool_context;pub mod web_fetch;+use call::inbound::toolset::call_toolset;use code_execution::{anthropic_bash_code_execution_tool, anthropic_text_editor_code_execution_tool,};@@ -48,7 +49,8 @@ pub fn all_tools() -> ToolSetWithPrompt {.add_tool::<read::ReadThread, Arc<ToolScribe>>().add_subtoolset::<ToolDocumentToolContext>(document_toolset()).add_subtoolset::<ToolPropertiesToolContext>(properties_toolset())- .add_subtoolset::<ToolEmailToolContext>(email_toolset());+ .add_subtoolset::<ToolEmailToolContext>(email_toolset())+ .add_subtoolset::<ToolCallToolContext>(call_toolset());let prompt = prompts::TOOLS_PROMPT;let toolset = Arc::new(toolset);ToolSetWithPrompt { toolset, prompt }diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rsindex dad133bc5f..aca754153b 100644--- a/rust/cloud-storage/ai_tools/src/tool_context.rs+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs@@ -1,4 +1,10 @@use axum::extract::FromRef;+use call::domain::models::{CallError, CallWebhookEvent, EgressS3Config};+use call::domain::ports::CallRtcClient;+use call::domain::service::{CallRecordQueryServiceImpl, CallServiceImpl};+use call::inbound::toolset::CallToolContext;+use call::outbound::pg_call_repo::PgCallRepo;+use call::outbound::s3_recording_storage::S3RecordingStorage;use connection::domain::ports::ConnectionService;use documents::{domain::ports::TaskPropertiesPort, inbound::toolset::DocumentToolContext};use email::{@@ -88,6 +94,82 @@ impl ConnectionService for NoOpConnectionService {}}+/// No-op RTC client used by the call tool context — the AI read-only tools+/// never touch RTC, so token/egress methods bail rather than silently succeed.+#[derive(Clone)]+pub struct NoOpCallRtcClient;++impl CallRtcClient for NoOpCallRtcClient {+ async fn create_room(&self, _room_name: &str) -> anyhow::Result<()> {+ Ok(())+ }++ async fn delete_room(&self, _room_name: &str) -> anyhow::Result<()> {+ Ok(())+ }++ async fn generate_token<'a>(+ &self,+ _room_name: &str,+ _participant_identity: MacroUserIdStr<'a>,+ ) -> anyhow::Result<String> {+ anyhow::bail!("call RTC client not configured")+ }++ async fn remove_participant<'a>(+ &self,+ _room_name: &str,+ _participant_identity: MacroUserIdStr<'a>,+ ) -> anyhow::Result<()> {+ Ok(())+ }++ async fn start_room_composite_egress(+ &self,+ _room_name: &str,+ _s3_config: &EgressS3Config,+ ) -> anyhow::Result<String> {+ anyhow::bail!("call RTC client not configured")+ }++ async fn stop_egress(&self, _egress_id: &str) -> anyhow::Result<()> {+ Ok(())+ }++ fn receive_webhook(+ &self,+ _body: &str,+ _auth_token: &str,+ ) -> Result<CallWebhookEvent, CallError> {+ Err(CallError::Auth)+ }++ async fn dispatch_transcription_agent(&self, _room_name: &str) -> anyhow::Result<()> {+ Ok(())+ }+}++/// No-op notification ingress used by the call tool context — reads never+/// push notifications.+#[derive(Clone)]+pub struct NoOpNotificationIngress;++impl notification::domain::service::NotificationIngress for NoOpNotificationIngress {+ async fn send_notification<+ 'a,+ T: notification::domain::models::Notification + Clone + 'static,+ U: serde::Serialize + Send + Sync + 'static,+ >(+ &'a self,+ _req: notification::domain::models::SendNotificationRequest<'a, T, U>,+ ) -> Result<+ Option<notification::domain::models::NotificationResult<'a>>,+ rootcause::Report<notification::domain::service::SendNotificationError>,+ > {+ Ok(None)+ }+}+/// Type alias for the entity access management service implementation used by AI toolspub type ToolEntityAccessManagementService =entity_access_management::domain::service::EntityAccessManagementServiceImpl<@@ -153,6 +235,26 @@ pub type ToolPropertiesToolContext = PropertiesToolContext<ToolPropertiesService/// Type alias for the email tool contextpub type ToolEmailToolContext = EmailToolContext<ToolUserEmailService>;+/// Type alias for the call service implementation used by AI tools.+/// Wired with NoOp RTC/connection/notification clients and no recording+/// storage — the AI tools are read-only, so those capabilities are never+/// exercised.+pub type ToolCallService = CallServiceImpl<+ PgCallRepo,+ NoOpCallRtcClient,+ NoOpConnectionService,+ ToolEntityAccessService,+ NoOpNotificationIngress,+ Option<S3RecordingStorage>,+>;++/// Type alias for the read-only call record query service.+pub type ToolCallRecordQueryService = CallRecordQueryServiceImpl<PgCallRepo>;++/// Type alias for the call tool context+pub type ToolCallToolContext =+ CallToolContext<ToolCallService, ToolCallRecordQueryService, ToolEntityAccessService>;+#[derive(Clone, Default)]pub struct NoOpScheduleContext;@@ -173,6 +275,7 @@ pub struct ToolServiceContext {pub document_tool_context: ToolDocumentToolContext,pub properties_tool_context: ToolPropertiesToolContext,pub email_tool_context: ToolEmailToolContext,+ pub call_tool_context: ToolCallToolContext,pub schedule_tool_context: NoOpScheduleContext,}diff --git a/rust/cloud-storage/call/Cargo.toml b/rust/cloud-storage/call/Cargo.tomlindex 0404ff6da9..4ff795cd87 100644--- a/rust/cloud-storage/call/Cargo.toml+++ b/rust/cloud-storage/call/Cargo.toml@@ -5,7 +5,8 @@ publish = falseversion = "0.1.0"[features]-default = ["inbound", "outbound", "ports"]+ai_tools = ["dep:ai", "dep:async-trait", "dep:schemars", "ports"]+default = ["ai_tools", "inbound", "outbound", "ports"]inbound = ["dep:axum","dep:model-error-response",@@ -26,7 +27,9 @@ outbound = [ports = ["dep:entity_access", "dep:tokio"][dependencies]+ai = { path = "../ai", optional = true }anyhow = { workspace = true }+async-trait = { workspace = true, optional = true }aws-sdk-s3 = { workspace = true, optional = true }axum = { workspace = true, optional = true }chrono = { workspace = true }@@ -52,6 +55,7 @@ model_user = { path = "../model_user", optional = true, features = ["axum"] }models_pagination = { path = "../models_pagination" }models_permissions = { path = "../models_permissions" }notification = { path = "../notification" }+schemars = { workspace = true, optional = true }serde = { workspace = true }serde_json = { workspace = true }sqlx = { workspace = true, optional = true }diff --git a/rust/cloud-storage/call/src/inbound/mod.rs b/rust/cloud-storage/call/src/inbound/mod.rsindex 13187bdc15..8408fe905a 100644--- a/rust/cloud-storage/call/src/inbound/mod.rs+++ b/rust/cloud-storage/call/src/inbound/mod.rs@@ -1,2 +1,7 @@/// Axum handler and router for calls.+#[cfg(feature = "inbound")]pub mod axum_router;++/// AI toolset exposing call records to agents.+#[cfg(feature = "ai_tools")]+pub mod toolset;diff --git a/rust/cloud-storage/call/src/inbound/toolset/list_call_records.rs b/rust/cloud-storage/call/src/inbound/toolset/list_call_records.rsnew file mode 100644index 0000000000..c72c1b52c7--- /dev/null+++ b/rust/cloud-storage/call/src/inbound/toolset/list_call_records.rs@@ -0,0 +1,150 @@+//! ListCallRecords tool for listing the caller's recent call records.++use std::sync::Arc;++use crate::domain::{+ models::GetCallRecordsRequest,+ ports::{CallRecordQueryService, CallService},+};+use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};+use async_trait::async_trait;+use chrono::{DateTime, Utc};+use entity_access::domain::ports::EntityAccessService;+use filter_ast::Expr;+use item_filters::ast::{LiteralTree, call::CallLiteral};+use models_pagination::{Query, SimpleSortMethod};+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use super::CallToolContext;++/// Maximum call records returned by a single [`ListCallRecords`] invocation.+const LIST_LIMIT: u32 = 50;++/// A call-record summary. Intentionally omits the transcript — use+/// [`super::read_call_record::ReadCallRecord`] to fetch it.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct CallRecordSummary {+ /// The call's unique identifier.+ pub call_id: Uuid,+ /// The channel the call belongs to.+ pub channel_id: Uuid,+ /// The channel's display name, if resolvable.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub channel_name: Option<String>,+ /// The user who created the call.+ pub created_by: String,+ /// When the call started.+ pub started_at: DateTime<Utc>,+ /// When the call ended. Absent if the call is still active.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub ended_at: Option<DateTime<Utc>>,+ /// Call duration in milliseconds. Absent if the call is still active.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub duration_ms: Option<i64>,+ /// IDs of users who participated in the call.+ pub participants: Vec<String>,+ /// True if the call is currently active.+ pub is_active: bool,+}++/// Response for [`ListCallRecords`].+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ListCallRecordsResponse {+ /// Call records ordered by start time descending.+ pub records: Vec<CallRecordSummary>,+}++/// Tool: list the caller's recent call records (transcripts excluded).+#[derive(Debug, Deserialize, JsonSchema, Clone, Default)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "ListCallRecords",+ description = "List recent call records the user can access, ordered by start time descending. Results are scoped to channels the user is a member of. Transcripts are NOT included — call ReadCallRecord with a specific callId to fetch a transcript."+)]+pub struct ListCallRecords {+ /// Only include calls in this channel.+ #[schemars(+ description = "Optional channel id. When provided, only calls from that channel are returned."+ )]+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub channel_id: Option<Uuid>,++ /// Only include calls the caller attended (or did not attend).+ #[schemars(+ description = "Optional filter on whether the caller joined the call. true = only calls the user attended; false = only calls the user did not attend; omit to include both."+ )]+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub attended: Option<bool>,+}++#[async_trait]+impl<CSvc, QSvc, ESvc> AsyncTool<CallToolContext<CSvc, QSvc, ESvc>> for ListCallRecords+where+ CSvc: CallService,+ QSvc: CallRecordQueryService,+ ESvc: EntityAccessService,+{+ type Output = ListCallRecordsResponse;++ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]+ async fn call(+ &self,+ service_context: ServiceContext<CallToolContext<CSvc, QSvc, ESvc>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ tracing::info!(params=?self, "List call records");++ let filter = build_filter(self.channel_id, self.attended);++ let req = GetCallRecordsRequest {+ user_id: request_context.user_id.clone(),+ limit: LIST_LIMIT,+ query: Query::Sort(SimpleSortMethod::CreatedAt, filter),+ };++ let records = service_context+ .query_service+ .get_user_call_records(req)+ .await+ .map_err(|e| ToolCallError {+ description: "unable to list call records".to_string(),+ internal_error: e.into(),+ })?;++ let records = records+ .into_iter()+ .map(|r| CallRecordSummary {+ call_id: r.call_id,+ channel_id: r.channel_id,+ channel_name: r.channel_name,+ created_by: r.created_by,+ started_at: r.started_at,+ ended_at: r.ended_at,+ duration_ms: r.duration_ms,+ participants: r.participants.into_iter().map(|p| p.user_id).collect(),+ is_active: r.is_active,+ })+ .collect();++ Ok(ListCallRecordsResponse { records })+ }+}++fn build_filter(channel_id: Option<Uuid>, attended: Option<bool>) -> LiteralTree<CallLiteral> {+ let mut parts = Vec::new();+ if let Some(id) = channel_id {+ parts.push(Expr::Literal(CallLiteral::ChannelId(id)));+ }+ if let Some(a) = attended {+ parts.push(Expr::Literal(CallLiteral::Attended(a)));+ }++ let mut iter = parts.into_iter();+ let first = iter.next()?;+ let combined = iter.fold(first, Expr::and);+ Some(Arc::new(combined))+}diff --git a/rust/cloud-storage/call/src/inbound/toolset/mod.rs b/rust/cloud-storage/call/src/inbound/toolset/mod.rsnew file mode 100644index 0000000000..b3deb0ae69--- /dev/null+++ b/rust/cloud-storage/call/src/inbound/toolset/mod.rs@@ -0,0 +1,73 @@+//! Toolset inbound adapter for calls.++mod list_call_records;+mod read_call_record;++#[cfg(test)]+mod test;++use crate::domain::ports::{CallRecordQueryService, CallService};+use ai::tool::AsyncToolSet;+use entity_access::domain::ports::EntityAccessService;+use std::sync::Arc;++use list_call_records::ListCallRecords;+use read_call_record::ReadCallRecord;++/// Service context for call AI tools.+pub struct CallToolContext<CSvc, QSvc, ESvc>+where+ CSvc: CallService,+ QSvc: CallRecordQueryService,+ ESvc: EntityAccessService,+{+ /// The call service — used to read a single call record with access checks.+ pub service: Arc<CSvc>,+ /// The read-only query service — used to list the caller's call records.+ pub query_service: Arc<QSvc>,+ /// The entity access service — used to generate access receipts.+ pub entity_access_service: Arc<ESvc>,+}++impl<CSvc, QSvc, ESvc> Clone for CallToolContext<CSvc, QSvc, ESvc>+where+ CSvc: CallService,+ QSvc: CallRecordQueryService,+ ESvc: EntityAccessService,+{+ fn clone(&self) -> Self {+ Self {+ service: self.service.clone(),+ query_service: self.query_service.clone(),+ entity_access_service: self.entity_access_service.clone(),+ }+ }+}++impl<CSvc, QSvc, ESvc> CallToolContext<CSvc, QSvc, ESvc>+where+ CSvc: CallService,+ QSvc: CallRecordQueryService,+ ESvc: EntityAccessService,+{+ /// Create a new call tool context.+ pub fn new(service: CSvc, query_service: QSvc, entity_access_service: ESvc) -> Self {+ Self {+ service: Arc::new(service),+ query_service: Arc::new(query_service),+ entity_access_service: Arc::new(entity_access_service),+ }+ }+}++/// Create a call toolset.+pub fn call_toolset<CSvc, QSvc, ESvc>() -> AsyncToolSet<CallToolContext<CSvc, QSvc, ESvc>>+where+ CSvc: CallService,+ QSvc: CallRecordQueryService,+ ESvc: EntityAccessService,+{+ AsyncToolSet::new()+ .add_tool::<ListCallRecords, CallToolContext<CSvc, QSvc, ESvc>>()+ .add_tool::<ReadCallRecord, CallToolContext<CSvc, QSvc, ESvc>>()+}diff --git a/rust/cloud-storage/call/src/inbound/toolset/read_call_record.rs b/rust/cloud-storage/call/src/inbound/toolset/read_call_record.rsnew file mode 100644index 0000000000..a8c5b3e953--- /dev/null+++ b/rust/cloud-storage/call/src/inbound/toolset/read_call_record.rs@@ -0,0 +1,110 @@+//! ReadCallRecord tool for fetching a single call's transcript.++use crate::domain::ports::{CallRecordQueryService, CallService};+use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};+use async_trait::async_trait;+use chrono::{DateTime, Utc};+use entity_access::domain::{+ models::{EntityType, ViewAccessLevel},+ ports::EntityAccessService,+};+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use super::CallToolContext;++/// A single transcript segment.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct TranscriptSegment {+ /// The speaker's user id.+ pub speaker_id: String,+ /// The transcribed text.+ pub content: String,+ /// When the speaker started this segment.+ pub started_at: DateTime<Utc>,+ /// When the speaker stopped (if known).+ #[serde(skip_serializing_if = "Option::is_none")]+ pub ended_at: Option<DateTime<Utc>>,+}++/// Response for [`ReadCallRecord`] — the transcript of the requested call.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ReadCallRecordResponse {+ /// The call id the transcript belongs to.+ pub call_id: Uuid,+ /// Transcript segments in chronological order.+ pub transcript: Vec<TranscriptSegment>,+}++/// Tool: fetch a single call record's transcript.+#[derive(Debug, Deserialize, JsonSchema, Clone, Default)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "ReadCallRecord",+ description = "Retrieve the transcript for a specific call record. Use ListCallRecords first to find the callId. Only the transcript is returned — other metadata (participants, duration, etc.) is already available from ListCallRecords."+)]+pub struct ReadCallRecord {+ #[schemars(description = "The id of the call whose transcript you want to retrieve.")]+ pub call_id: Uuid,+}++#[async_trait]+impl<CSvc, QSvc, ESvc> AsyncTool<CallToolContext<CSvc, QSvc, ESvc>> for ReadCallRecord+where+ CSvc: CallService,+ QSvc: CallRecordQueryService,+ ESvc: EntityAccessService,+{+ type Output = ReadCallRecordResponse;++ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, call_id=?self.call_id), err)]+ async fn call(+ &self,+ service_context: ServiceContext<CallToolContext<CSvc, QSvc, ESvc>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ tracing::info!(params=?self, "Read call record");++ let receipt = service_context+ .entity_access_service+ .generate_entity_access_receipt::<ViewAccessLevel>(+ &request_context.user_id,+ None,+ &self.call_id.to_string(),+ EntityType::Call,+ )+ .await+ .map_err(|e| ToolCallError {+ description: "unable to get the entity access receipt".to_string(),+ internal_error: e.into(),+ })?;++ let record = service_context+ .service+ .get_call_record(receipt)+ .await+ .map_err(|e| ToolCallError {+ description: "unable to get the call record".to_string(),+ internal_error: e.into(),+ })?;++ let transcript = record+ .transcript+ .into_iter()+ .map(|s| TranscriptSegment {+ speaker_id: s.speaker_id,+ content: s.content,+ started_at: s.started_at,+ ended_at: s.ended_at,+ })+ .collect();++ Ok(ReadCallRecordResponse {+ call_id: record.call_id,+ transcript,+ })+ }+}diff --git a/rust/cloud-storage/call/src/inbound/toolset/test.rs b/rust/cloud-storage/call/src/inbound/toolset/test.rsnew file mode 100644index 0000000000..ddf0f0c7e9--- /dev/null+++ b/rust/cloud-storage/call/src/inbound/toolset/test.rs@@ -0,0 +1,40 @@+use super::list_call_records::ListCallRecords;+use super::read_call_record::ReadCallRecord;+use ai::generate_tool_input_schema;+use ai::tool::types::tool_object::validate_tool_schema;++#[test]+fn test_list_call_records_schema_validation() {+ let schema = generate_tool_input_schema!(ListCallRecords);++ let result = validate_tool_schema(&schema);+ assert!(result.is_ok(), "{:?}", result);++ let (name, description) = result.unwrap();+ assert_eq!(+ name, "ListCallRecords",+ "Tool name should match the schemars title"+ );+ assert!(+ description.contains("List"),+ "Description should contain expected text"+ );+}++#[test]+fn test_read_call_record_schema_validation() {+ let schema = generate_tool_input_schema!(ReadCallRecord);++ let result = validate_tool_schema(&schema);+ assert!(result.is_ok(), "{:?}", result);++ let (name, description) = result.unwrap();+ assert_eq!(+ name, "ReadCallRecord",+ "Tool name should match the schemars title"+ );+ assert!(+ description.contains("transcript"),+ "Description should contain expected text"+ );+}diff --git a/rust/cloud-storage/call/src/lib.rs b/rust/cloud-storage/call/src/lib.rsindex c83c4cf165..287d3a2a96 100644--- a/rust/cloud-storage/call/src/lib.rs+++ b/rust/cloud-storage/call/src/lib.rs@@ -6,8 +6,8 @@/// Domain layer: models, ports, and service.pub mod domain;-/// Inbound layer: axum handler and router.-#[cfg(feature = "inbound")]+/// Inbound layer: axum handler, router, and AI toolset.+#[cfg(any(feature = "inbound", feature = "ai_tools"))]pub mod inbound;/// Outbound layer: LiveKit RTC client adapter.#[cfg(feature = "outbound")]diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rsindex 6b7532e853..ecc6271b87 100644--- a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs@@ -1,8 +1,8 @@use crate::config::Config;use crate::service::ai_stream_registry::AiStreamRegistry;use ai_tools::{- AiToolSet, ToolDocumentToolContext, ToolEmailService, ToolEmailToolContext,- ToolPropertiesToolContext, ToolServiceContext, ToolSoupService,+ AiToolSet, ToolCallToolContext, ToolDocumentToolContext, ToolEmailService,+ ToolEmailToolContext, ToolPropertiesToolContext, ToolServiceContext, ToolSoupService,};use axum::extract::FromRef;use connection_gateway::service::connection::ConnectionRepo;@@ -59,6 +59,7 @@ pub struct ApiContext {pub memory_service: Arc<DcsMemoryService>,pub properties_tool_context: ToolPropertiesToolContext,pub email_tool_context: ToolEmailToolContext,+ pub call_tool_context: ToolCallToolContext,pub tool_service_context: ToolServiceContext,pub all_tools: Arc<AiToolSet>,pub all_tools_prompt: &'static str,diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rsindex f67e27abf0..57375245f8 100644--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs@@ -284,6 +284,24 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arentity_access_service.clone(),);+ let call_service = call::domain::service::CallServiceImpl::new(+ call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),+ ai_tools::NoOpCallRtcClient,+ ai_tools::NoOpConnectionService,+ (*entity_access_service).clone(),+ ai_tools::NoOpNotificationIngress,+ None::<call::outbound::s3_recording_storage::S3RecordingStorage>,+ String::new(),+ );+ let call_query_service = call::domain::service::CallRecordQueryServiceImpl::new(+ call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),+ );+ let call_tool_context = call::inbound::toolset::CallToolContext::new(+ call_service,+ call_query_service,+ (*entity_access_service).clone(),+ );+let tool_service_context = ai_tools::ToolServiceContext {search_service_client: search_service_client.clone(),email_service_client: email_service_client_external.clone(),@@ -293,6 +311,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ardocument_tool_context: document_tool_context.clone(),properties_tool_context: properties_tool_context.clone(),email_tool_context: email_tool_context.clone(),+ call_tool_context: call_tool_context.clone(),schedule_tool_context: ai_tools::no_op_schedule_context(),};let all_tools = ai_tools::all_tools();@@ -327,6 +346,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Armemory_service,properties_tool_context,email_tool_context,+ call_tool_context,tool_service_context,all_tools: all_tools_toolset,all_tools_prompt,diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rsindex dc22c4a365..ab8141ad63 100644--- a/rust/cloud-storage/document_cognition_service/src/main.rs+++ b/rust/cloud-storage/document_cognition_service/src/main.rs@@ -1,7 +1,14 @@#![recursion_limit = "256"]use crate::api::context::ApiContext;-use ai_tools::{NoOpConnectionService, NoOpNotificationService, NoOpTaskProperties};+use ai_tools::{+ NoOpCallRtcClient, NoOpConnectionService, NoOpNotificationIngress, NoOpNotificationService,+ NoOpTaskProperties,+};use anyhow::Context;+use call::domain::service::{CallRecordQueryServiceImpl, CallServiceImpl};+use call::inbound::toolset::CallToolContext;+use call::outbound::pg_call_repo::PgCallRepo;+use call::outbound::s3_recording_storage::S3RecordingStorage;use comms::domain::service::ChannelServiceImpl;use comms::outbound::postgres::comms_repo::PgCommsRepo;use comms::outbound::postgres::user_repo::PgUserRepo;@@ -295,6 +302,24 @@ async fn main() -> anyhow::Result<()> {tracing::info!("initialized email tool context");+ let call_service = CallServiceImpl::new(+ PgCallRepo::new(db.clone()),+ NoOpCallRtcClient,+ NoOpConnectionService,+ (*entity_access_service).clone(),+ NoOpNotificationIngress,+ None::<S3RecordingStorage>,+ String::new(),+ );+ let call_query_service = CallRecordQueryServiceImpl::new(PgCallRepo::new(db.clone()));+ let call_tool_context = CallToolContext::new(+ call_service,+ call_query_service,+ (*entity_access_service).clone(),+ );++ tracing::info!("initialized call tool context");+let tool_service_context = ai_tools::ToolServiceContext {search_service_client: search_service_client.clone(),email_service_client: email_service_client_external.clone(),@@ -304,6 +329,7 @@ async fn main() -> anyhow::Result<()> {document_tool_context: document_tool_context.clone(),properties_tool_context: properties_tool_context.clone(),email_tool_context: email_tool_context.clone(),+ call_tool_context: call_tool_context.clone(),schedule_tool_context: ai_tools::NoOpScheduleContext,};let all_tools = ai_tools::all_tools();@@ -341,6 +367,7 @@ async fn main() -> anyhow::Result<()> {memory_service,properties_tool_context,email_tool_context: email_tool_context.clone(),+ call_tool_context,tool_service_context,all_tools: all_tools_toolset,all_tools_prompt,diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rsindex da0c5315cd..cb13d046b3 100644--- a/rust/cloud-storage/mcp_service/src/context.rs+++ b/rust/cloud-storage/mcp_service/src/context.rs@@ -1,8 +1,8 @@use std::sync::Arc;use ai_tools::{- NoOpConnectionService, NoOpNotificationService, NoOpScheduleContext, NoOpTaskProperties,- ToolServiceContext,+ NoOpCallRtcClient, NoOpConnectionService, NoOpNotificationIngress, NoOpNotificationService,+ NoOpScheduleContext, NoOpTaskProperties, ToolServiceContext,};use anyhow::Context;use comms::domain::service::ChannelServiceImpl;@@ -256,6 +256,24 @@ async fn build_tool_context())),);+ let call_service = call::domain::service::CallServiceImpl::new(+ call::outbound::pg_call_repo::PgCallRepo::new(db.clone()),+ NoOpCallRtcClient,+ NoOpConnectionService,+ EntityAccessServiceImpl::new(PgAccessRepository::new(db.clone())),+ NoOpNotificationIngress,+ None::<call::outbound::s3_recording_storage::S3RecordingStorage>,+ String::new(),+ );+ let call_query_service = call::domain::service::CallRecordQueryServiceImpl::new(+ call::outbound::pg_call_repo::PgCallRepo::new(db.clone()),+ );+ let call_tool_context = call::inbound::toolset::CallToolContext::new(+ call_service,+ call_query_service,+ EntityAccessServiceImpl::new(PgAccessRepository::new(db.clone())),+ );+let tool_context = ToolServiceContext {email_service_client: Arc::new(EmailServiceClientExternal::new(email_service_client.url().to_owned(),@@ -284,6 +302,7 @@ async fn build_tool_context(document_tool_context,properties_tool_context,email_tool_context,+ call_tool_context,schedule_tool_context: NoOpScheduleContext,};