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(calendar): calendar event CRUD AI tools (#5721)

gbirmand7bb01c410da
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 71b2723c0f..a1591dc8e8 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -53,6 +53,7 @@
"crates/authentication_service_client",
"crates/bot_id",
"crates/broadcast",
+ "crates/calendar_events",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -233,6 +234,7 @@
"crates/authentication_service_client",
"crates/bot_id",
"crates/broadcast",
+ "crates/calendar_events",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -723,6 +725,7 @@
"crates/authentication_service_client",
"crates/bot_id",
"crates/broadcast",
+ "crates/calendar_events",
"crates/call",
"crates/channel_bots",
"crates/channel_sender",
@@ -1508,6 +1511,7 @@
"crates/authentication_service_client",
"crates/bot_id",
"crates/broadcast",
+ "crates/calendar_events",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -3980,6 +3984,7 @@
"crates/authentication_service_client",
"crates/bot_id",
"crates/broadcast",
+ "crates/calendar_events",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -4100,6 +4105,7 @@
"crates/authentication_service_client",
"crates/bot_id",
"crates/broadcast",
+ "crates/calendar_events",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -5221,6 +5227,7 @@
"crates/authentication_service_client",
"crates/bot_id",
"crates/broadcast",
+ "crates/calendar_events",
"crates/call",
"crates/channel_sender",
"crates/channels",
diff --git a/Cargo.lock b/Cargo.lock
index f3f512e01d..e84cdc74ed 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -279,6 +279,7 @@ dependencies = [
"aws-sdk-secretsmanager",
"aws-sdk-sqs",
"axum",
+ "calendar_events",
"call",
"channels",
"chat",
@@ -2676,6 +2677,9 @@ dependencies = [
name = "calendar_events"
version = "0.1.0"
dependencies = [
+ "ai_toolset",
+ "anyhow",
+ "async-trait",
"aws-sdk-sqs",
"axum",
"chrono",
@@ -2689,6 +2693,7 @@ dependencies = [
"notification",
"reqwest 0.13.4",
"rootcause",
+ "schemars 1.2.1",
"serde",
"serde_json",
"sqlx",
diff --git a/apps/web/src/lib/core/component/AI/component/tool/CalendarTools.tsx b/apps/web/src/lib/core/component/AI/component/tool/CalendarTools.tsx
new file mode 100644
index 0000000000..22b966857c
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/CalendarTools.tsx
@@ -0,0 +1,285 @@
+import CalendarBlank from '@phosphor-icons/core/regular/calendar-blank.svg';
+import CalendarDots from '@phosphor-icons/core/regular/calendar-dots.svg';
+import CalendarPlus from '@phosphor-icons/core/regular/calendar-plus.svg';
+import CalendarX from '@phosphor-icons/core/regular/calendar-x.svg';
+import type { NamedTool } from '@service-cognition/generated/tools/tool';
+import { format, isSameDay, subDays } from 'date-fns';
+import { createSignal, For, Show } from 'solid-js';
+import { BaseTool } from './BaseTool';
+import { Tool } from './Tool';
+import { createToolRenderer } from './ToolRenderer';
+
+type CalendarEventListItem = NamedTool<
+ 'ListCalendarEvents',
+ 'response'
+>['data']['events'][number];
+
+type ToolCalendarEvent = NamedTool<'CreateCalendarEvent', 'response'>['data'];
+
+type ToolCalendar = NamedTool<
+ 'ListCalendars',
+ 'response'
+>['data']['calendars'][number];
+
+const formatEventTime = (
+ start: string,
+ end: string,
+ isAllDay: boolean
+): string => {
+ if (isAllDay) {
+ const startDate = new Date(`${start}T00:00:00`);
+ const lastDate = subDays(new Date(`${end}T00:00:00`), 1);
+ if (isSameDay(startDate, lastDate)) return format(startDate, 'EEE MMM d');
+ return `${format(startDate, 'EEE MMM d')} – ${format(lastDate, 'EEE MMM d')}`;
+ }
+ const startsAt = new Date(start);
+ const endsAt = new Date(end);
+ if (isSameDay(startsAt, endsAt)) {
+ return `${format(startsAt, 'EEE MMM d, h:mm a')} – ${format(endsAt, 'h:mm a')}`;
+ }
+ return `${format(startsAt, 'EEE MMM d, h:mm a')} – ${format(endsAt, 'EEE MMM d, h:mm a')}`;
+};
+
+const EventDetails = (props: { event: ToolCalendarEvent }) => (
+ <Tool.List>
+ <Tool.ListItem icon={<CalendarBlank class="size-4" />}>
+ <div class="flex min-w-0 flex-col gap-0.5">
+ <span class="truncate text-xs text-ink">{props.event.title}</span>
+ <span class="text-xs text-ink-extra-muted">
+ {formatEventTime(
+ props.event.start,
+ props.event.end,
+ props.event.isAllDay
+ )}
+ </span>
+ <Show when={props.event.location}>
+ <span class="truncate text-xs text-ink-extra-muted">
+ {props.event.location}
+ </span>
+ </Show>
+ <Show when={props.event.attendeeCount > 0}>
+ <span class="truncate text-xs text-ink-extra-muted">
+ {props.event.attendeeCount === 1
+ ? '1 attendee'
+ : `${props.event.attendeeCount} attendees`}
+ {': '}
+ {props.event.attendees.map((attendee) => attendee.email).join(', ')}
+ </span>
+ </Show>
+ <Show when={props.event.conferenceUrl}>
+ {(url) => (
+ <a
+ class="truncate text-xs text-accent hover:underline"
+ href={url()}
+ rel="noreferrer"
+ target="_blank"
+ >
+ {url()}
+ </a>
+ )}
+ </Show>
+ </div>
+ </Tool.ListItem>
+ </Tool.List>
+);
+
+const mutationRenderer = (
+ name: 'CreateCalendarEvent' | 'UpdateCalendarEvent',
+ icon: typeof CalendarPlus,
+ label: string
+) =>
+ createToolRenderer({
+ name,
+ render: (ctx) => {
+ const [isExpanded, setIsExpanded] = createSignal(false);
+ const event = () => ctx.response?.data as ToolCalendarEvent | undefined;
+ const title = () => {
+ const responseTitle = event()?.title;
+ if (responseTitle) return responseTitle;
+ const callTitle = (ctx.tool.data as { title?: string | null }).title;
+ return callTitle ?? undefined;
+ };
+
+ return (
+ <BaseTool
+ icon={icon}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ event() && isExpanded() ? (
+ <EventDetails event={event() as ToolCalendarEvent} />
+ ) : undefined
+ }
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3 overflow-hidden">
+ <span class="min-w-0 truncate">
+ {label}
+ <Show when={title()}>
+ {(eventTitle) => (
+ <>
+ {' '}
+ <span class="text-ink">{eventTitle()}</span>
+ </>
+ )}
+ </Show>
+ </span>
+ <Tool.ResultToggle
+ expanded={isExpanded()}
+ onToggle={() => setIsExpanded((expanded) => !expanded)}
+ showToggle={Boolean(event())}
+ status={event() ? 'Done' : undefined}
+ />
+ </div>
+ </BaseTool>
+ );
+ },
+ });
+
+export const createCalendarEventHandler = mutationRenderer(
+ 'CreateCalendarEvent',
+ CalendarPlus,
+ 'Create calendar event'
+);
+
+export const updateCalendarEventHandler = mutationRenderer(
+ 'UpdateCalendarEvent',
+ CalendarDots,
+ 'Update calendar event'
+);
+
+export const deleteCalendarEventHandler = createToolRenderer({
+ name: 'DeleteCalendarEvent',
+ render: (ctx) => (
+ <BaseTool icon={CalendarX} renderContext={ctx.renderContext} type="call">
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3 overflow-hidden">
+ <span class="min-w-0 truncate">Delete calendar event</span>
+ <Show when={ctx.response}>
+ <span class="shrink-0 text-xs text-ink-extra-muted">Deleted</span>
+ </Show>
+ </div>
+ </BaseTool>
+ ),
+});
+
+const ListEventsResponse = (props: { events: CalendarEventListItem[] }) => (
+ <Tool.List>
+ <For each={props.events}>
+ {(event) => (
+ <Tool.ListItem icon={<CalendarBlank class="size-4" />}>
+ <div class="flex min-w-0 items-center justify-between gap-2">
+ <span class="truncate text-xs text-ink">{event.title}</span>
+ <span class="shrink-0 text-xs text-ink-extra-muted">
+ {formatEventTime(event.start, event.end, event.isAllDay)}
+ </span>
+ </div>
+ </Tool.ListItem>
+ )}
+ </For>
+ </Tool.List>
+);
+
+export const listCalendarEventsHandler = createToolRenderer({
+ name: 'ListCalendarEvents',
+ render: (ctx) => {
+ const [isExpanded, setIsExpanded] = createSignal(false);
+ const events = () => ctx.response?.data.events ?? [];
+ const hasResults = () => events().length > 0;
+ const statusText = () => {
+ if (!ctx.response) return undefined;
+ const count = events().length;
+ if (count === 0) return 'No events';
+ const label = count === 1 ? '1 event' : `${count} events`;
+ return ctx.response.data.truncated ? `${label}+` : label;
+ };
+
+ return (
+ <BaseTool
+ icon={CalendarDots}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ hasResults() && isExpanded() ? (
+ <ListEventsResponse events={events()} />
+ ) : undefined
+ }
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3 overflow-hidden">
+ <span class="min-w-0 truncate">List calendar events</span>
+ <Tool.ResultToggle
+ expanded={isExpanded()}
+ onToggle={() => setIsExpanded((expanded) => !expanded)}
+ showToggle={hasResults()}
+ status={statusText()}
+ />
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
+const calendarLabel = (calendar: ToolCalendar): string => {
+ if (!calendar.isWritable) return 'Read-only';
+ if (calendar.isPrimary) return 'Primary';
+ return 'Writable';
+};
+
+const ListCalendarsResponse = (props: { calendars: ToolCalendar[] }) => (
+ <Tool.List>
+ <For each={props.calendars}>
+ {(calendar) => (
+ <Tool.ListItem icon={<CalendarBlank class="size-4" />}>
+ <div class="flex min-w-0 items-center justify-between gap-2">
+ <span class="truncate text-xs text-ink">
+ {calendar.name}
+ <span class="text-ink-extra-muted">
+ {' '}
+ · {calendar.emailAddress}
+ </span>
+ </span>
+ <span class="shrink-0 text-xs text-ink-extra-muted">
+ {calendarLabel(calendar)}
+ </span>
+ </div>
+ </Tool.ListItem>
+ )}
+ </For>
+ </Tool.List>
+);
+
+export const listCalendarsHandler = createToolRenderer({
+ name: 'ListCalendars',
+ render: (ctx) => {
+ const [isExpanded, setIsExpanded] = createSignal(false);
+ const calendars = () => ctx.response?.data.calendars ?? [];
+ const hasResults = () => calendars().length > 0;
+ const statusText = () => {
+ if (!ctx.response) return undefined;
+ const count = calendars().length;
+ if (count === 0) return 'No calendars';
+ return count === 1 ? '1 calendar' : `${count} calendars`;
+ };
+
+ return (
+ <BaseTool
+ icon={CalendarBlank}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ hasResults() && isExpanded() ? (
+ <ListCalendarsResponse calendars={calendars()} />
+ ) : undefined
+ }
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3 overflow-hidden">
+ <span class="min-w-0 truncate">List calendars</span>
+ <Tool.ResultToggle
+ expanded={isExpanded()}
+ onToggle={() => setIsExpanded((expanded) => !expanded)}
+ showToggle={hasResults()}
+ status={statusText()}
+ />
+ </div>
+ </BaseTool>
+ );
+ },
+});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
index 568772869e..c903cfd096 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
@@ -5,6 +5,13 @@ import {
} from '@service-cognition/generated/tools/tool';
import { Dynamic } from 'solid-js/web';
import { bashCodeExecutionHandler } from './BashCodeExecution';
+import {
+ createCalendarEventHandler,
+ deleteCalendarEventHandler,
+ listCalendarEventsHandler,
+ listCalendarsHandler,
+ updateCalendarEventHandler,
+} from './CalendarTools';
import { createDocumentHandler } from './CreateDocument';
import { createProjectHandler } from './CreateProject';
import { createTagHandler } from './CreateTag';
@@ -69,6 +76,11 @@ import { webFetchHandler } from './WebFetch';
import { webSearchHandler } from './WebSearch';
const toolHandlers: ToolHandlerMap<RenderContext> = {
+ CreateCalendarEvent: createCalendarEventHandler,
+ UpdateCalendarEvent: updateCalendarEventHandler,
+ DeleteCalendarEvent: deleteCalendarEventHandler,
+ ListCalendarEvents: listCalendarEventsHandler,
+ ListCalendars: listCalendarsHandler,
CreateImportEntity: createImportEntityHandler,
DeleteImportEntity: deleteImportEntityHandler,
ImportNotionPage: importNotionPageHandler,
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
index 30ea0c0107..680fc70ee8 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
@@ -646,6 +646,75 @@ export const SearchToolResponse = z.object({
),
});
+export const CreateCalendarEvent = z.object({
+ addGoogleMeet: z.boolean().optional(),
+ attendees: z
+ .array(z.object({ email: z.string(), isOptional: z.boolean().optional() }))
+ .optional(),
+ calendarId: z.union([z.string().uuid(), z.null()]).optional(),
+ description: z.union([z.string(), z.null()]).optional(),
+ location: z.union([z.string(), z.null()]).optional(),
+ recurrenceLines: z.array(z.string()).optional(),
+ time: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.object({
+ endsAt: z.string().datetime({ offset: true }),
+ kind: z.literal('timed'),
+ startsAt: z.string().datetime({ offset: true }),
+ timeZone: z.union([z.string(), z.null()]).optional(),
+ }),
+ z.object({
+ endDate: z.string().date(),
+ kind: z.literal('allDay'),
+ startDate: z.string().date(),
+ }),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ title: z.string(),
+});
+
+export const ToolCalendarEvent = z.object({
+ attendeeCount: z.number().int().gte(0),
+ attendees: z.array(
+ z.object({
+ email: z.string(),
+ isOptional: z.boolean(),
+ isOrganizer: z.boolean(),
+ responseStatus: z.string(),
+ })
+ ),
+ calendarId: z.union([z.string().uuid(), z.null()]).optional(),
+ conferenceUrl: z.union([z.string(), z.null()]).optional(),
+ description: z.union([z.string(), z.null()]).optional(),
+ end: z.string(),
+ eventId: z.string().uuid(),
+ isAllDay: z.boolean(),
+ isReadOnly: z.boolean(),
+ isRecurring: z.boolean(),
+ location: z.union([z.string(), z.null()]).optional(),
+ organizerEmail: z.union([z.string(), z.null()]).optional(),
+ recurrenceLines: z.array(z.string()),
+ start: z.string(),
+ status: z.string(),
+ timeZone: z.union([z.string(), z.null()]).optional(),
+ title: z.string(),
+});
+
export const CreateDocument = z.object({
documentName: z.string(),
fileContent: z.string(),
@@ -856,6 +925,41 @@ export const CreateTagResponse = z.object({
summary: z.string(),
});
+export const DeleteCalendarEvent = z.object({
+ eventId: z.string().uuid(),
+ recurrenceId: z.union([z.string(), z.null()]).optional(),
+ scope: z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('all'),
+ z.literal('this_event'),
+ z.literal('this_and_following'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ })
+ .optional(),
+});
+
+export const DeleteCalendarEventResponse = z.object({
+ eventId: z.string().uuid(),
+ summary: z.string(),
+});
+
export const DeleteImportEntity = z.object({ id: z.string().uuid() });
export const DeleteImportEntityResponse = z.object({
@@ -1144,6 +1248,61 @@ export const ImportNotionPageResponse = z.object({
outcome: z.string(),
});
+export const ListCalendarEvents = z.object({
+ end: z.string().datetime({ offset: true }),
+ start: z.string().datetime({ offset: true }),
+});
+
+export const ListCalendarEventsResponse = z.object({
+ events: z.array(
+ z.object({
+ attendeeCount: z.number().int().gte(0),
+ attendees: z.array(
+ z.object({
+ email: z.string(),
+ isOptional: z.boolean(),
+ isOrganizer: z.boolean(),
+ responseStatus: z.string(),
+ })
+ ),
+ calendarId: z.union([z.string().uuid(), z.null()]).optional(),
+ conferenceUrl: z.union([z.string(), z.null()]).optional(),
+ description: z.union([z.string(), z.null()]).optional(),
+ end: z.string(),
+ eventId: z.string().uuid(),
+ isAllDay: z.boolean(),
+ isReadOnly: z.boolean(),
+ isRecurring: z.boolean(),
+ location: z.union([z.string(), z.null()]).optional(),
+ myResponse: z.union([z.string(), z.null()]).optional(),
+ organizerEmail: z.union([z.string(), z.null()]).optional(),
+ recurrenceId: z.union([z.string(), z.null()]).optional(),
+ start: z.string(),
+ status: z.string(),
+ timeZone: z.union([z.string(), z.null()]).optional(),
+ title: z.string(),
+ })
+ ),
+ summary: z.string(),
+ syncStatus: z.string(),
+ truncated: z.boolean(),
+});
+
+export const ListCalendars = z.record(z.any());
+
+export const ListCalendarsToolResponse = z.object({
+ calendars: z.array(
+ z.object({
+ calendarId: z.string().uuid(),
+ emailAddress: z.string(),
+ isPrimary: z.boolean(),
+ isWritable: z.boolean(),
+ name: z.string(),
+ })
+ ),
+ summary: z.string(),
+});
+
export const ListCompanies = z.object({
include_hidden: z.union([z.boolean(), z.null()]).optional(),
limit: z.union([z.number().int().gte(0).lte(65535), z.null()]).optional(),
@@ -3408,6 +3567,80 @@ export const TextEditorCodeExecutionResponse = z.object({
tool_use_id: z.string(),
});
+export const UpdateCalendarEvent = z.object({
+ attendees: z
+ .union([
+ z.array(
+ z.object({ email: z.string(), isOptional: z.boolean().optional() })
+ ),
+ z.null(),
+ ])
+ .optional(),
+ conference: z
+ .union([
+ z.any().superRefine((x, ctx) => {
+ const schemas = [z.literal('google_meet'), z.literal('remove')];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ z.null(),
+ ])
+ .optional(),
+ description: z.union([z.string(), z.null()]).optional(),
+ eventId: z.string().uuid(),
+ location: z.union([z.string(), z.null()]).optional(),
+ recurrenceLines: z.union([z.array(z.string()), z.null()]).optional(),
+ time: z
+ .union([
+ z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.object({
+ endsAt: z.string().datetime({ offset: true }),
+ kind: z.literal('timed'),
+ startsAt: z.string().datetime({ offset: true }),
+ timeZone: z.union([z.string(), z.null()]).optional(),
+ }),
+ z.object({
+ endDate: z.string().date(),
+ kind: z.literal('allDay'),
+ startDate: z.string().date(),
+ }),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ z.null(),
+ ])
+ .optional(),
+ title: z.union([z.string(), z.null()]).optional(),
+});
+
export const UpdateThreadLabels = z.object({
add: z.boolean(),
label_id: z.string().uuid(),
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
index 6c9b1be31f..afeeafe233 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
@@ -20,6 +20,10 @@ type ToolParserMap = {
call: types.ContentSearch;
response: types.SearchToolResponse;
};
+ CreateCalendarEvent: {
+ call: types.CreateCalendarEvent;
+ response: types.ToolCalendarEvent;
+ };
CreateDocument: {
call: types.CreateDocument;
response: types.CreateDocumentResponse;
@@ -33,6 +37,10 @@ type ToolParserMap = {
response: types.CreateProjectResponse;
};
CreateTag: { call: types.CreateTag; response: types.CreateTagResponse };
+ DeleteCalendarEvent: {
+ call: types.DeleteCalendarEvent;
+ response: types.DeleteCalendarEventResponse;
+ };
DeleteImportEntity: {
call: types.DeleteImportEntity;
response: types.DeleteImportEntityResponse;
@@ -57,6 +65,14 @@ type ToolParserMap = {
call: types.ImportNotionPage;
response: types.ImportNotionPageResponse;
};
+ ListCalendarEvents: {
+ call: types.ListCalendarEvents;
+ response: types.ListCalendarEventsResponse;
+ };
+ ListCalendars: {
+ call: types.ListCalendars;
+ response: types.ListCalendarsToolResponse;
+ };
ListCompanies: {
call: types.ListCompanies;
response: types.ListCompaniesResponse;
@@ -146,6 +162,10 @@ type ToolParserMap = {
call: types.TextEditorCodeExecution;
response: types.TextEditorCodeExecutionResponse;
};
+ UpdateCalendarEvent: {
+ call: types.UpdateCalendarEvent;
+ response: types.ToolCalendarEvent;
+ };
UpdateThreadLabels: {
call: types.UpdateThreadLabels;
response: types.UpdateThreadLabelsResponse;
@@ -167,6 +187,10 @@ const toolParserMap = {
call: schemas.ContentSearch,
response: schemas.SearchToolResponse,
},
+ CreateCalendarEvent: {
+ call: schemas.CreateCalendarEvent,
+ response: schemas.ToolCalendarEvent,
+ },
CreateDocument: {
call: schemas.CreateDocument,
response: schemas.CreateDocumentResponse,
@@ -180,6 +204,10 @@ const toolParserMap = {
response: schemas.CreateProjectResponse,
},
CreateTag: { call: schemas.CreateTag, response: schemas.CreateTagResponse },
+ DeleteCalendarEvent: {
+ call: schemas.DeleteCalendarEvent,
+ response: schemas.DeleteCalendarEventResponse,
+ },
DeleteImportEntity: {
call: schemas.DeleteImportEntity,
response: schemas.DeleteImportEntityResponse,
@@ -207,6 +235,14 @@ const toolParserMap = {
call: schemas.ImportNotionPage,
response: schemas.ImportNotionPageResponse,
},
+ ListCalendarEvents: {
+ call: schemas.ListCalendarEvents,
+ response: schemas.ListCalendarEventsResponse,
+ },
+ ListCalendars: {
+ call: schemas.ListCalendars,
+ response: schemas.ListCalendarsToolResponse,
+ },
ListCompanies: {
call: schemas.ListCompanies,
response: schemas.ListCompaniesResponse,
@@ -317,6 +353,10 @@ const toolParserMap = {
call: schemas.TextEditorCodeExecution,
response: schemas.TextEditorCodeExecutionResponse,
},
+ UpdateCalendarEvent: {
+ call: schemas.UpdateCalendarEvent,
+ response: schemas.ToolCalendarEvent,
+ },
UpdateThreadLabels: {
call: schemas.UpdateThreadLabels,
response: schemas.UpdateThreadLabelsResponse,
@@ -346,6 +386,10 @@ type ToolDataMap = {
call: types.ContentSearch;
response: types.SearchToolResponse;
};
+ CreateCalendarEvent: {
+ call: types.CreateCalendarEvent;
+ response: types.ToolCalendarEvent;
+ };
CreateDocument: {
call: types.CreateDocument;
response: types.CreateDocumentResponse;
@@ -359,6 +403,10 @@ type ToolDataMap = {
response: types.CreateProjectResponse;
};
CreateTag: { call: types.CreateTag; response: types.CreateTagResponse };
+ DeleteCalendarEvent: {
+ call: types.DeleteCalendarEvent;
+ response: types.DeleteCalendarEventResponse;
+ };
DeleteImportEntity: {
call: types.DeleteImportEntity;
response: types.DeleteImportEntityResponse;
@@ -383,6 +431,14 @@ type ToolDataMap = {
call: types.ImportNotionPage;
response: types.ImportNotionPageResponse;
};
+ ListCalendarEvents: {
+ call: types.ListCalendarEvents;
+ response: types.ListCalendarEventsResponse;
+ };
+ ListCalendars: {
+ call: types.ListCalendars;
+ response: types.ListCalendarsToolResponse;
+ };
ListCompanies: {
call: types.ListCompanies;
response: types.ListCompaniesResponse;
@@ -472,6 +528,10 @@ type ToolDataMap = {
call: types.TextEditorCodeExecution;
response: types.TextEditorCodeExecutionResponse;
};
+ UpdateCalendarEvent: {
+ call: types.UpdateCalendarEvent;
+ response: types.ToolCalendarEvent;
+ };
UpdateThreadLabels: {
call: types.UpdateThreadLabels;
response: types.UpdateThreadLabelsResponse;
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index 76af119da6..cedd945d2e 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -67,6 +67,10 @@ export type ChannelMessagesWindowType =
* Which part of a thread to read.
*/
export type ChannelThreadWindowType = 'allIfSmall' | 'latest' | 'aroundReply';
+/**
+ * A requested change to an event's video conference.
+ */
+export type ConferenceChangeInput = 'google_meet' | 'remove';
/**
* The content of the document
*/
@@ -133,6 +137,38 @@ export type ContentType =
| 'chat-thread'
| 'chat-message'
| 'project';
+/**
+ * The mutually exclusive time shape supplied to calendar tools.
+ */
+export type EventTimeInput =
+ | {
+ /**
+ * Exclusive end instant, RFC 3339 UTC. Must be after the start.
+ */
+ endsAt: string;
+ kind: 'timed';
+ /**
+ * Inclusive start instant, RFC 3339 UTC (e.g. 2026-08-20T17:00:00Z).
+ */
+ startsAt: string;
+ /**
+ * IANA time zone the event was scheduled in (e.g.
+ * America/New_York). Recurring events expand in this zone.
+ */
+ timeZone?: string | null;
+ }
+ | {
+ /**
+ * Exclusive local end date (YYYY-MM-DD); the day after the last
+ * covered day, so a one-day event ends the next date.
+ */
+ endDate: string;
+ kind: 'allDay';
+ /**
+ * Inclusive local start date (YYYY-MM-DD).
+ */
+ startDate: string;
+ };
/**
* External systems items can be imported from.
*/
@@ -161,6 +197,10 @@ export type TagColor =
| 'purple'
| 'pink'
| 'gray';
+/**
+ * How much of a recurring series a deletion removes.
+ */
+export type DeletionScopeInput = 'all' | 'this_event' | 'this_and_following';
/**
* Where document content is, or is expected to be, read from.
*/
@@ -625,6 +665,19 @@ export interface AppliedTag {
label: string;
scope: TagScope;
}
+/**
+ * An attendee supplied to a calendar tool.
+ */
+export interface AttendeeInput {
+ /**
+ * The attendee's email address.
+ */
+ email: string;
+ /**
+ * Whether attendance is optional for this attendee. Defaults to required.
+ */
+ isOptional?: boolean;
+}
/**
* Execute a bash command in a sandboxed environment using Claude's built-in code execution tool.
*/
@@ -748,6 +801,108 @@ export interface BulkSetEntityPropertyOptionsResult {
*/
status: string;
}
+/**
+ * One calendar event occurrence in the requested window.
+ */
+export interface CalendarEventListItem {
+ /**
+ * Total number of attendees.
+ */
+ attendeeCount: number;
+ /**
+ * Attendees, capped at 20; `attendee_count` has the full number.
+ */
+ attendees: ToolEventAttendee[];
+ /**
+ * Calendar the event belongs to, when known.
+ */
+ calendarId?: string | null;
+ /**
+ * Conference join URL, when a conference is attached.
+ */
+ conferenceUrl?: string | null;
+ /**
+ * Event body, truncated for brevity.
+ */
+ description?: string | null;
+ /**
+ * Exclusive occurrence end: RFC 3339 UTC instant, or YYYY-MM-DD for
+ * all-day events.
+ */
+ end: string;
+ /**
+ * Macro calendar event id, used by UpdateCalendarEvent and
+ * DeleteCalendarEvent. Recurring events repeat it across occurrences.
+ */
+ eventId: string;
+ /**
+ * Whether the event covers whole days.
+ */
+ isAllDay: boolean;
+ /**
+ * Whether the user's calendar prohibits modifying this event.
+ */
+ isReadOnly: boolean;
+ /**
+ * Whether this occurrence belongs to a recurring series.
+ */
+ isRecurring: boolean;
+ /**
+ * Location label, when set.
+ */
+ location?: string | null;
+ /**
+ * The user's own RSVP on this event, when they are an attendee.
+ */
+ myResponse?: string | null;
+ /**
+ * Organizer email address, when known.
+ */
+ organizerEmail?: string | null;
+ /**
+ * Occurrence key identifying this instance within its recurring series;
+ * pass as `recurrenceId` for occurrence-scoped deletion.
+ */
+ recurrenceId?: string | null;
+ /**
+ * Occurrence start: RFC 3339 UTC instant, or YYYY-MM-DD for all-day
+ * events.
+ */
+ start: string;
+ /**
+ * Event status: confirmed or tentative.
+ */
+ status: string;
+ /**
+ * IANA time zone the event was scheduled in, when known.
+ */
+ timeZone?: string | null;
+ /**
+ * Display title.
+ */
+ title: string;
+}
+/**
+ * An attendee of a calendar event, as returned by calendar tools.
+ */
+export interface ToolEventAttendee {
+ /**
+ * Attendee email address.
+ */
+ email: string;
+ /**
+ * Whether attendance is optional.
+ */
+ isOptional: boolean;
+ /**
+ * Whether this attendee organized the event.
+ */
+ isOrganizer: boolean;
+ /**
+ * RSVP state: needs_action, accepted, declined, or tentative.
+ */
+ responseStatus: string;
+}
export interface CallRecordMetadata {
attended: boolean;
channel_name?: string | null;
@@ -1250,6 +1405,42 @@ export interface MessageWithAttachments {
content: string;
date: string;
}
+/**
+ * Create an event on the user's calendar, inviting any listed attendees through Google Calendar. The event is written to Google immediately, so attendees receive invitations the moment it is created — confirm details with the user before creating events with attendees.
+ *
+ * The event lands on the user's primary calendar unless `calendarId` (from ListCalendars) targets another one. For recurring events pass RFC 5545 lines in `recurrenceLines`, e.g. ["RRULE:FREQ=WEEKLY;BYDAY=MO"]. Returns the created event with its `eventId` for later updates or deletion. Fails if the user has no writable calendar connected.
+ */
+export interface CreateCalendarEvent {
+ /**
+ * Attach a freshly generated Google Meet video conference to the event.
+ */
+ addGoogleMeet?: boolean;
+ /**
+ * Attendees to invite by email. They are notified by Google Calendar as soon as the event is created. Omit for a solo event.
+ */
+ attendees?: AttendeeInput[];
+ /**
+ * Calendar to create the event on, from ListCalendars. Omit to use the user's primary calendar.
+ */
+ calendarId?: string | null;
+ /**
+ * Optional event body/description.
+ */
+ description?: string | null;
+ /**
+ * Optional physical or virtual location label.
+ */
+ location?: string | null;
+ /**
+ * Raw RFC 5545 recurrence lines (RRULE, RDATE, EXDATE), e.g. ["RRULE:FREQ=WEEKLY;BYDAY=MO,WE"]. Omit for a one-off event.
+ */
+ recurrenceLines?: string[];
+ time: EventTimeInput;
+ /**
+ * The event title.
+ */
+ title: string;
+}
/**
* Create a plaintext document.
*/
@@ -1478,6 +1669,35 @@ export interface CrmCompanySearchResponseItem {
*/
updatedAt: string;
}
+/**
+ * Delete an event from the user's calendar. The deletion is written to Google immediately and attendees are notified, so confirm with the user before deleting — it cannot be undone. Get the `eventId` from ListCalendarEvents.
+ *
+ * For recurring events, `scope` controls how much is removed: "all" (default) removes the whole series, "this_event" removes one occurrence, and "this_and_following" ends the series from an occurrence onward. The scoped variants require `recurrenceId` from the targeted occurrence's ListCalendarEvents entry.
+ */
+export interface DeleteCalendarEvent {
+ /**
+ * The event's id, from ListCalendarEvents or CreateCalendarEvent.
+ */
+ eventId: string;
+ /**
+ * The `recurrenceId` of the targeted occurrence, from its ListCalendarEvents entry. Required for "this_event" and "this_and_following".
+ */
+ recurrenceId?: string | null;
+ scope?: DeletionScopeInput;
+}
+/**
+ * Response from the DeleteCalendarEvent tool.
+ */
+export interface DeleteCalendarEventResponse {
+ /**
+ * The id of the deleted event.
+ */
+ eventId: string;
+ /**
+ * A human-readable confirmation of what was removed.
+ */
+ summary: string;
+}
/**
* Decline a staged import candidate on the user's behalf. The item is remembered as declined so it won't be proposed again; only the user's own staged items can be declined.
*/
@@ -2080,6 +2300,90 @@ export interface ImportNotionPageResponse {
*/
outcome: string;
}
+/**
+ * List the user's calendar events between two instants, across every calendar they have connected. Returns one entry per occurrence (a recurring event appears once per instance in the window), soonest first, with the `eventId` needed by UpdateCalendarEvent and DeleteCalendarEvent.
+ *
+ * Use this to answer questions about the user's schedule ("what's on my calendar tomorrow?"), to find an event the user wants changed or removed, and to check for conflicts before creating an event. Keep the window as narrow as the request allows — a day or a week — since wide windows truncate at 200 occurrences. The window must be at most 370 days and within one year past to two years future. If `syncStatus` is `syncing`, tell the user results may still be incomplete.
+ */
+export interface ListCalendarEvents {
+ /**
+ * Exclusive window end, RFC 3339 UTC. Must be after start.
+ */
+ end: string;
+ /**
+ * Inclusive window start, RFC 3339 UTC (e.g. 2026-08-20T00:00:00Z).
+ */
+ start: string;
+}
+/**
+ * Response from the ListCalendarEvents tool.
+ */
+export interface ListCalendarEventsResponse {
+ /**
+ * Occurrences in the window, soonest first.
+ */
+ events: CalendarEventListItem[];
+ /**
+ * A human-readable summary of the result.
+ */
+ summary: string;
+ /**
+ * `syncing` while any connected calendar is still ingesting — results
+ * may be incomplete — or `ready`.
+ */
+ syncStatus: string;
+ /**
+ * Whether the window held more occurrences than were returned; narrow
+ * the window to see the rest.
+ */
+ truncated: boolean;
+}
+/**
+ * List the calendars the user can see across their connected inboxes, with each calendar's `calendarId`, display name, owning inbox address, and whether it is primary and writable.
+ *
+ * Use this before CreateCalendarEvent when the user wants an event on a specific non-default calendar (e.g. "add it to my work calendar") so you can pass the exact `calendarId`. Most users have a single primary calendar, in which case CreateCalendarEvent targets it by default and you do not need this tool. An empty result means no calendar is connected.
+ */
+export type ListCalendars = {};
+/**
+ * Response from the ListCalendars tool.
+ */
+export interface ListCalendarsToolResponse {
+ /**
+ * The calendars the user can see, primaries and writables first.
+ */
+ calendars: ToolCalendar[];
+ /**
+ * A human-readable summary of the calendars.
+ */
+ summary: string;
+}
+/**
+ * A calendar surfaced to the AI.
+ */
+export interface ToolCalendar {
+ /**
+ * Calendar id; pass as `calendarId` to CreateCalendarEvent to target
+ * this calendar.
+ */
+ calendarId: string;
+ /**
+ * Connected inbox address the calendar belongs to.
+ */
+ emailAddress: string;
+ /**
+ * Whether this is its account's primary calendar — the default target
+ * for created events.
+ */
+ isPrimary: boolean;
+ /**
+ * Whether events can be created and modified on this calendar.
+ */
+ isWritable: boolean;
+ /**
+ * Provider display name.
+ */
+ name: string;
+}
/**
* List the CRM companies tracked by the authenticated user's team, sorted by most recent interaction. Each row includes the company id, name, domains, last interaction time, and its pipeline Stage / Owner / Revenue properties when set. Use the filters to narrow results: `search` for name/domain text, `stage` for pipeline stage, `owner_user_id` for companies owned by a user. Use GetCompany for one company's full details (contacts + all properties), and SetEntityProperty with entity_type=company to move stages or update owner/revenue/custom properties.
*/
@@ -3817,6 +4121,120 @@ export interface TextEditorCodeExecutionResponse {
content: TextEditorCodeExecutionContent;
tool_use_id: string;
}
+/**
+ * A calendar event as returned by the create and update tools.
+ */
+export interface ToolCalendarEvent {
+ /**
+ * Total number of attendees.
+ */
+ attendeeCount: number;
+ /**
+ * Attendees, capped at 20; `attendee_count` has the full number.
+ */
+ attendees: ToolEventAttendee[];
+ /**
+ * Calendar the event belongs to, when known.
+ */
+ calendarId?: string | null;
+ /**
+ * Conference join URL, when a conference is attached.
+ */
+ conferenceUrl?: string | null;
+ /**
+ * Event body, truncated for brevity.
+ */
+ description?: string | null;
+ /**
+ * Exclusive event end: RFC 3339 UTC instant, or YYYY-MM-DD for all-day
+ * events.
+ */
+ end: string;
+ /**
+ * Macro calendar event id, used by UpdateCalendarEvent and
+ * DeleteCalendarEvent.
+ */
+ eventId: string;
+ /**
+ * Whether the event covers whole days.
+ */
+ isAllDay: boolean;
+ /**
+ * Whether the user's calendar prohibits modifying this event.
+ */
+ isReadOnly: boolean;
+ /**
+ * Whether the event recurs.
+ */
+ isRecurring: boolean;
+ /**
+ * Location label, when set.
+ */
+ location?: string | null;
+ /**
+ * Organizer email address, when known.
+ */
+ organizerEmail?: string | null;
+ /**
+ * Raw RFC 5545 recurrence properties, when the event recurs.
+ */
+ recurrenceLines: string[];
+ /**
+ * Event start: RFC 3339 UTC instant, or YYYY-MM-DD for all-day events.
+ */
+ start: string;
+ /**
+ * Event status: confirmed, tentative, or cancelled.
+ */
+ status: string;
+ /**
+ * IANA time zone the event was scheduled in, when known.
+ */
+ timeZone?: string | null;
+ /**
+ * Display title.
+ */
+ title: string;
+}
+/**
+ * Update an existing calendar event. Only the supplied fields change; omitted fields keep their current values. The change is written to Google immediately and attendees are notified of it, so confirm details with the user first. Get the `eventId` from ListCalendarEvents.
+ *
+ * Passing `attendees` replaces the full attendee list — include everyone who should remain, not just additions. An empty string for `description` or `location` clears it. Updating a recurring event changes the whole series. Fails on events from calendars the user cannot edit.
+ */
+export interface UpdateCalendarEvent {
+ /**
+ * Replacement attendee list — replaces all current attendees, so include everyone who should remain. Omit to leave attendees unchanged.
+ */
+ attendees?: AttendeeInput[] | null;
+ /**
+ * Change the event's video conference: "google_meet" attaches a fresh Google Meet, "remove" detaches the current conference. Omit to leave it untouched.
+ */
+ conference?: ConferenceChangeInput | null;
+ /**
+ * Replacement event body/description. An empty string clears it; omit to keep the current one.
+ */
+ description?: string | null;
+ /**
+ * The event's id, from ListCalendarEvents or CreateCalendarEvent.
+ */
+ eventId: string;
+ /**
+ * Replacement location label. An empty string clears it; omit to keep the current one.
+ */
+ location?: string | null;
+ /**
+ * Replacement RFC 5545 recurrence lines. An empty list makes the event one-off; omit to keep the current recurrence.
+ */
+ recurrenceLines?: string[] | null;
+ /**
+ * Replacement time: a timed span with `kind` "timed" (startsAt, endsAt, optional timeZone) or whole days with `kind` "allDay" (startDate, exclusive endDate). Omit to keep the current time.
+ */
+ time?: EventTimeInput | null;
+ /**
+ * Replacement title. Omit to keep the current title.
+ */
+ title?: string | null;
+}
/**
* Add or remove a single label from every message in a Gmail thread. In Gmail, nearly all inbox operations are just label add/remove operations, so this tool is the primitive for archiving, marking read/unread, starring, trashing, marking important/spam, and applying or removing custom labels.
*
diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.toml
index 78fec9d0a9..6760b26d5c 100644
--- a/crates/ai_tools/Cargo.toml
+++ b/crates/ai_tools/Cargo.toml
@@ -18,6 +18,7 @@ anyhow.workspace = true
async-trait.workspace = true
axum = { workspace = true, features = ["macros"] }
aws-sdk-sqs.workspace = true
+calendar_events = { path = "../calendar_events", features = ["ai_tools", "mutation-client", "postgres"] }
call = { path = "../call", default-features = false, features = ["ai_tools", "outbound", "ports"] }
chat = { path = "../chat", features = ["ai_tools", "outbound"] }
channels = { path = "../channels", features = ["ai_tools", "outbound"] }
diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rs
index 3957b4aaa7..a0080ea084 100644
--- a/crates/ai_tools/src/build_context.rs
+++ b/crates/ai_tools/src/build_context.rs
@@ -186,7 +186,7 @@ pub async fn build_tool_service_context_from_env(
sync_service_auth_key.clone(),
sync_service_url,
));
- let email_ext_client = Arc::new(EmailServiceClientExternal::new(email_service_url));
+ let email_ext_client = Arc::new(EmailServiceClientExternal::new(email_service_url.clone()));
let lexical_client = LexicalClient::new(
env.document_storage_service_auth_key.to_string(),
lexical_service_url,
@@ -346,6 +346,12 @@ pub async fn build_tool_service_context_from_env(
(*entity_access_service).clone(),
);
+ let calendar_tool_context = crate::tool_context::build_calendar_tool_context(
+ pool.clone(),
+ email_service_url,
+ env.internal_api_key.to_string(),
+ );
+
let notification_reader_service = NotificationReaderService {
repository: DbNotificationRepository::new(pool.clone()),
queue: notification_queue,
@@ -397,6 +403,7 @@ pub async fn build_tool_service_context_from_env(
properties_tool_context,
email_tool_context,
call_tool_context,
+ calendar_tool_context,
notification_tool_context,
import_tool_context: ToolImportToolContext::unwired(),
chat_tool_context,
diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rs
index 53fedf6a0f..3f97af2a4b 100644
--- a/crates/ai_tools/src/lib.rs
+++ b/crates/ai_tools/src/lib.rs
@@ -18,6 +18,7 @@ mod tool_context;
pub use anthropic::toolset::AnthropicToolContext;
use anthropic::toolset::anthropic_toolset;
+use calendar_events::inbound::toolset::calendar_toolset;
use call::inbound::toolset::call_toolset;
use channels::inbound::toolset::channel_toolset;
use chat::inbound::toolset::chat_toolset;
@@ -47,22 +48,22 @@ pub use tool_context::no_op_schedule_context;
pub use 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, ToolMcpSelector, ToolNotificationQueue, ToolNotificationService,
- ToolNotificationToolContext, ToolPipedreamConnection, ToolProjectService,
- ToolProjectToolContext, ToolPropertiesService, ToolPropertiesToolContext, ToolServiceContext,
- ToolSkillService, ToolSkillToolContext, 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_project_tool_context, build_properties_service, build_properties_tool_context,
- build_skill_tool_context, build_task_properties_adapter, build_team_repository,
- build_team_tool_context,
+ RequestContext, TaskPropertiesAdapter, ToolCalendarMutationService, ToolCalendarReadService,
+ ToolCalendarToolContext, ToolCallRecordQueryService, ToolCallService, ToolCallToolContext,
+ ToolChannelEventDispatcher, ToolChannelMessagesService, ToolChannelToolContext,
+ ToolChatService, ToolChatToolContext, ToolCommsService, ToolCrmService, ToolCrmToolContext,
+ ToolDocumentService, ToolDocumentToolContext, ToolEmailService, ToolEmailToolContext,
+ ToolEntityAccessManagementService, ToolEntityAccessService, ToolEntityCreator,
+ ToolForeignEntityService, ToolFrecencyService, ToolImportService, ToolImportToolContext,
+ ToolMcpSelector, ToolNotificationQueue, ToolNotificationService, ToolNotificationToolContext,
+ ToolPipedreamConnection, ToolProjectService, ToolProjectToolContext, ToolPropertiesService,
+ ToolPropertiesToolContext, ToolServiceContext, ToolSkillService, ToolSkillToolContext,
+ ToolSoupService, ToolSystemPropertiesService, ToolTeamService, ToolTeamToolContext,
+ ToolUserEmailService, build_calendar_tool_context, 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_project_tool_context, build_properties_service,
+ build_properties_tool_context, build_skill_tool_context, build_task_properties_adapter,
+ build_team_repository, build_team_tool_context,
};
pub type AiToolSet = AsyncToolCollection<ToolServiceContext>;
@@ -104,6 +105,7 @@ pub fn all_tools() -> ToolSetWithPrompt {
let toolset = subagent_toolset()
.add_subtoolset::<ToolNotificationToolContext>(notification_toolset())
.add_subtoolset::<ToolEmailToolContext>(email_toolset())
+ .add_subtoolset::<ToolCalendarToolContext>(calendar_toolset())
.add_subtoolset::<ToolImportToolContext>(import_toolset())
.add_tool::<Subagent, ToolServiceContext>()
.add_tool::<SearchTools, ToolServiceContext>()
@@ -132,6 +134,7 @@ pub fn mcp_tools() -> ToolSetWithPrompt {
let toolset = subagent_toolset()
.add_subtoolset::<ToolNotificationToolContext>(notification_toolset())
.add_subtoolset::<ToolEmailToolContext>(email_mcp_toolset())
+ .add_subtoolset::<ToolCalendarToolContext>(calendar_toolset())
.add_subtoolset::<ToolImportToolContext>(import_toolset())
.add_tool::<Subagent, ToolServiceContext>();
let toolset = Arc::new(toolset);
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index 88755b1b10..1569e8e21d 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -1,5 +1,6 @@
use anthropic::toolset::AnthropicToolContext;
use axum::extract::FromRef;
+use calendar_events::inbound::toolset::CalendarToolContext;
use call::domain::models::{CallError, CallWebhookEvent, EgressS3Config};
use call::domain::ports::CallRtcClient;
use call::domain::service::{CallRecordQueryServiceImpl, CallServiceImpl};
@@ -214,6 +215,44 @@ pub fn build_channel_tool_context_with_dispatcher(
)
}
+/// Type alias for the calendar occurrence read service used by AI tools.
+pub type ToolCalendarReadService = calendar_events::domain::service::CalendarService<
+ calendar_events::outbound::pg::PgCalendarRepository,
+>;
+
+/// Type alias for the calendar mutation client used by AI tools. Mutations
+/// call the email service — the calendar write authority holding the Google
+/// client, token minting, and request gate — with internal auth on behalf
+/// of the requesting user, so tool-driven edits behave identically to
+/// UI-driven ones.
+pub type ToolCalendarMutationService =
+ calendar_events::outbound::email_service_mutations::EmailServiceCalendarMutations;
+
+/// Type alias for the calendar AI tool context.
+pub type ToolCalendarToolContext =
+ CalendarToolContext<ToolCalendarMutationService, ToolCalendarReadService>;
+
+/// Build the calendar AI tool context: reads query the local occurrence
+/// projections from `pool`; mutations call the email service at
+/// `email_service_url` with the shared internal API key.
+pub fn build_calendar_tool_context(
+ pool: sqlx::PgPool,
+ email_service_url: String,
+ internal_api_key: String,
+) -> ToolCalendarToolContext {
+ CalendarToolContext::new(
+ Arc::new(
+ calendar_events::outbound::email_service_mutations::EmailServiceCalendarMutations::new(
+ email_service_url,
+ internal_api_key,
+ ),
+ ),
+ Arc::new(calendar_events::domain::service::CalendarService::new(
+ calendar_events::outbound::pg::PgCalendarRepository::new(pool),
+ )),
+ )
+}
+
/// Type alias for the CRM AI tool context.
pub type ToolCrmToolContext =
CrmToolContext<ToolCrmService, ToolEntityAccessService, ToolPropertiesService>;
@@ -1134,6 +1173,7 @@ pub struct ToolServiceContext {
pub properties_tool_context: ToolPropertiesToolContext,
pub email_tool_context: ToolEmailToolContext,
pub call_tool_context: ToolCallToolContext,
+ pub calendar_tool_context: ToolCalendarToolContext,
pub notification_tool_context: ToolNotificationToolContext,
/// Import staging/tracking tools. `unwired` in hosts that can't build
/// the import service — calls there fail with a clear error.
diff --git a/crates/calendar_events/Cargo.toml b/crates/calendar_events/Cargo.toml
index 770625c799..d6102637f6 100644
--- a/crates/calendar_events/Cargo.toml
+++ b/crates/calendar_events/Cargo.toml
@@ -6,12 +6,17 @@ version = "0.1.0"
[features]
default = []
+# The AI toolset adapter exposing calendar CRUD to agents.
+ai_tools = ["dep:ai_toolset", "dep:anyhow", "dep:async-trait", "dep:schemars"]
# The reminder dispatch queue worker. Transport-agnostic: it drives the
# domain through the dispatch ports.
dispatch = ["dep:tokio", "dep:tokio-util"]
# The worker plus the SQS adapter that backs it.
dispatch-sqs = ["dep:aws-sdk-sqs", "dispatch"]
google = ["dep:reqwest", "dep:urlencoding"]
+# The email-service HTTP adapter implementing the mutation port, for hosts
+# that are not the calendar write authority.
+mutation-client = ["dep:reqwest"]
inbound = [
"dep:axum",
"dep:macro_authorization",
@@ -24,6 +29,9 @@ postgres = ["dep:sqlx", "dep:tokio"]
schema = ["dep:utoipa"]
[dependencies]
+ai_toolset = { path = "../ai_toolset", optional = true }
+anyhow = { workspace = true, optional = true }
+async-trait = { workspace = true, optional = true }
aws-sdk-sqs = { workspace = true, optional = true }
axum = { workspace = true, optional = true }
chrono = { workspace = true }
@@ -38,6 +46,7 @@ models_pagination = { path = "../models_pagination", optional = true }
notification = { path = "../notification", optional = true }
reqwest = { workspace = true, optional = true }
rootcause = { workspace = true }
+schemars = { workspace = true, optional = true }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true, optional = true }
@@ -52,4 +61,5 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
macro_db_migrator = { path = "../macro_db_migrator" }
+macro_user_id = { path = "../macro_user_id" }
tokio = { workspace = true }
diff --git a/crates/calendar_events/src/domain/models.rs b/crates/calendar_events/src/domain/models.rs
index 49f1dd2115..434387125c 100644
--- a/crates/calendar_events/src/domain/models.rs
+++ b/crates/calendar_events/src/domain/models.rs
@@ -869,7 +869,7 @@ impl CalendarEventMutationTarget {
}
/// A calendar visible to a requester, listed for pickers and filters.
-#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct VisibleCalendar {
diff --git a/crates/calendar_events/src/inbound/mod.rs b/crates/calendar_events/src/inbound/mod.rs
index ae7ed0ff88..749ecb0480 100644
--- a/crates/calendar_events/src/inbound/mod.rs
+++ b/crates/calendar_events/src/inbound/mod.rs
@@ -11,3 +11,7 @@ pub mod dispatch_worker;
/// Axum routes for authenticated calendar event mutations.
#[cfg(feature = "inbound")]
pub mod mutation_router;
+
+/// AI toolset adapter exposing calendar CRUD to agents.
+#[cfg(feature = "ai_tools")]
+pub mod toolset;
diff --git a/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs b/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs
new file mode 100644
index 0000000000..bb7aded03c
--- /dev/null
+++ b/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs
@@ -0,0 +1,135 @@
+//! CreateCalendarEvent tool for adding events to the user's calendar.
+
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,
+};
+use async_trait::async_trait;
+use schemars::JsonSchema;
+use serde::Deserialize;
+
+use super::{
+ AttendeeInput, CalendarToolContext, EventTimeInput, ToolCalendarEvent, mutation_tool_error,
+};
+use crate::domain::{
+ models::{CalendarEventDraft, ConferenceChange},
+ ports::{CalendarMutationService, CalendarOccurrenceService},
+};
+
+/// Create a calendar event.
+#[derive(Debug, Deserialize, JsonSchema, Clone)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "CreateCalendarEvent",
+ description = "\
+Create an event on the user's calendar, inviting any listed attendees through Google \
+Calendar. The event is written to Google immediately, so attendees receive invitations the \
+moment it is created — confirm details with the user before creating events with attendees.\n\
+\n\
+The event lands on the user's primary calendar unless `calendarId` (from ListCalendars) \
+targets another one. For recurring events pass RFC 5545 lines in `recurrenceLines`, e.g. \
+[\"RRULE:FREQ=WEEKLY;BYDAY=MO\"]. Returns the created event with its `eventId` for later \
+updates or deletion. Fails if the user has no writable calendar connected."
+)]
+pub struct CreateCalendarEvent {
+ /// Display title.
+ #[schemars(description = "The event title.")]
+ pub title: String,
+
+ /// Timed or all-day span.
+ #[schemars(
+ description = "When the event happens: a timed span with `kind` \"timed\" (startsAt, \
+ endsAt, optional timeZone) or whole days with `kind` \"allDay\" \
+ (startDate, exclusive endDate)."
+ )]
+ pub time: EventTimeInput,
+
+ /// Optional event body.
+ #[schemars(description = "Optional event body/description.")]
+ #[serde(default)]
+ pub description: Option<String>,
+
+ /// Optional location label.
+ #[schemars(description = "Optional physical or virtual location label.")]
+ #[serde(default)]
+ pub location: Option<String>,
+
+ /// Attendees to invite.
+ #[schemars(
+ description = "Attendees to invite by email. They are notified by Google Calendar as \
+ soon as the event is created. Omit for a solo event."
+ )]
+ #[serde(default)]
+ pub attendees: Vec<AttendeeInput>,
+
+ /// Recurrence properties.
+ #[schemars(
+ description = "Raw RFC 5545 recurrence lines (RRULE, RDATE, EXDATE), e.g. \
+ [\"RRULE:FREQ=WEEKLY;BYDAY=MO,WE\"]. Omit for a one-off event."
+ )]
+ #[serde(default)]
+ pub recurrence_lines: Vec<String>,
+
+ /// Calendar to create the event on.
+ #[schemars(
+ description = "Calendar to create the event on, from ListCalendars. Omit to use the \
+ user's primary calendar."
+ )]
+ #[serde(default)]
+ pub calendar_id: Option<uuid::Uuid>,
+
+ /// Whether to attach a Google Meet conference.
+ #[schemars(
+ description = "Attach a freshly generated Google Meet video conference to the event."
+ )]
+ #[serde(default)]
+ pub add_google_meet: bool,
+}
+
+impl ToolAnnotated for CreateCalendarEvent {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::additive("Create calendar event");
+}
+
+#[async_trait]
+impl<M, O> AsyncTool<CalendarToolContext<M, O>> for CreateCalendarEvent
+where
+ M: CalendarMutationService,
+ O: CalendarOccurrenceService,
+{
+ type Output = ToolCalendarEvent;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<CalendarToolContext<M, O>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ tracing::info!(
+ calendar_id=?self.calendar_id,
+ attendee_count = self.attendees.len(),
+ add_google_meet = self.add_google_meet,
+ "Create calendar event"
+ );
+
+ let requester_id = request_context.user_id.to_string();
+ let draft = CalendarEventDraft {
+ title: self.title.clone(),
+ description: self.description.clone(),
+ location: self.location.clone(),
+ time: self.time.clone().into(),
+ attendees: self.attendees.iter().cloned().map(Into::into).collect(),
+ recurrence_lines: self.recurrence_lines.clone(),
+ visibility: None,
+ transparency: None,
+ reminders: None,
+ conference: self.add_google_meet.then_some(ConferenceChange::GoogleMeet),
+ };
+
+ let event = service_context
+ .mutations
+ .create_event(&requester_id, None, self.calendar_id, draft)
+ .await
+ .map_err(|error| mutation_tool_error("create the calendar event", error))?;
+
+ Ok(ToolCalendarEvent::from_event(&event))
+ }
+}
diff --git a/crates/calendar_events/src/inbound/toolset/delete_calendar_event.rs b/crates/calendar_events/src/inbound/toolset/delete_calendar_event.rs
new file mode 100644
index 0000000000..70f9c31152
--- /dev/null
+++ b/crates/calendar_events/src/inbound/toolset/delete_calendar_event.rs
@@ -0,0 +1,135 @@
+//! DeleteCalendarEvent tool for removing calendar events.
+
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,
+ ToolResult,
+};
+use async_trait::async_trait;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+use super::{CalendarToolContext, mutation_tool_error};
+use crate::domain::ports::{
+ CalendarDeletionScope, CalendarMutationService, CalendarOccurrenceService,
+};
+
+/// How much of a recurring series a deletion removes.
+#[derive(Debug, Deserialize, JsonSchema, Clone, Copy, Default, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum DeletionScopeInput {
+ /// The entire event or series.
+ #[default]
+ All,
+ /// One occurrence of a recurring series.
+ ThisEvent,
+ /// One occurrence and everything after it.
+ ThisAndFollowing,
+}
+
+/// Response from the DeleteCalendarEvent tool.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct DeleteCalendarEventResponse {
+ /// The id of the deleted event.
+ pub event_id: uuid::Uuid,
+ /// A human-readable confirmation of what was removed.
+ pub summary: String,
+}
+
+/// Delete a calendar event.
+#[derive(Debug, Deserialize, JsonSchema, Clone)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "DeleteCalendarEvent",
+ description = "\
+Delete an event from the user's calendar. The deletion is written to Google immediately and \
+attendees are notified, so confirm with the user before deleting — it cannot be undone. Get \
+the `eventId` from ListCalendarEvents.\n\
+\n\
+For recurring events, `scope` controls how much is removed: \"all\" (default) removes the \
+whole series, \"this_event\" removes one occurrence, and \"this_and_following\" ends the \
+series from an occurrence onward. The scoped variants require `recurrenceId` from the \
+targeted occurrence's ListCalendarEvents entry."
+)]
+pub struct DeleteCalendarEvent {
+ /// Event to delete.
+ #[schemars(description = "The event's id, from ListCalendarEvents or CreateCalendarEvent.")]
+ pub event_id: uuid::Uuid,
+
+ /// Deletion scope.
+ #[schemars(
+ description = "How much of a recurring series to remove: \"all\" (default), \
+ \"this_event\", or \"this_and_following\". Non-recurring events use \
+ \"all\"."
+ )]
+ #[serde(default)]
+ pub scope: DeletionScopeInput,
+
+ /// Occurrence key for scoped deletions.
+ #[schemars(
+ description = "The `recurrenceId` of the targeted occurrence, from its \
+ ListCalendarEvents entry. Required for \"this_event\" and \
+ \"this_and_following\"."
+ )]
+ #[serde(default)]
+ pub recurrence_id: Option<String>,
+}
+
+impl ToolAnnotated for DeleteCalendarEvent {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Delete calendar event");
+}
+
+#[async_trait]
+impl<M, O> AsyncTool<CalendarToolContext<M, O>> for DeleteCalendarEvent
+where
+ M: CalendarMutationService,
+ O: CalendarOccurrenceService,
+{
+ type Output = DeleteCalendarEventResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<CalendarToolContext<M, O>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ tracing::info!(params=?self, "Delete calendar event");
+
+ let requester_id = request_context.user_id.to_string();
+ let scoped_occurrence = |kind: &'static str| {
+ self.recurrence_id.clone().ok_or_else(|| ToolCallError {
+ description: format!(
+ "A {kind} deletion requires `recurrenceId` — use the occurrence's \
+ `recurrenceId` from ListCalendarEvents."
+ ),
+ internal_error: anyhow::anyhow!("scoped deletion without recurrenceId"),
+ })
+ };
+ let (scope, removed) = match self.scope {
+ DeletionScopeInput::All => (CalendarDeletionScope::All, "the event"),
+ DeletionScopeInput::ThisEvent => (
+ CalendarDeletionScope::ThisEvent {
+ recurrence_id: scoped_occurrence("this_event")?,
+ },
+ "one occurrence of the event",
+ ),
+ DeletionScopeInput::ThisAndFollowing => (
+ CalendarDeletionScope::ThisAndFollowing {
+ recurrence_id: scoped_occurrence("this_and_following")?,
+ },
+ "the occurrence and all that follow it",
+ ),
+ };
+
+ service_context
+ .mutations
+ .delete_event(&requester_id, self.event_id, scope)
+ .await
+ .map_err(|error| mutation_tool_error("delete the calendar event", error))?;
+
+ Ok(DeleteCalendarEventResponse {
+ event_id: self.event_id,
+ summary: format!("Deleted {removed}."),
+ })
+ }
+}
diff --git a/crates/calendar_events/src/inbound/toolset/list_calendar_events.rs b/crates/calendar_events/src/inbound/toolset/list_calendar_events.rs
new file mode 100644
index 0000000000..274229580b
--- /dev/null
+++ b/crates/calendar_events/src/inbound/toolset/list_calendar_events.rs
@@ -0,0 +1,292 @@
+//! ListCalendarEvents tool for reading a bounded window of calendar events.
+
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,
+ ToolResult,
+};
+use async_trait::async_trait;
+use chrono::{DateTime, Utc};
+use rootcause::compat::boxed_error::IntoBoxedError;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+use super::{CalendarToolContext, ToolEventAttendee, description_preview, time_fields};
+use crate::domain::{
+ models::{CalendarOccurrenceCursor, CalendarSyncStatus, OccurrenceRange},
+ ports::{CalendarMutationService, CalendarOccurrenceService},
+ service::CalendarValidationError,
+};
+
+/// The most occurrences one call returns; wider windows report truncation.
+pub(super) const OCCURRENCES_MAX: u16 = 200;
+
+/// Bound on cursor pages fetched while filling the cap with non-cancelled
+/// occurrences; stopping early reports the window as truncated.
+const PAGES_MAX: usize = 10;
+
+/// One calendar event occurrence in the requested window.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CalendarEventListItem {
+ /// Macro calendar event id, used by UpdateCalendarEvent and
+ /// DeleteCalendarEvent. Recurring events repeat it across occurrences.
+ pub event_id: uuid::Uuid,
+ /// Display title.
+ pub title: String,
+ /// Occurrence start: RFC 3339 UTC instant, or YYYY-MM-DD for all-day
+ /// events.
+ pub start: String,
+ /// Exclusive occurrence end: RFC 3339 UTC instant, or YYYY-MM-DD for
+ /// all-day events.
+ pub end: String,
+ /// Whether the event covers whole days.
+ pub is_all_day: bool,
+ /// IANA time zone the event was scheduled in, when known.
+ pub time_zone: Option<String>,
+ /// Location label, when set.
+ pub location: Option<String>,
+ /// Event body, truncated for brevity.
+ pub description: Option<String>,
+ /// Event status: confirmed or tentative.
+ pub status: String,
+ /// Whether this occurrence belongs to a recurring series.
+ pub is_recurring: bool,
+ /// Occurrence key identifying this instance within its recurring series;
+ /// pass as `recurrenceId` for occurrence-scoped deletion.
+ pub recurrence_id: Option<String>,
+ /// Attendees, capped at 20; `attendee_count` has the full number.
+ pub attendees: Vec<ToolEventAttendee>,
+ /// Total number of attendees.
+ pub attendee_count: usize,
+ /// The user's own RSVP on this event, when they are an attendee.
+ pub my_response: Option<String>,
+ /// Organizer email address, when known.
+ pub organizer_email: Option<String>,
+ /// Conference join URL, when a conference is attached.
+ pub conference_url: Option<String>,
+ /// Whether the user's calendar prohibits modifying this event.
+ pub is_read_only: bool,
+ /// Calendar the event belongs to, when known.
+ pub calendar_id: Option<uuid::Uuid>,
+}
+
+/// Response from the ListCalendarEvents tool.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ListCalendarEventsResponse {
+ /// Occurrences in the window, soonest first.
+ pub events: Vec<CalendarEventListItem>,
+ /// Whether the window held more occurrences than were returned; narrow
+ /// the window to see the rest.
+ pub truncated: bool,
+ /// `syncing` while any connected calendar is still ingesting — results
+ /// may be incomplete — or `ready`.
+ pub sync_status: String,
+ /// A human-readable summary of the result.
+ pub summary: String,
+}
+
+/// List calendar events in a time window.
+#[derive(Debug, Deserialize, JsonSchema, Clone)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "ListCalendarEvents",
+ description = "\
+List the user's calendar events between two instants, across every calendar they have \
+connected. Returns one entry per occurrence (a recurring event appears once per instance in \
+the window), soonest first, with the `eventId` needed by UpdateCalendarEvent and \
+DeleteCalendarEvent.\n\
+\n\
+Use this to answer questions about the user's schedule (\"what's on my calendar \
+tomorrow?\"), to find an event the user wants changed or removed, and to check for conflicts \
+before creating an event. Keep the window as narrow as the request allows — a day or a week \
+— since wide windows truncate at 200 occurrences. The window must be at most 370 days and \
+within one year past to two years future. If `syncStatus` is `syncing`, tell the user \
+results may still be incomplete."
+)]
+pub struct ListCalendarEvents {
+ /// Inclusive window start.
+ #[schemars(description = "Inclusive window start, RFC 3339 UTC (e.g. 2026-08-20T00:00:00Z).")]
+ pub start: DateTime<Utc>,
+ /// Exclusive window end.
+ #[schemars(description = "Exclusive window end, RFC 3339 UTC. Must be after start.")]
+ pub end: DateTime<Utc>,
+}
+
+impl ToolAnnotated for ListCalendarEvents {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("List calendar events");
+}
+
+#[async_trait]
+impl<M, O> AsyncTool<CalendarToolContext<M, O>> for ListCalendarEvents
+where
+ M: CalendarMutationService,
+ O: CalendarOccurrenceService,
+{
+ type Output = ListCalendarEventsResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<CalendarToolContext<M, O>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ tracing::info!(params=?self, "List calendar events");
+
+ let requester_id = request_context.user_id.to_string();
+ let range = OccurrenceRange {
+ starts_at: self.start,
+ ends_at: self.end,
+ start_date: self.start.date_naive(),
+ end_date: end_date_bound(self.end),
+ };
+
+ // Cancelled occurrences never reach the response, so they must not
+ // count toward the cap or its truncation flag: keep paging until the
+ // cap is exceeded by active occurrences alone or the window is
+ // exhausted, up to a bounded number of pages.
+ let mut occurrences = Vec::new();
+ let mut cursor = None;
+ let mut exhausted = false;
+ for _ in 0..PAGES_MAX {
+ let rows = service_context
+ .occurrences
+ .list_occurrences(
+ &requester_id,
+ range.clone(),
+ cursor.take(),
+ OCCURRENCES_MAX + 1,
+ )
+ .await
+ .map_err(list_error)?;
+ let full_page = rows.len() > usize::from(OCCURRENCES_MAX);
+ cursor = rows
+ .last()
+ .map(|(_, occurrence)| CalendarOccurrenceCursor::from_occurrence(occurrence));
+ occurrences.extend(
+ rows.into_iter()
+ .filter(|(_, occurrence)| !occurrence.is_cancelled),
+ );
+ if !full_page {
+ exhausted = true;
+ break;
+ }
+ if occurrences.len() > usize::from(OCCURRENCES_MAX) {
+ break;
+ }
+ }
+ let truncated = occurrences.len() > usize::from(OCCURRENCES_MAX) || !exhausted;
+ occurrences.truncate(usize::from(OCCURRENCES_MAX));
+
+ let sync_status = service_context
+ .occurrences
+ .sync_status(&requester_id)
+ .await
+ .map_err(|error| ToolCallError {
+ description: "Failed to query calendar sync status. Try again shortly.".to_string(),
+ internal_error: anyhow::Error::from_boxed(error.into_boxed_error()),
+ })?;
+
+ let events: Vec<CalendarEventListItem> = occurrences
+ .into_iter()
+ .map(|(event, occurrence)| {
+ let (start, end, is_all_day, time_zone) = time_fields(&occurrence.time);
+ let is_recurring = !event.recurrence_lines.is_empty();
+ CalendarEventListItem {
+ event_id: event.id,
+ title: event.title.clone(),
+ start,
+ end,
+ is_all_day,
+ time_zone,
+ location: event.location.clone(),
+ description: description_preview(event.description.as_deref()),
+ status: event.status.as_str().to_string(),
+ is_recurring,
+ recurrence_id: is_recurring.then(|| occurrence.occurrence_key.clone()),
+ attendees: event
+ .attendees
+ .iter()
+ .take(super::ATTENDEES_SHOWN_MAX)
+ .map(|attendee| ToolEventAttendee {
+ email: attendee.email.clone(),
+ response_status: attendee.response_status.as_str().to_string(),
+ is_organizer: attendee.is_organizer,
+ is_optional: attendee.is_optional,
+ })
+ .collect(),
+ attendee_count: event.attendees.len(),
+ my_response: event
+ .attendees
+ .iter()
+ .find(|attendee| attendee.is_self)
+ .map(|attendee| attendee.response_status.as_str().to_string()),
+ organizer_email: event.organizer_email.clone(),
+ conference_url: event.conference_url.clone(),
+ is_read_only: event.is_read_only,
+ calendar_id: event.calendar_id,
+ }
+ })
+ .collect();
+
+ let sync_status = match sync_status {
+ CalendarSyncStatus::Syncing => "syncing",
+ CalendarSyncStatus::Ready => "ready",
+ }
+ .to_string();
+ let summary = build_summary(events.len(), truncated, &sync_status);
+
+ Ok(ListCalendarEventsResponse {
+ events,
+ truncated,
+ sync_status,
+ summary,
+ })
+ }
+}
+
+/// Map an occurrence-query failure to an agent-readable tool error.
+fn list_error(error: rootcause::Report) -> ToolCallError {
+ let description = if error
+ .as_ref()
+ .downcast_current_context::<CalendarValidationError>()
+ .is_some()
+ {
+ "The window is invalid: it must be positive, at most 370 days, and within one year past \
+ to two years future."
+ .to_string()
+ } else {
+ "Failed to query calendar events. Try again shortly.".to_string()
+ };
+ ToolCallError {
+ description,
+ internal_error: anyhow::Error::from_boxed(error.into_boxed_error()),
+ }
+}
+
+/// Exclusive local date bound covering the instant window, mirroring the
+/// occurrence HTTP route's default.
+fn end_date_bound(end: DateTime<Utc>) -> chrono::NaiveDate {
+ if end.time() == chrono::NaiveTime::MIN {
+ end.date_naive()
+ } else {
+ end.date_naive()
+ .succ_opt()
+ .unwrap_or_else(|| end.date_naive())
+ }
+}
+
+fn build_summary(count: usize, truncated: bool, sync_status: &str) -> String {
+ let mut summary = match count {
+ 0 => "No calendar events in this window.".to_string(),
+ 1 => "Found 1 calendar event.".to_string(),
+ count => format!("Found {count} calendar events."),
+ };
+ if truncated {
+ summary.push_str(" More exist — narrow the window to see the rest.");
+ }
+ if sync_status == "syncing" {
+ summary.push_str(" Calendars are still syncing; results may be incomplete.");
+ }
+ summary
+}
diff --git a/crates/calendar_events/src/inbound/toolset/list_calendars.rs b/crates/calendar_events/src/inbound/toolset/list_calendars.rs
new file mode 100644
index 0000000000..528b2c8dec
--- /dev/null
+++ b/crates/calendar_events/src/inbound/toolset/list_calendars.rs
@@ -0,0 +1,102 @@
+//! ListCalendars tool for enumerating the calendars a user can see.
+
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,
+};
+use async_trait::async_trait;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+use super::{CalendarToolContext, mutation_tool_error};
+use crate::domain::ports::{CalendarMutationService, CalendarOccurrenceService};
+
+/// A calendar surfaced to the AI.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ToolCalendar {
+ /// Calendar id; pass as `calendarId` to CreateCalendarEvent to target
+ /// this calendar.
+ pub calendar_id: uuid::Uuid,
+ /// Provider display name.
+ pub name: String,
+ /// Connected inbox address the calendar belongs to.
+ pub email_address: String,
+ /// Whether this is its account's primary calendar — the default target
+ /// for created events.
+ pub is_primary: bool,
+ /// Whether events can be created and modified on this calendar.
+ pub is_writable: bool,
+}
+
+/// Response from the ListCalendars tool.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ListCalendarsToolResponse {
+ /// The calendars the user can see, primaries and writables first.
+ pub calendars: Vec<ToolCalendar>,
+ /// A human-readable summary of the calendars.
+ pub summary: String,
+}
+
+/// List the calendars the user can access.
+#[derive(Debug, Deserialize, JsonSchema, Clone, Default)]
+#[schemars(
+ title = "ListCalendars",
+ description = "\
+List the calendars the user can see across their connected inboxes, with each calendar's \
+`calendarId`, display name, owning inbox address, and whether it is primary and writable.\n\
+\n\
+Use this before CreateCalendarEvent when the user wants an event on a specific non-default \
+calendar (e.g. \"add it to my work calendar\") so you can pass the exact `calendarId`. Most \
+users have a single primary calendar, in which case CreateCalendarEvent targets it by default \
+and you do not need this tool. An empty result means no calendar is connected."
+)]
+pub struct ListCalendars {}
+
+impl ToolAnnotated for ListCalendars {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("List calendars");
+}
+
+#[async_trait]
+impl<M, O> AsyncTool<CalendarToolContext<M, O>> for ListCalendars
+where
+ M: CalendarMutationService,
+ O: CalendarOccurrenceService,
+{
+ type Output = ListCalendarsToolResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<CalendarToolContext<M, O>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ tracing::info!("List calendars");
+
+ let requester_id = request_context.user_id.to_string();
+ let calendars = service_context
+ .mutations
+ .list_visible_calendars(&requester_id)
+ .await
+ .map_err(|error| mutation_tool_error("list calendars", error))?;
+
+ let calendars: Vec<ToolCalendar> = calendars
+ .into_iter()
+ .map(|calendar| ToolCalendar {
+ calendar_id: calendar.id,
+ name: calendar.name,
+ email_address: calendar.email_address,
+ is_primary: calendar.is_primary,
+ is_writable: calendar.is_writable,
+ })
+ .collect();
+
+ let summary = match calendars.len() {
+ 0 => "No calendars are connected.".to_string(),
+ 1 => "Found 1 calendar.".to_string(),
+ count => format!("Found {count} calendars."),
+ };
+
+ Ok(ListCalendarsToolResponse { calendars, summary })
+ }
+}
diff --git a/crates/calendar_events/src/inbound/toolset/mod.rs b/crates/calendar_events/src/inbound/toolset/mod.rs
new file mode 100644
index 0000000000..326d087bfb
--- /dev/null
+++ b/crates/calendar_events/src/inbound/toolset/mod.rs
@@ -0,0 +1,336 @@
+//! AI toolset adapter for calendar events.
+//!
+//! Tools are thin: they convert tool inputs into domain calls on the
+//! [`CalendarMutationService`] and [`CalendarOccurrenceService`] ports and
+//! map domain errors to agent-readable failures. Authorization and business
+//! policy live behind those ports, exactly as for the HTTP routers.
+
+mod create_calendar_event;
+mod delete_calendar_event;
+mod list_calendar_events;
+mod list_calendars;
+mod update_calendar_event;
+
+#[cfg(test)]
+mod test;
+
+use std::sync::Arc;
+
+use ai_toolset::{AsyncToolCollection, ToolCallError};
+use chrono::NaiveDate;
+use chrono::{DateTime, Utc};
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+use crate::domain::{
+ models::{CalendarAttendeeInput, CalendarEvent, EventTime},
+ ports::{CalendarMutationError, CalendarMutationService, CalendarOccurrenceService},
+};
+
+pub use create_calendar_event::CreateCalendarEvent;
+pub use delete_calendar_event::{
+ DeleteCalendarEvent, DeleteCalendarEventResponse, DeletionScopeInput,
+};
+pub use list_calendar_events::{
+ CalendarEventListItem, ListCalendarEvents, ListCalendarEventsResponse,
+};
+pub use list_calendars::{ListCalendars, ListCalendarsToolResponse, ToolCalendar};
+pub use update_calendar_event::{ConferenceChangeInput, UpdateCalendarEvent};
+
+/// Service context for calendar AI tools.
+pub struct CalendarToolContext<M, O>
+where
+ M: CalendarMutationService,
+ O: CalendarOccurrenceService,
+{
+ /// Write path: user-initiated mutations, written through to the provider.
+ pub mutations: Arc<M>,
+ /// Read path: bounded occurrence viewport queries.
+ pub occurrences: Arc<O>,
+}
+
+impl<M, O> Clone for CalendarToolContext<M, O>
+where
+ M: CalendarMutationService,
+ O: CalendarOccurrenceService,
+{
+ fn clone(&self) -> Self {
+ Self {
+ mutations: Arc::clone(&self.mutations),
+ occurrences: Arc::clone(&self.occurrences),
+ }
+ }
+}
+
+impl<M, O> CalendarToolContext<M, O>
+where
+ M: CalendarMutationService,
+ O: CalendarOccurrenceService,
+{
+ /// Create a calendar tool context from its two ports.
+ pub fn new(mutations: Arc<M>, occurrences: Arc<O>) -> Self {
+ Self {
+ mutations,
+ occurrences,
+ }
+ }
+}
+
+/// Create the calendar toolset.
+pub fn calendar_toolset<M, O>() -> AsyncToolCollection<CalendarToolContext<M, O>>
+where
+ M: CalendarMutationService,
+ O: CalendarOccurrenceService,
+{
+ AsyncToolCollection::new()
+ .add_tool::<ListCalendarEvents, CalendarToolContext<M, O>>()
+ .add_tool::<ListCalendars, CalendarToolContext<M, O>>()
+ .add_tool::<CreateCalendarEvent, CalendarToolContext<M, O>>()
+ .add_tool::<UpdateCalendarEvent, CalendarToolContext<M, O>>()
+ .add_tool::<DeleteCalendarEvent, CalendarToolContext<M, O>>()
+}
+
+/// The mutually exclusive time shape supplied to calendar tools.
+#[derive(Debug, Clone, PartialEq, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase", tag = "kind")]
+pub enum EventTimeInput {
+ /// A clock-time event with absolute instants.
+ #[serde(rename_all = "camelCase")]
+ Timed {
+ /// Inclusive start instant, RFC 3339 UTC (e.g. 2026-08-20T17:00:00Z).
+ starts_at: DateTime<Utc>,
+ /// Exclusive end instant, RFC 3339 UTC. Must be after the start.
+ ends_at: DateTime<Utc>,
+ /// IANA time zone the event was scheduled in (e.g.
+ /// America/New_York). Recurring events expand in this zone.
+ time_zone: Option<String>,
+ },
+ /// An all-day event spanning whole local dates.
+ #[serde(rename_all = "camelCase")]
+ AllDay {
+ /// Inclusive local start date (YYYY-MM-DD).
+ start_date: NaiveDate,
+ /// Exclusive local end date (YYYY-MM-DD); the day after the last
+ /// covered day, so a one-day event ends the next date.
+ end_date: NaiveDate,
+ },
+}
+
+impl From<EventTimeInput> for EventTime {
+ fn from(input: EventTimeInput) -> Self {
+ match input {
+ EventTimeInput::Timed {
+ starts_at,
+ ends_at,
+ time_zone,
+ } => Self::Timed {
+ starts_at,
+ ends_at,
+ time_zone,
+ },
+ EventTimeInput::AllDay {
+ start_date,
+ end_date,
+ } => Self::AllDay {
+ start_date,
+ end_date,
+ },
+ }
+ }
+}
+
+/// An attendee supplied to a calendar tool.
+#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct AttendeeInput {
+ /// Attendee email address.
+ #[schemars(description = "The attendee's email address.")]
+ pub email: String,
+ /// Whether attendance is optional.
+ #[schemars(
+ description = "Whether attendance is optional for this attendee. Defaults to required."
+ )]
+ #[serde(default)]
+ pub is_optional: bool,
+}
+
+impl From<AttendeeInput> for CalendarAttendeeInput {
+ fn from(input: AttendeeInput) -> Self {
+ Self {
+ email: input.email,
+ is_optional: input.is_optional,
+ }
+ }
+}
+
+/// An attendee of a calendar event, as returned by calendar tools.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ToolEventAttendee {
+ /// Attendee email address.
+ pub email: String,
+ /// RSVP state: needs_action, accepted, declined, or tentative.
+ pub response_status: String,
+ /// Whether this attendee organized the event.
+ pub is_organizer: bool,
+ /// Whether attendance is optional.
+ pub is_optional: bool,
+}
+
+/// A calendar event as returned by the create and update tools.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ToolCalendarEvent {
+ /// Macro calendar event id, used by UpdateCalendarEvent and
+ /// DeleteCalendarEvent.
+ pub event_id: uuid::Uuid,
+ /// Display title.
+ pub title: String,
+ /// Event start: RFC 3339 UTC instant, or YYYY-MM-DD for all-day events.
+ pub start: String,
+ /// Exclusive event end: RFC 3339 UTC instant, or YYYY-MM-DD for all-day
+ /// events.
+ pub end: String,
+ /// Whether the event covers whole days.
+ pub is_all_day: bool,
+ /// IANA time zone the event was scheduled in, when known.
+ pub time_zone: Option<String>,
+ /// Location label, when set.
+ pub location: Option<String>,
+ /// Event body, truncated for brevity.
+ pub description: Option<String>,
+ /// Event status: confirmed, tentative, or cancelled.
+ pub status: String,
+ /// Whether the event recurs.
+ pub is_recurring: bool,
+ /// Raw RFC 5545 recurrence properties, when the event recurs.
+ pub recurrence_lines: Vec<String>,
+ /// Attendees, capped at 20; `attendee_count` has the full number.
+ pub attendees: Vec<ToolEventAttendee>,
+ /// Total number of attendees.
+ pub attendee_count: usize,
+ /// Organizer email address, when known.
+ pub organizer_email: Option<String>,
+ /// Conference join URL, when a conference is attached.
+ pub conference_url: Option<String>,
+ /// Whether the user's calendar prohibits modifying this event.
+ pub is_read_only: bool,
+ /// Calendar the event belongs to, when known.
+ pub calendar_id: Option<uuid::Uuid>,
+}
+
+const DESCRIPTION_PREVIEW_CHARS: usize = 280;
+const ATTENDEES_SHOWN_MAX: usize = 20;
+
+/// Truncate an event description to a context-friendly preview.
+fn description_preview(description: Option<&str>) -> Option<String> {
+ description.map(|description| {
+ if description.chars().count() <= DESCRIPTION_PREVIEW_CHARS {
+ description.to_string()
+ } else {
+ let preview: String = description
+ .chars()
+ .take(DESCRIPTION_PREVIEW_CHARS)
+ .collect();
+ format!("{preview}…")
+ }
+ })
+}
+
+/// Render an event time as start/end strings plus the all-day flag and zone.
+fn time_fields(time: &EventTime) -> (String, String, bool, Option<String>) {
+ match time {
+ EventTime::Timed {
+ starts_at,
+ ends_at,
+ time_zone,
+ } => (
+ starts_at.to_rfc3339(),
+ ends_at.to_rfc3339(),
+ false,
+ time_zone.clone(),
+ ),
+ EventTime::AllDay {
+ start_date,
+ end_date,
+ } => (start_date.to_string(), end_date.to_string(), true, None),
+ }
+}
+
+impl ToolCalendarEvent {
+ fn from_event(event: &CalendarEvent) -> Self {
+ let (start, end, is_all_day, time_zone) = time_fields(&event.time);
+ Self {
+ event_id: event.id,
+ title: event.title.clone(),
+ start,
+ end,
+ is_all_day,
+ time_zone,
+ location: event.location.clone(),
+ description: description_preview(event.description.as_deref()),
+ status: event.status.as_str().to_string(),
+ is_recurring: !event.recurrence_lines.is_empty(),
+ recurrence_lines: event.recurrence_lines.clone(),
+ attendees: event
+ .attendees
+ .iter()
+ .take(ATTENDEES_SHOWN_MAX)
+ .map(|attendee| ToolEventAttendee {
+ email: attendee.email.clone(),
+ response_status: attendee.response_status.as_str().to_string(),
+ is_organizer: attendee.is_organizer,
+ is_optional: attendee.is_optional,
+ })
+ .collect(),
+ attendee_count: event.attendees.len(),
+ organizer_email: event.organizer_email.clone(),
+ conference_url: event.conference_url.clone(),
+ is_read_only: event.is_read_only,
+ calendar_id: event.calendar_id,
+ }
+ }
+}
+
+/// Map a domain mutation failure to an agent-readable tool error.
+fn mutation_tool_error(action: &str, error: CalendarMutationError) -> ToolCallError {
+ let description = match &error {
+ CalendarMutationError::NotFound => {
+ "The calendar event was not found — it may have been deleted or the id is stale. \
+ Use ListCalendarEvents to get current event ids."
+ .to_string()
+ }
+ CalendarMutationError::ReadOnly => {
+ "This event's calendar is read-only for the user, so it cannot be modified.".to_string()
+ }
+ CalendarMutationError::NoWritableCalendar => {
+ "No connected calendar can accept events. The user has not connected a Google \
+ Calendar with write access, or calendar sync is not enabled for their account."
+ .to_string()
+ }
+ CalendarMutationError::NotAttendee => {
+ "The user's connected account is not an attendee of this event.".to_string()
+ }
+ CalendarMutationError::InvalidInput(message) => message.clone(),
+ CalendarMutationError::ReauthRequired(_) => {
+ "Calendar access must be re-authorized. Ask the user to reconnect their calendar in \
+ settings."
+ .to_string()
+ }
+ CalendarMutationError::ProviderRejected(message) => {
+ format!("Google Calendar rejected the change: {message}")
+ }
+ CalendarMutationError::Retryable(_) => {
+ "The calendar service is temporarily unavailable. Try again shortly.".to_string()
+ }
+ CalendarMutationError::PersistFailed(_) => {
+ "The change reached Google Calendar, but Macro's copy lagged behind. It will appear \
+ after the next sync."
+ .to_string()
+ }
+ };
+ ToolCallError {
+ description: format!("Failed to {action}: {description}"),
+ internal_error: error.into(),
+ }
+}
diff --git a/crates/calendar_events/src/inbound/toolset/test.rs b/crates/calendar_events/src/inbound/toolset/test.rs
new file mode 100644
index 0000000000..3dc075b276
--- /dev/null
+++ b/crates/calendar_events/src/inbound/toolset/test.rs
@@ -0,0 +1,532 @@
+use std::sync::Mutex;
+
+use ai_toolset::schema::generate_validated_input_schema;
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext};
+use chrono::{NaiveDate, TimeZone, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use uuid::Uuid;
+
+use super::*;
+use crate::domain::models::{
+ AttendeeResponseStatus, CalendarAttendee, CalendarEventDraft, CalendarEventPatch,
+ CalendarOccurrence, CalendarSyncStatus, ConferenceChange, EventReminders, EventStatus,
+ EventTransparency, EventVisibility, OccurrenceRange, VisibleCalendar,
+};
+use crate::domain::ports::{
+ CalendarDeletionScope, CalendarMutationError, CalendarMutationService,
+ CalendarOccurrenceService, CalendarRsvpScope,
+};
+
+#[test]
+fn tool_input_schemas_satisfy_strict_mode() {
+ for (name, result) in [
+ (
+ "ListCalendarEvents",
+ generate_validated_input_schema::<ListCalendarEvents>().map(|schema| schema.name),
+ ),
+ (
+ "ListCalendars",
+ generate_validated_input_schema::<ListCalendars>().map(|schema| schema.name),
+ ),
+ (
+ "CreateCalendarEvent",
+ generate_validated_input_schema::<CreateCalendarEvent>().map(|schema| schema.name),
+ ),
+ (
+ "UpdateCalendarEvent",
+ generate_validated_input_schema::<UpdateCalendarEvent>().map(|schema| schema.name),
+ ),
+ (
+ "DeleteCalendarEvent",
+ generate_validated_input_schema::<DeleteCalendarEvent>().map(|schema| schema.name),
+ ),
+ ] {
+ match result {
+ Ok(schema_name) => assert_eq!(schema_name, name, "schema title for {name}"),
+ Err(error) => panic!("schema for {name} failed validation: {error:?}"),
+ }
+ }
+}
+
+#[test]
+fn event_time_input_deserializes_both_shapes() {
+ let timed: EventTimeInput = serde_json::from_value(serde_json::json!({
+ "kind": "timed",
+ "startsAt": "2026-08-20T17:00:00Z",
+ "endsAt": "2026-08-20T18:00:00Z",
+ "timeZone": "America/New_York",
+ }))
+ .unwrap();
+ assert!(matches!(timed, EventTimeInput::Timed { .. }));
+
+ let all_day: EventTimeInput = serde_json::from_value(serde_json::json!({
+ "kind": "allDay",
+ "startDate": "2026-08-20",
+ "endDate": "2026-08-21",
+ }))
+ .unwrap();
+ assert!(matches!(all_day, EventTimeInput::AllDay { .. }));
+}
+
+fn sample_event(recurrence_lines: Vec<String>) -> crate::domain::models::CalendarEvent {
+ crate::domain::models::CalendarEvent {
+ id: Uuid::from_u128(7),
+ owner_id: "macro|[email protected]".to_string(),
+ ical_uid: "uid-1".to_string(),
+ calendar_id: Some(Uuid::from_u128(9)),
+ title: "Standup".to_string(),
+ description: Some("Daily sync".to_string()),
+ location: Some("Room 1".to_string()),
+ status: EventStatus::Confirmed,
+ visibility: EventVisibility::Default,
+ transparency: EventTransparency::Opaque,
+ time: EventTime::Timed {
+ starts_at: Utc.with_ymd_and_hms(2026, 8, 20, 17, 0, 0).unwrap(),
+ ends_at: Utc.with_ymd_and_hms(2026, 8, 20, 18, 0, 0).unwrap(),
+ time_zone: Some("America/New_York".to_string()),
+ },
+ recurrence_lines,
+ organizer_email: Some("[email protected]".to_string()),
+ organizer_name: None,
+ conference_url: Some("https://meet.google.com/abc".to_string()),
+ conference_provider: Some(crate::domain::models::ConferenceProvider::GoogleMeet),
+ sequence: 0,
+ is_read_only: false,
+ attendees: vec![
+ CalendarAttendee {
+ email: "[email protected]".to_string(),
+ display_name: None,
+ response_status: AttendeeResponseStatus::Accepted,
+ is_organizer: true,
+ is_optional: false,
+ is_self: true,
+ comment: None,
+ },
+ CalendarAttendee {
+ email: "[email protected]".to_string(),
+ display_name: None,
+ response_status: AttendeeResponseStatus::NeedsAction,
+ is_organizer: false,
+ is_optional: true,
+ is_self: false,
+ comment: None,
+ },
+ ],
+ reminders: EventReminders::default(),
+ created_at: Utc.with_ymd_and_hms(2026, 8, 1, 0, 0, 0).unwrap(),
+ updated_at: Utc.with_ymd_and_hms(2026, 8, 1, 0, 0, 0).unwrap(),
+ }
+}
+
+fn occurrence_of(
+ event: &crate::domain::models::CalendarEvent,
+ key: &str,
+ is_cancelled: bool,
+) -> CalendarOccurrence {
+ CalendarOccurrence {
+ event_id: event.id,
+ occurrence_key: key.to_string(),
+ recurrence_id: None,
+ time: event.time.clone(),
+ is_cancelled,
+ }
+}
+
+type RecordedCreate = (Option<Uuid>, Option<Uuid>, CalendarEventDraft);
+
+#[derive(Default)]
+struct MockMutations {
+ created: Mutex<Vec<RecordedCreate>>,
+ create_error: Mutex<Option<CalendarMutationError>>,
+ updated: Mutex<Vec<(Uuid, CalendarEventPatch)>>,
+ deleted: Mutex<Vec<(Uuid, CalendarDeletionScope)>>,
+ calendars: Mutex<Vec<VisibleCalendar>>,
+}
+
+impl CalendarMutationService for MockMutations {
+ async fn create_event(
+ &self,
+ _requester_id: &str,
+ email_link_id: Option<Uuid>,
+ calendar_id: Option<Uuid>,
+ draft: CalendarEventDraft,
+ ) -> Result<crate::domain::models::CalendarEvent, CalendarMutationError> {
+ if let Some(error) = self.create_error.lock().unwrap().take() {
+ return Err(error);
+ }
+ self.created
+ .lock()
+ .unwrap()
+ .push((email_link_id, calendar_id, draft));
+ Ok(sample_event(Vec::new()))
+ }
+
+ async fn list_visible_calendars(
+ &self,
+ _requester_id: &str,
+ ) -> Result<Vec<VisibleCalendar>, CalendarMutationError> {
+ Ok(self.calendars.lock().unwrap().clone())
+ }
+
+ async fn update_event(
+ &self,
+ _requester_id: &str,
+ event_id: Uuid,
+ patch: CalendarEventPatch,
+ ) -> Result<crate::domain::models::CalendarEvent, CalendarMutationError> {
+ self.updated.lock().unwrap().push((event_id, patch));
+ Ok(sample_event(Vec::new()))
+ }
+
+ async fn delete_event(
+ &self,
+ _requester_id: &str,
+ event_id: Uuid,
+ scope: CalendarDeletionScope,
+ ) -> Result<(), CalendarMutationError> {
+ self.deleted.lock().unwrap().push((event_id, scope));
+ Ok(())
+ }
+
+ async fn respond_to_event(
+ &self,
+ _requester_id: &str,
+ _event_id: Uuid,
+ _response: AttendeeResponseStatus,
+ _scope: CalendarRsvpScope,
+ ) -> Result<crate::domain::models::CalendarEvent, CalendarMutationError> {
+ unreachable!("no calendar tool responds to events")
+ }
+
+ async fn disconnect_calendar(
+ &self,
+ _requester_id: &str,
+ _email_link_id: Uuid,
+ ) -> Result<(), CalendarMutationError> {
+ unreachable!("no calendar tool disconnects calendars")
+ }
+}
+
+struct MockOccurrences {
+ rows: Mutex<Vec<(crate::domain::models::CalendarEvent, CalendarOccurrence)>>,
+ status: CalendarSyncStatus,
+}
+
+impl CalendarOccurrenceService for MockOccurrences {
+ async fn list_occurrences(
+ &self,
+ _requester_id: &str,
+ _range: OccurrenceRange,
+ cursor: Option<crate::domain::models::CalendarOccurrenceCursor>,
+ limit: u16,
+ ) -> Result<Vec<(crate::domain::models::CalendarEvent, CalendarOccurrence)>, rootcause::Report>
+ {
+ let rows = self.rows.lock().unwrap().clone();
+ let start = cursor
+ .map(|cursor| {
+ rows.iter()
+ .position(|(_, occurrence)| occurrence.occurrence_key == cursor.occurrence_key)
+ .map_or(rows.len(), |position| position + 1)
+ })
+ .unwrap_or(0);
+ let mut page: Vec<_> = rows.into_iter().skip(start).collect();
+ page.truncate(usize::from(limit));
+ Ok(page)
+ }
+
+ async fn sync_status(
+ &self,
+ _requester_id: &str,
+ ) -> Result<CalendarSyncStatus, rootcause::Report> {
+ Ok(self.status)
+ }
+}
+
+fn context(
+ mutations: MockMutations,
+ occurrences: MockOccurrences,
+) -> (
+ std::sync::Arc<MockMutations>,
+ ServiceContext<CalendarToolContext<MockMutations, MockOccurrences>>,
+) {
+ let mutations = std::sync::Arc::new(mutations);
+ let context = CalendarToolContext::new(mutations.clone(), std::sync::Arc::new(occurrences));
+ (mutations, ServiceContext(context))
+}
+
+fn request_context() -> RequestContext {
+ RequestContext::new(MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap())
+}
+
+fn empty_occurrences() -> MockOccurrences {
+ MockOccurrences {
+ rows: Mutex::new(Vec::new()),
+ status: CalendarSyncStatus::Ready,
+ }
+}
+
+#[tokio::test]
+async fn create_converts_input_into_a_domain_draft() {
+ let (mutations, context) = context(MockMutations::default(), empty_occurrences());
+ let calendar_id = Uuid::from_u128(3);
+
+ let tool = CreateCalendarEvent {
+ title: "Design review".to_string(),
+ time: EventTimeInput::AllDay {
+ start_date: NaiveDate::from_ymd_opt(2026, 8, 21).unwrap(),
+ end_date: NaiveDate::from_ymd_opt(2026, 8, 22).unwrap(),
+ },
+ description: Some("Quarterly".to_string()),
+ location: None,
+ attendees: vec![AttendeeInput {
+ email: "[email protected]".to_string(),
+ is_optional: true,
+ }],
+ recurrence_lines: vec!["RRULE:FREQ=WEEKLY".to_string()],
+ calendar_id: Some(calendar_id),
+ add_google_meet: true,
+ };
+ let response = tool.call(context, request_context()).await.unwrap();
+ assert_eq!(response.event_id, Uuid::from_u128(7));
+
+ let created = mutations.created.lock().unwrap();
+ let (email_link_id, target_calendar, draft) = created.first().expect("one create call");
+ assert_eq!(*email_link_id, None);
+ assert_eq!(*target_calendar, Some(calendar_id));
+ assert_eq!(draft.title, "Design review");
+ assert_eq!(draft.attendees.len(), 1);
+ assert!(draft.attendees[0].is_optional);
+ assert_eq!(
+ draft.recurrence_lines,
+ vec!["RRULE:FREQ=WEEKLY".to_string()]
+ );
+ assert_eq!(draft.conference, Some(ConferenceChange::GoogleMeet));
+ assert!(matches!(draft.time, EventTime::AllDay { .. }));
+}
+
+#[tokio::test]
+async fn create_surfaces_missing_calendar_as_an_actionable_error() {
+ let mutations = MockMutations {
+ create_error: Mutex::new(Some(CalendarMutationError::NoWritableCalendar)),
+ ..Default::default()
+ };
+ let (_, context) = context(mutations, empty_occurrences());
+
+ let tool = CreateCalendarEvent {
+ title: "Lunch".to_string(),
+ time: EventTimeInput::Timed {
+ starts_at: Utc.with_ymd_and_hms(2026, 8, 20, 12, 0, 0).unwrap(),
+ ends_at: Utc.with_ymd_and_hms(2026, 8, 20, 13, 0, 0).unwrap(),
+ time_zone: None,
+ },
+ description: None,
+ location: None,
+ attendees: Vec::new(),
+ recurrence_lines: Vec::new(),
+ calendar_id: None,
+ add_google_meet: false,
+ };
+ let error = tool.call(context, request_context()).await.unwrap_err();
+ assert!(
+ error
+ .description
+ .contains("not connected a Google Calendar"),
+ "unexpected description: {}",
+ error.description
+ );
+}
+
+#[tokio::test]
+async fn update_converts_input_into_a_domain_patch() {
+ let (mutations, context) = context(MockMutations::default(), empty_occurrences());
+ let event_id = Uuid::from_u128(11);
+
+ let tool = UpdateCalendarEvent {
+ event_id,
+ title: Some("Renamed".to_string()),
+ description: Some(String::new()),
+ location: None,
+ time: None,
+ attendees: Some(vec![AttendeeInput {
+ email: "[email protected]".to_string(),
+ is_optional: false,
+ }]),
+ recurrence_lines: None,
+ conference: Some(ConferenceChangeInput::Remove),
+ };
+ tool.call(context, request_context()).await.unwrap();
+
+ let updated = mutations.updated.lock().unwrap();
+ let (patched_id, patch) = updated.first().expect("one update call");
+ assert_eq!(*patched_id, event_id);
+ assert_eq!(patch.title.as_deref(), Some("Renamed"));
+ assert_eq!(patch.description.as_deref(), Some(""));
+ assert_eq!(patch.location, None);
+ assert_eq!(
+ patch.attendees.as_ref().map(|attendees| attendees.len()),
+ Some(1)
+ );
+ assert_eq!(patch.conference, Some(ConferenceChange::Removed));
+}
+
+#[tokio::test]
+async fn scoped_deletion_requires_a_recurrence_id() {
+ let (mutations, context) = context(MockMutations::default(), empty_occurrences());
+
+ let tool = DeleteCalendarEvent {
+ event_id: Uuid::from_u128(11),
+ scope: DeletionScopeInput::ThisEvent,
+ recurrence_id: None,
+ };
+ let error = tool.call(context, request_context()).await.unwrap_err();
+ assert!(error.description.contains("recurrenceId"));
+ assert!(mutations.deleted.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn deletion_passes_the_selected_scope() {
+ let (mutations, context) = context(MockMutations::default(), empty_occurrences());
+ let event_id = Uuid::from_u128(11);
+
+ let tool = DeleteCalendarEvent {
+ event_id,
+ scope: DeletionScopeInput::ThisAndFollowing,
+ recurrence_id: Some("2026-08-20T17:00:00+00:00".to_string()),
+ };
+ let response = tool.call(context, request_context()).await.unwrap();
+ assert_eq!(response.event_id, event_id);
+
+ let deleted = mutations.deleted.lock().unwrap();
+ assert_eq!(
+ deleted.first(),
+ Some(&(
+ event_id,
+ CalendarDeletionScope::ThisAndFollowing {
+ recurrence_id: "2026-08-20T17:00:00+00:00".to_string(),
+ }
+ ))
+ );
+}
+
+#[tokio::test]
+async fn list_events_maps_occurrences_and_skips_cancelled_ones() {
+ let recurring = sample_event(vec!["RRULE:FREQ=DAILY".to_string()]);
+ let occurrences = MockOccurrences {
+ rows: Mutex::new(vec![
+ (recurring.clone(), occurrence_of(&recurring, "k-1", false)),
+ (recurring.clone(), occurrence_of(&recurring, "k-2", true)),
+ ]),
+ status: CalendarSyncStatus::Syncing,
+ };
+ let (_, context) = context(MockMutations::default(), occurrences);
+
+ let tool = ListCalendarEvents {
+ start: Utc.with_ymd_and_hms(2026, 8, 20, 0, 0, 0).unwrap(),
+ end: Utc.with_ymd_and_hms(2026, 8, 27, 0, 0, 0).unwrap(),
+ };
+ let response = tool.call(context, request_context()).await.unwrap();
+
+ assert_eq!(response.events.len(), 1, "cancelled occurrence is skipped");
+ let item = &response.events[0];
+ assert_eq!(item.event_id, recurring.id);
+ assert!(item.is_recurring);
+ assert_eq!(item.recurrence_id.as_deref(), Some("k-1"));
+ assert_eq!(item.my_response.as_deref(), Some("accepted"));
+ assert_eq!(item.attendee_count, 2);
+ assert!(!item.is_all_day);
+ assert_eq!(response.sync_status, "syncing");
+ assert!(response.summary.contains("still syncing"));
+ assert!(!response.truncated);
+}
+
+#[tokio::test]
+async fn list_events_reports_truncation() {
+ let event = sample_event(Vec::new());
+ let max = usize::from(super::list_calendar_events::OCCURRENCES_MAX);
+ let rows = (0..max + 1)
+ .map(|index| {
+ (
+ event.clone(),
+ occurrence_of(&event, &format!("k-{index}"), false),
+ )
+ })
+ .collect();
+ let occurrences = MockOccurrences {
+ rows: Mutex::new(rows),
+ status: CalendarSyncStatus::Ready,
+ };
+ let (_, context) = context(MockMutations::default(), occurrences);
+
+ let tool = ListCalendarEvents {
+ start: Utc.with_ymd_and_hms(2026, 8, 20, 0, 0, 0).unwrap(),
+ end: Utc.with_ymd_and_hms(2026, 8, 27, 0, 0, 0).unwrap(),
+ };
+ let response = tool.call(context, request_context()).await.unwrap();
+ assert_eq!(response.events.len(), max);
+ assert!(response.truncated);
+ assert!(response.summary.contains("narrow the window"));
+}
+
+#[tokio::test]
+async fn cancelled_occurrences_do_not_count_toward_truncation() {
+ let event = sample_event(Vec::new());
+ let max = usize::from(super::list_calendar_events::OCCURRENCES_MAX);
+ // Exactly the cap of active occurrences plus one cancelled row in the
+ // middle: the first page overflows only because of the cancelled row, so
+ // the tool must page past it instead of reporting truncation.
+ let mut rows: Vec<_> = (0..max)
+ .map(|index| {
+ (
+ event.clone(),
+ occurrence_of(&event, &format!("k-{index}"), false),
+ )
+ })
+ .collect();
+ rows.insert(
+ max / 2,
+ (event.clone(), occurrence_of(&event, "k-cancelled", true)),
+ );
+ let occurrences = MockOccurrences {
+ rows: Mutex::new(rows),
+ status: CalendarSyncStatus::Ready,
+ };
+ let (_, context) = context(MockMutations::default(), occurrences);
+
+ let tool = ListCalendarEvents {
+ start: Utc.with_ymd_and_hms(2026, 8, 20, 0, 0, 0).unwrap(),
+ end: Utc.with_ymd_and_hms(2026, 8, 27, 0, 0, 0).unwrap(),
+ };
+ let response = tool.call(context, request_context()).await.unwrap();
+ assert_eq!(response.events.len(), max);
+ assert!(!response.truncated);
+}
+
+#[tokio::test]
+async fn list_calendars_maps_visible_calendars() {
+ let mutations = MockMutations {
+ calendars: Mutex::new(vec![VisibleCalendar {
+ id: Uuid::from_u128(3),
+ email_link_id: Uuid::from_u128(4),
+ email_address: "[email protected]".to_string(),
+ name: "Work".to_string(),
+ color: None,
+ is_primary: true,
+ is_writable: true,
+ default_reminders: Vec::new(),
+ }]),
+ ..Default::default()
+ };
+ let (_, context) = context(mutations, empty_occurrences());
+
+ let response = ListCalendars {}
+ .call(context, request_context())
+ .await
+ .unwrap();
+ assert_eq!(response.calendars.len(), 1);
+ let calendar = &response.calendars[0];
+ assert_eq!(calendar.calendar_id, Uuid::from_u128(3));
+ assert_eq!(calendar.email_address, "[email protected]");
+ assert!(calendar.is_primary);
+ assert!(calendar.is_writable);
+ assert_eq!(response.summary, "Found 1 calendar.");
+}
diff --git a/crates/calendar_events/src/inbound/toolset/update_calendar_event.rs b/crates/calendar_events/src/inbound/toolset/update_calendar_event.rs
new file mode 100644
index 0000000000..35658dc043
--- /dev/null
+++ b/crates/calendar_events/src/inbound/toolset/update_calendar_event.rs
@@ -0,0 +1,163 @@
+//! UpdateCalendarEvent tool for editing existing calendar events.
+
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,
+};
+use async_trait::async_trait;
+use schemars::JsonSchema;
+use serde::Deserialize;
+
+use super::{
+ AttendeeInput, CalendarToolContext, EventTimeInput, ToolCalendarEvent, mutation_tool_error,
+};
+use crate::domain::{
+ models::{CalendarEventPatch, ConferenceChange},
+ ports::{CalendarMutationService, CalendarOccurrenceService},
+};
+
+/// A requested change to an event's video conference.
+#[derive(Debug, Deserialize, JsonSchema, Clone, Copy, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum ConferenceChangeInput {
+ /// Generate a new Google Meet conference and attach it.
+ GoogleMeet,
+ /// Detach whatever conference is currently attached.
+ Remove,
+}
+
+impl From<ConferenceChangeInput> for ConferenceChange {
+ fn from(input: ConferenceChangeInput) -> Self {
+ match input {
+ ConferenceChangeInput::GoogleMeet => Self::GoogleMeet,
+ ConferenceChangeInput::Remove => Self::Removed,
+ }
+ }
+}
+
+/// Update fields of a calendar event.
+#[derive(Debug, Deserialize, JsonSchema, Clone)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "UpdateCalendarEvent",
+ description = "\
+Update an existing calendar event. Only the supplied fields change; omitted fields keep \
+their current values. The change is written to Google immediately and attendees are \
+notified of it, so confirm details with the user first. Get the `eventId` from \
+ListCalendarEvents.\n\
+\n\
+Passing `attendees` replaces the full attendee list — include everyone who should remain, \
+not just additions. An empty string for `description` or `location` clears it. Updating a \
+recurring event changes the whole series. Fails on events from calendars the user cannot \
+edit."
+)]
+pub struct UpdateCalendarEvent {
+ /// Event to update.
+ #[schemars(description = "The event's id, from ListCalendarEvents or CreateCalendarEvent.")]
+ pub event_id: uuid::Uuid,
+
+ /// Replacement title.
+ #[schemars(description = "Replacement title. Omit to keep the current title.")]
+ #[serde(default)]
+ pub title: Option<String>,
+
+ /// Replacement description.
+ #[schemars(
+ description = "Replacement event body/description. An empty string clears it; omit to \
+ keep the current one."
+ )]
+ #[serde(default)]
+ pub description: Option<String>,
+
+ /// Replacement location.
+ #[schemars(
+ description = "Replacement location label. An empty string clears it; omit to keep \
+ the current one."
+ )]
+ #[serde(default)]
+ pub location: Option<String>,
+
+ /// Replacement time.
+ #[schemars(
+ description = "Replacement time: a timed span with `kind` \"timed\" (startsAt, endsAt, \
+ optional timeZone) or whole days with `kind` \"allDay\" (startDate, \
+ exclusive endDate). Omit to keep the current time."
+ )]
+ #[serde(default)]
+ pub time: Option<EventTimeInput>,
+
+ /// Replacement attendee list.
+ #[schemars(
+ description = "Replacement attendee list — replaces all current attendees, so include \
+ everyone who should remain. Omit to leave attendees unchanged."
+ )]
+ #[serde(default)]
+ pub attendees: Option<Vec<AttendeeInput>>,
+
+ /// Replacement recurrence properties.
+ #[schemars(
+ description = "Replacement RFC 5545 recurrence lines. An empty list makes the event \
+ one-off; omit to keep the current recurrence."
+ )]
+ #[serde(default)]
+ pub recurrence_lines: Option<Vec<String>>,
+
+ /// Conference change.
+ #[schemars(
+ description = "Change the event's video conference: \"google_meet\" attaches a fresh \
+ Google Meet, \"remove\" detaches the current conference. Omit to leave \
+ it untouched."
+ )]
+ #[serde(default)]
+ pub conference: Option<ConferenceChangeInput>,
+}
+
+impl ToolAnnotated for UpdateCalendarEvent {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Update calendar event");
+}
+
+#[async_trait]
+impl<M, O> AsyncTool<CalendarToolContext<M, O>> for UpdateCalendarEvent
+where
+ M: CalendarMutationService,
+ O: CalendarOccurrenceService,
+{
+ type Output = ToolCalendarEvent;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<CalendarToolContext<M, O>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ tracing::info!(
+ event_id=%self.event_id,
+ attendee_count=?self.attendees.as_ref().map(Vec::len),
+ "Update calendar event"
+ );
+
+ let requester_id = request_context.user_id.to_string();
+ let patch = CalendarEventPatch {
+ title: self.title.clone(),
+ description: self.description.clone(),
+ location: self.location.clone(),
+ time: self.time.clone().map(Into::into),
+ attendees: self
+ .attendees
+ .clone()
+ .map(|attendees| attendees.into_iter().map(Into::into).collect()),
+ recurrence_lines: self.recurrence_lines.clone(),
+ visibility: None,
+ transparency: None,
+ reminders: None,
+ conference: self.conference.map(Into::into),
+ };
+
+ let event = service_context
+ .mutations
+ .update_event(&requester_id, self.event_id, patch)
+ .await
+ .map_err(|error| mutation_tool_error("update the calendar event", error))?;
+
+ Ok(ToolCalendarEvent::from_event(&event))
+ }
+}
diff --git a/crates/calendar_events/src/lib.rs b/crates/calendar_events/src/lib.rs
index a0ea735b79..46e99af9c5 100644
--- a/crates/calendar_events/src/lib.rs
+++ b/crates/calendar_events/src/lib.rs
@@ -8,13 +8,14 @@
/// Calendar business models, ports, and services.
pub mod domain;
/// Inbound adapters that expose calendar use cases and accepted formats.
-#[cfg(any(feature = "inbound", feature = "dispatch"))]
+#[cfg(any(feature = "inbound", feature = "dispatch", feature = "ai_tools"))]
pub mod inbound;
/// Database and provider adapters used by service composition roots.
#[cfg(any(
feature = "google",
feature = "postgres",
feature = "dispatch-sqs",
- feature = "notify"
+ feature = "notify",
+ feature = "mutation-client"
))]
pub mod outbound;
diff --git a/crates/calendar_events/src/outbound/email_service_mutations.rs b/crates/calendar_events/src/outbound/email_service_mutations.rs
new file mode 100644
index 0000000000..069a2ce391
--- /dev/null
+++ b/crates/calendar_events/src/outbound/email_service_mutations.rs
@@ -0,0 +1,341 @@
+//! Email-service HTTP adapter for the calendar mutation port.
+//!
+//! The email service is the calendar write authority: it holds the Google
+//! provider client, token minting, and the per-inbox request gate. Hosts
+//! that expose calendar mutations without those dependencies (the AI tool
+//! hosts) implement [`CalendarMutationService`] through this client, so
+//! every mutation flows through the same routes, validation, and error
+//! mapping as user-initiated ones.
+
+#[cfg(all(test, feature = "inbound"))]
+mod test;
+
+use reqwest::StatusCode;
+use serde::Deserialize;
+use uuid::Uuid;
+
+use crate::domain::{
+ models::{
+ AttendeeResponseStatus, CalendarEvent, CalendarEventDraft, CalendarEventPatch,
+ VisibleCalendar,
+ },
+ ports::{
+ CalendarDeletionScope, CalendarMutationError, CalendarMutationService, CalendarRsvpScope,
+ },
+};
+
+/// Header carrying the shared key for internal service authorization.
+const INTERNAL_API_KEY_HEADER: &str = "x-internal-auth-key";
+/// Header carrying the acting Macro user for internal authorization.
+const INTERNAL_MACRO_USER_ID_HEADER: &str = "x-internal-macro-user-id";
+
+/// Calendar mutation client calling the email service with internal
+/// authorization on behalf of the requesting user.
+pub struct EmailServiceCalendarMutations {
+ base_url: String,
+ internal_api_key: String,
+ http: reqwest::Client,
+}
+
+impl EmailServiceCalendarMutations {
+ /// Construct the client for the email service at `base_url`.
+ pub fn new(base_url: String, internal_api_key: String) -> Self {
+ Self {
+ base_url: base_url.trim_end_matches('/').to_string(),
+ internal_api_key,
+ http: reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(30))
+ .build()
+ .expect("static reqwest client configuration is valid"),
+ }
+ }
+
+ fn request(
+ &self,
+ method: reqwest::Method,
+ path: &str,
+ requester_id: &str,
+ ) -> reqwest::RequestBuilder {
+ self.http
+ .request(method, format!("{}{path}", self.base_url))
+ .header(INTERNAL_API_KEY_HEADER, &self.internal_api_key)
+ .header(INTERNAL_MACRO_USER_ID_HEADER, requester_id)
+ }
+
+ async fn send(
+ &self,
+ request: reqwest::RequestBuilder,
+ ) -> Result<reqwest::Response, CalendarMutationError> {
+ let response = request.send().await.map_err(|error| {
+ CalendarMutationError::Retryable(format!(
+ "calendar mutation request failed to reach the email service: {error}"
+ ))
+ })?;
+ let status = response.status();
+ if status.is_success() {
+ return Ok(response);
+ }
+ Err(error_from_response(status, response.text().await.ok()))
+ }
+
+ async fn event_from(
+ &self,
+ request: reqwest::RequestBuilder,
+ ) -> Result<CalendarEvent, CalendarMutationError> {
+ self.send(request)
+ .await?
+ .json::<CalendarEvent>()
+ .await
+ .map_err(|error| {
+ CalendarMutationError::PersistFailed(format!(
+ "calendar mutation succeeded but its echo could not be parsed: {error}"
+ ))
+ })
+ }
+}
+
+/// Wire body for the calendars listing.
+#[derive(Deserialize)]
+struct ListCalendarsWire {
+ calendars: Vec<VisibleCalendar>,
+}
+
+/// Wire body of a mutation error response.
+#[derive(Deserialize)]
+struct MutationErrorWire {
+ code: String,
+ message: String,
+}
+
+/// Map an error response to the domain failure its code encodes.
+fn error_from_response(status: StatusCode, body: Option<String>) -> CalendarMutationError {
+ let parsed = body
+ .as_deref()
+ .and_then(|body| serde_json::from_str::<MutationErrorWire>(body).ok());
+ let Some(error) = parsed else {
+ return fallback_error(
+ status,
+ format!(
+ "the email service calendar API returned status {status} with no mutation \
+ error body"
+ ),
+ );
+ };
+ match error.code.as_str() {
+ "not_found" => CalendarMutationError::NotFound,
+ "read_only" => CalendarMutationError::ReadOnly,
+ "no_writable_calendar" => CalendarMutationError::NoWritableCalendar,
+ "not_attendee" => CalendarMutationError::NotAttendee,
+ "invalid_input" => CalendarMutationError::InvalidInput(error.message),
+ "reauth_required" => CalendarMutationError::ReauthRequired(error.message),
+ "provider_rejected" => CalendarMutationError::ProviderRejected(error.message),
+ "retryable" => CalendarMutationError::Retryable(error.message),
+ "persist_failed" => CalendarMutationError::PersistFailed(error.message),
+ _ => fallback_error(status, error.message),
+ }
+}
+
+/// Classify an unrecognized failure by its status. Marking a client error
+/// retryable would invite a duplicate non-idempotent write (a retried create
+/// makes a second event and re-invites its attendees), so only statuses that
+/// genuinely signal a transient condition stay [`CalendarMutationError::Retryable`].
+fn fallback_error(status: StatusCode, message: String) -> CalendarMutationError {
+ match status {
+ StatusCode::NOT_FOUND => CalendarMutationError::NotFound,
+ StatusCode::REQUEST_TIMEOUT | StatusCode::TOO_MANY_REQUESTS => {
+ CalendarMutationError::Retryable(message)
+ }
+ _ if status.is_client_error() => CalendarMutationError::InvalidInput(message),
+ _ => CalendarMutationError::Retryable(message),
+ }
+}
+
+/// Wire body for event creation, matching `CreateCalendarEventRequest`.
+fn create_body(
+ email_link_id: Option<Uuid>,
+ calendar_id: Option<Uuid>,
+ draft: &CalendarEventDraft,
+) -> serde_json::Value {
+ serde_json::json!({
+ "emailLinkId": email_link_id,
+ "calendarId": calendar_id,
+ "title": draft.title,
+ "description": draft.description,
+ "location": draft.location,
+ "time": draft.time,
+ "attendees": attendees_body(&draft.attendees),
+ "recurrenceLines": draft.recurrence_lines,
+ "visibility": draft.visibility,
+ "transparency": draft.transparency,
+ "reminders": draft.reminders,
+ "conference": draft.conference,
+ })
+}
+
+/// Wire body for an event patch, matching `UpdateCalendarEventRequest`.
+fn update_body(patch: &CalendarEventPatch) -> serde_json::Value {
+ serde_json::json!({
+ "title": patch.title,
+ "description": patch.description,
+ "location": patch.location,
+ "time": patch.time,
+ "attendees": patch
+ .attendees
+ .as_deref()
+ .map(attendees_body),
+ "recurrenceLines": patch.recurrence_lines,
+ "visibility": patch.visibility,
+ "transparency": patch.transparency,
+ "reminders": patch.reminders,
+ "conference": patch.conference,
+ })
+}
+
+fn attendees_body(
+ attendees: &[crate::domain::models::CalendarAttendeeInput],
+) -> Vec<serde_json::Value> {
+ attendees
+ .iter()
+ .map(|attendee| {
+ serde_json::json!({
+ "email": attendee.email,
+ "isOptional": attendee.is_optional,
+ })
+ })
+ .collect()
+}
+
+/// Wire query for a deletion scope, matching `DeleteCalendarEventQuery`.
+fn delete_query(scope: &CalendarDeletionScope) -> Vec<(&'static str, String)> {
+ match scope {
+ CalendarDeletionScope::All => vec![("scope", "all".to_string())],
+ CalendarDeletionScope::ThisEvent { recurrence_id } => vec![
+ ("scope", "this_event".to_string()),
+ ("recurrenceId", recurrence_id.clone()),
+ ],
+ CalendarDeletionScope::ThisAndFollowing { recurrence_id } => vec![
+ ("scope", "this_and_following".to_string()),
+ ("recurrenceId", recurrence_id.clone()),
+ ],
+ }
+}
+
+/// Wire body for an RSVP, matching `RsvpCalendarEventRequest`.
+fn rsvp_body(response: AttendeeResponseStatus, scope: &CalendarRsvpScope) -> serde_json::Value {
+ match scope {
+ CalendarRsvpScope::All => serde_json::json!({
+ "response": response,
+ "scope": "all",
+ }),
+ CalendarRsvpScope::ThisEvent { recurrence_id } => serde_json::json!({
+ "response": response,
+ "scope": "this_event",
+ "recurrenceId": recurrence_id,
+ }),
+ }
+}
+
+impl CalendarMutationService for EmailServiceCalendarMutations {
+ #[tracing::instrument(skip(self, requester_id, draft), err)]
+ async fn create_event(
+ &self,
+ requester_id: &str,
+ email_link_id: Option<Uuid>,
+ calendar_id: Option<Uuid>,
+ draft: CalendarEventDraft,
+ ) -> Result<CalendarEvent, CalendarMutationError> {
+ self.event_from(
+ self.request(reqwest::Method::POST, "/calendar/events", requester_id)
+ .json(&create_body(email_link_id, calendar_id, &draft)),
+ )
+ .await
+ }
+
+ #[tracing::instrument(skip(self, requester_id), err)]
+ async fn list_visible_calendars(
+ &self,
+ requester_id: &str,
+ ) -> Result<Vec<VisibleCalendar>, CalendarMutationError> {
+ self.send(self.request(reqwest::Method::GET, "/calendar/calendars", requester_id))
+ .await?
+ .json::<ListCalendarsWire>()
+ .await
+ .map(|wire| wire.calendars)
+ .map_err(|error| {
+ CalendarMutationError::Retryable(format!(
+ "the calendars listing could not be parsed: {error}"
+ ))
+ })
+ }
+
+ #[tracing::instrument(skip(self, requester_id, patch), err)]
+ async fn update_event(
+ &self,
+ requester_id: &str,
+ event_id: Uuid,
+ patch: CalendarEventPatch,
+ ) -> Result<CalendarEvent, CalendarMutationError> {
+ self.event_from(
+ self.request(
+ reqwest::Method::PATCH,
+ &format!("/calendar/events/{event_id}"),
+ requester_id,
+ )
+ .json(&update_body(&patch)),
+ )
+ .await
+ }
+
+ #[tracing::instrument(skip(self, requester_id), err)]
+ async fn delete_event(
+ &self,
+ requester_id: &str,
+ event_id: Uuid,
+ scope: CalendarDeletionScope,
+ ) -> Result<(), CalendarMutationError> {
+ self.send(
+ self.request(
+ reqwest::Method::DELETE,
+ &format!("/calendar/events/{event_id}"),
+ requester_id,
+ )
+ .query(&delete_query(&scope)),
+ )
+ .await
+ .map(|_| ())
+ }
+
+ #[tracing::instrument(skip(self, requester_id), err)]
+ async fn respond_to_event(
+ &self,
+ requester_id: &str,
+ event_id: Uuid,
+ response: AttendeeResponseStatus,
+ scope: CalendarRsvpScope,
+ ) -> Result<CalendarEvent, CalendarMutationError> {
+ self.event_from(
+ self.request(
+ reqwest::Method::PUT,
+ &format!("/calendar/events/{event_id}/rsvp"),
+ requester_id,
+ )
+ .json(&rsvp_body(response, &scope)),
+ )
+ .await
+ }
+
+ #[tracing::instrument(skip(self, requester_id), err)]
+ async fn disconnect_calendar(
+ &self,
+ requester_id: &str,
+ email_link_id: Uuid,
+ ) -> Result<(), CalendarMutationError> {
+ self.send(self.request(
+ reqwest::Method::DELETE,
+ &format!("/email/links/{email_link_id}/calendar"),
+ requester_id,
+ ))
+ .await
+ .map(|_| ())
+ }
+}
diff --git a/crates/calendar_events/src/outbound/email_service_mutations/test.rs b/crates/calendar_events/src/outbound/email_service_mutations/test.rs
new file mode 100644
index 0000000000..7c97b47c5c
--- /dev/null
+++ b/crates/calendar_events/src/outbound/email_service_mutations/test.rs
@@ -0,0 +1,171 @@
+//! Wire-contract tests: the client's bodies and queries must deserialize
+//! into the mutation router's request DTOs, and the router's error bodies
+//! must map back to the domain failures they encode.
+
+use chrono::{TimeZone, Utc};
+use reqwest::StatusCode;
+use uuid::Uuid;
+
+use super::*;
+use crate::domain::models::{CalendarAttendeeInput, EventReminders, EventTime};
+use crate::inbound::mutation_router::{
+ CalendarMutationApiError, CreateCalendarEventRequest, DeleteCalendarEventQuery,
+ RsvpCalendarEventRequest, UpdateCalendarEventRequest,
+};
+
+fn sample_draft() -> CalendarEventDraft {
+ CalendarEventDraft {
+ title: "Standup".to_string(),
+ description: Some("Daily".to_string()),
+ location: None,
+ time: EventTime::Timed {
+ starts_at: Utc.with_ymd_and_hms(2026, 8, 20, 17, 0, 0).unwrap(),
+ ends_at: Utc.with_ymd_and_hms(2026, 8, 20, 18, 0, 0).unwrap(),
+ time_zone: Some("America/New_York".to_string()),
+ },
+ attendees: vec![CalendarAttendeeInput {
+ email: "[email protected]".to_string(),
+ is_optional: true,
+ }],
+ recurrence_lines: vec!["RRULE:FREQ=WEEKLY".to_string()],
+ visibility: None,
+ transparency: None,
+ reminders: Some(EventReminders::default()),
+ conference: Some(crate::domain::models::ConferenceChange::GoogleMeet),
+ }
+}
+
+#[test]
+fn create_body_matches_the_router_request() {
+ let calendar_id = Some(Uuid::from_u128(3));
+ let body = create_body(None, calendar_id, &sample_draft());
+ let request: CreateCalendarEventRequest = serde_json::from_value(body).unwrap();
+
+ assert_eq!(request.calendar_id, calendar_id);
+ assert_eq!(request.email_link_id, None);
+ assert_eq!(request.title, "Standup");
+ assert_eq!(request.description.as_deref(), Some("Daily"));
+ assert!(matches!(request.time, EventTime::Timed { .. }));
+ assert_eq!(request.attendees.len(), 1);
+ assert!(request.attendees[0].is_optional);
+ assert_eq!(request.recurrence_lines, vec!["RRULE:FREQ=WEEKLY"]);
+ assert_eq!(request.reminders, Some(EventReminders::default()));
+ assert_eq!(
+ request.conference,
+ Some(crate::domain::models::ConferenceChange::GoogleMeet)
+ );
+}
+
+#[test]
+fn update_body_matches_the_router_request() {
+ let patch = CalendarEventPatch {
+ title: Some("Renamed".to_string()),
+ description: Some(String::new()),
+ attendees: Some(vec![CalendarAttendeeInput {
+ email: "[email protected]".to_string(),
+ is_optional: false,
+ }]),
+ conference: Some(crate::domain::models::ConferenceChange::Removed),
+ ..Default::default()
+ };
+ let request: UpdateCalendarEventRequest = serde_json::from_value(update_body(&patch)).unwrap();
+
+ assert_eq!(request.title.as_deref(), Some("Renamed"));
+ assert_eq!(request.description.as_deref(), Some(""));
+ assert_eq!(request.location, None);
+ assert!(request.time.is_none());
+ assert_eq!(request.attendees.map(|attendees| attendees.len()), Some(1));
+ assert!(request.recurrence_lines.is_none());
+ assert_eq!(
+ request.conference,
+ Some(crate::domain::models::ConferenceChange::Removed)
+ );
+}
+
+#[test]
+fn delete_query_matches_the_router_query() {
+ for (scope, expected_recurrence) in [
+ (CalendarDeletionScope::All, None),
+ (
+ CalendarDeletionScope::ThisEvent {
+ recurrence_id: "k-1".to_string(),
+ },
+ Some("k-1"),
+ ),
+ (
+ CalendarDeletionScope::ThisAndFollowing {
+ recurrence_id: "k-2".to_string(),
+ },
+ Some("k-2"),
+ ),
+ ] {
+ let pairs = delete_query(&scope);
+ let map: serde_json::Map<String, serde_json::Value> = pairs
+ .into_iter()
+ .map(|(key, value)| (key.to_string(), serde_json::Value::String(value)))
+ .collect();
+ let query: DeleteCalendarEventQuery =
+ serde_json::from_value(serde_json::Value::Object(map)).unwrap();
+ assert_eq!(query.recurrence_id.as_deref(), expected_recurrence);
+ }
+}
+
+#[test]
+fn rsvp_body_matches_the_router_request() {
+ let body = rsvp_body(
+ AttendeeResponseStatus::Accepted,
+ &CalendarRsvpScope::ThisEvent {
+ recurrence_id: "k-1".to_string(),
+ },
+ );
+ let request: RsvpCalendarEventRequest = serde_json::from_value(body).unwrap();
+ assert_eq!(request.response, AttendeeResponseStatus::Accepted);
+ assert_eq!(request.recurrence_id.as_deref(), Some("k-1"));
+}
+
+#[test]
+fn router_error_bodies_round_trip_to_their_domain_failures() {
+ let cases = [
+ CalendarMutationError::NotFound,
+ CalendarMutationError::ReadOnly,
+ CalendarMutationError::NoWritableCalendar,
+ CalendarMutationError::NotAttendee,
+ CalendarMutationError::InvalidInput("bad".to_string()),
+ CalendarMutationError::ReauthRequired("expired".to_string()),
+ CalendarMutationError::ProviderRejected("no".to_string()),
+ CalendarMutationError::Retryable("later".to_string()),
+ CalendarMutationError::PersistFailed("lag".to_string()),
+ ];
+ for domain_error in cases {
+ let expected = std::mem::discriminant(&domain_error);
+ let api_error = CalendarMutationApiError::from(domain_error);
+ let body = serde_json::to_string(&api_error).unwrap();
+ let parsed = error_from_response(StatusCode::BAD_REQUEST, Some(body));
+ assert_eq!(std::mem::discriminant(&parsed), expected);
+ }
+}
+
+#[test]
+fn unrecognized_failures_are_classified_by_status() {
+ // Only genuinely transient statuses may invite a retry — a retried
+ // create is not idempotent.
+ let parsed = error_from_response(StatusCode::SERVICE_UNAVAILABLE, None);
+ assert!(matches!(parsed, CalendarMutationError::Retryable(_)));
+ let parsed = error_from_response(StatusCode::TOO_MANY_REQUESTS, None);
+ assert!(matches!(parsed, CalendarMutationError::Retryable(_)));
+
+ let parsed = error_from_response(StatusCode::NOT_FOUND, Some("not found".to_string()));
+ assert!(matches!(parsed, CalendarMutationError::NotFound));
+ let parsed = error_from_response(StatusCode::BAD_REQUEST, Some("nope".to_string()));
+ assert!(matches!(parsed, CalendarMutationError::InvalidInput(_)));
+ let parsed = error_from_response(
+ StatusCode::FORBIDDEN,
+ Some(r#"{"code":"mystery","message":"no"}"#.to_string()),
+ );
+ assert!(matches!(parsed, CalendarMutationError::InvalidInput(_)));
+ let parsed = error_from_response(
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Some(r#"{"code":"mystery","message":"no"}"#.to_string()),
+ );
+ assert!(matches!(parsed, CalendarMutationError::Retryable(_)));
+}
diff --git a/crates/calendar_events/src/outbound/mod.rs b/crates/calendar_events/src/outbound/mod.rs
index 2888066bd8..2874f96d3d 100644
--- a/crates/calendar_events/src/outbound/mod.rs
+++ b/crates/calendar_events/src/outbound/mod.rs
@@ -1,5 +1,8 @@
//! Outbound calendar adapters.
+/// Email-service HTTP adapter for the mutation port.
+#[cfg(feature = "mutation-client")]
+pub mod email_service_mutations;
/// Google Calendar API adapter.
#[cfg(feature = "google")]
pub mod google;
diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rs
index 4349dd6f24..5ce3f72167 100644
--- a/services/document_cognition_service/src/api/context/test.rs
+++ b/services/document_cognition_service/src/api/context/test.rs
@@ -362,6 +362,11 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
properties_tool_context: properties_tool_context.clone(),
email_tool_context: email_tool_context.clone(),
call_tool_context: call_tool_context.clone(),
+ calendar_tool_context: ai_tools::build_calendar_tool_context(
+ pool.clone(),
+ "http://localhost:0".to_string(),
+ "test-internal-api-key".to_string(),
+ ),
notification_tool_context: notification_tool_context.clone(),
import_tool_context: ai_tools::ToolImportToolContext::unwired(),
chat_tool_context,
diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rs
index d3774b34b1..b330c5ce61 100644
--- a/services/document_cognition_service/src/main.rs
+++ b/services/document_cognition_service/src/main.rs
@@ -555,6 +555,11 @@ async fn main() -> anyhow::Result<()> {
properties_tool_context: properties_tool_context.clone(),
email_tool_context: email_tool_context.clone(),
call_tool_context: call_tool_context.clone(),
+ calendar_tool_context: ai_tools::build_calendar_tool_context(
+ db.clone(),
+ EmailServiceUrl::new()?.to_string(),
+ internal_api_key.clone(),
+ ),
notification_tool_context: notification_tool_context.clone(),
import_tool_context: import::inbound::toolset::ImportToolContext::wired(
import_service.clone(),
diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rs
index eade952f99..4a06c22f40 100644
--- a/services/mcp_service/src/context.rs
+++ b/services/mcp_service/src/context.rs
@@ -376,6 +376,11 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To
properties_tool_context,
email_tool_context,
call_tool_context,
+ calendar_tool_context: ai_tools::build_calendar_tool_context(
+ db.clone(),
+ email_service_client.url().to_owned(),
+ config.internal_api_key.to_string(),
+ ),
notification_tool_context,
import_tool_context: ToolImportToolContext::unwired(),
chat_tool_context,