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): let the agent read a mentioned calendar event (#8703)

gbirman4ffdaf520816
diff --git a/apps/docs/AI/mcp/tools/index.mdx b/apps/docs/AI/mcp/tools/index.mdx
index 16b2d16a66..24456e8034 100644
--- a/apps/docs/AI/mcp/tools/index.mdx
+++ b/apps/docs/AI/mcp/tools/index.mdx
@@ -116,6 +116,7 @@ These pages are generated from Macro's Rust MCP tool registry.
- [ReadAgentSession](/AI/mcp/tools/read-agent-session)
- [ReadAgentSessionSharing](/AI/mcp/tools/read-agent-session-sharing)
- [ReadBookingSettings](/AI/mcp/tools/read-booking-settings)
+- [ReadCalendarEvent](/AI/mcp/tools/read-calendar-event)
- [ReadCallRecord](/AI/mcp/tools/read-call-record)
- [ReadCanvas](/AI/mcp/tools/read-canvas)
- [ReadChannelMessageContext](/AI/mcp/tools/read-channel-message-context)
diff --git a/apps/docs/AI/mcp/tools/read-calendar-event.mdx b/apps/docs/AI/mcp/tools/read-calendar-event.mdx
new file mode 100644
index 0000000000..91c8fc5bc1
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/read-calendar-event.mdx
@@ -0,0 +1,20 @@
+---
+title: ReadCalendarEvent
+description: >-
+ Read one calendar event by id: the `documentId` of a calendar event mention
+ (`blockName` `calendar`) in a message, document, or email, or an `eventId` a
+ calendar tool returned.
+---
+
+# ReadCalendarEvent
+
+Read one calendar event by id: the `documentId` of a calendar event mention (`blockName` `calendar`) in a message, document, or email, or an `eventId` a calendar tool returned. Returns what the mention's preview card shows: title, time, location, description (truncated), organizer, guest count, and whether it repeats. ReadContent and ReadMetadata read documents only; use this tool for calendar events.
+
+`access` says how the user holds the meeting, as the card does. `on_your_calendar`: their own event (they organize it, or a delegated inbox holds it). `invited`: they are a guest. `snapshot`: a private copy they added of a shared meeting, which doesn't follow the organizer's changes and where an answer or a new guest would never reach the meeting. In these three, `eventId` is the user's copy for UpdateCalendarEvent and DeleteCalendarEvent. `shared_with_you`: someone shared their copy with a channel the user belongs to and the meeting is on none of the user's calendars. The event is then read-only for the user; AddSharedCalendarEvent adds a snapshot of it, and `canRequestToJoin` and `joinRequestStatus` say whether they can ask the person who shared it to add them as a guest, which they do from the event's card. To read one instance of a recurring event, pass the mention's `occurrenceKey` block param.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `eventId` | string | Yes | Calendar event id: a calendar mention's documentId, or an eventId from a calendar tool. |
+| `occurrenceKey` | string | No | Occurrence to read for a recurring event: the mention's occurrenceKey block param, or a recurrenceId from ListCalendarEvents. Omit to read the next upcoming instance, else the latest past one, else the series start. |
diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.json
index 7deb90a4c3..e28b2b3923 100644
--- a/apps/docs/config/tool-pages.json
+++ b/apps/docs/config/tool-pages.json
@@ -107,6 +107,7 @@
"AI/mcp/tools/read-agent-session",
"AI/mcp/tools/read-agent-session-sharing",
"AI/mcp/tools/read-booking-settings",
+ "AI/mcp/tools/read-calendar-event",
"AI/mcp/tools/read-call-record",
"AI/mcp/tools/read-canvas",
"AI/mcp/tools/read-channel-message-context",
diff --git a/apps/docs/docs.json b/apps/docs/docs.json
index fc147158bc..38f2d46332 100644
--- a/apps/docs/docs.json
+++ b/apps/docs/docs.json
@@ -211,6 +211,7 @@
"AI/mcp/tools/read-agent-session",
"AI/mcp/tools/read-agent-session-sharing",
"AI/mcp/tools/read-booking-settings",
+ "AI/mcp/tools/read-calendar-event",
"AI/mcp/tools/read-call-record",
"AI/mcp/tools/read-canvas",
"AI/mcp/tools/read-channel-message-context",
diff --git a/apps/docs/product/calendar.mdx b/apps/docs/product/calendar.mdx
index c9518f83e8..8411990030 100644
--- a/apps/docs/product/calendar.mdx
+++ b/apps/docs/product/calendar.mdx
@@ -68,6 +68,7 @@ You can use the same tools over Macro's MCP server:
- [`ListCalendars`](/AI/mcp/tools/list-calendars)
- [`ListCalendarEvents`](/AI/mcp/tools/list-calendar-events)
+- [`ReadCalendarEvent`](/AI/mcp/tools/read-calendar-event)
- [`CreateCalendarEvent`](/AI/mcp/tools/create-calendar-event)
- [`UpdateCalendarEvent`](/AI/mcp/tools/update-calendar-event)
- [`DeleteCalendarEvent`](/AI/mcp/tools/delete-calendar-event)
diff --git a/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx b/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx
index e15f2d3b0b..5a8ec23238 100644
--- a/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx
+++ b/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx
@@ -220,6 +220,7 @@ function MacroToolIcon(props: { name: string }): JSX.Element {
'ReadPhotoshopDocument',
'ReadIllustratorDocument',
'ReadWordDocument',
+ 'ReadCalendarEvent',
() => <ReadIcon class="size-4" />
)
.with('WebFetch', () => <GlobeIcon class="size-4" />)
diff --git a/apps/web/src/features/block-agent/state/tool-approval-wording.ts b/apps/web/src/features/block-agent/state/tool-approval-wording.ts
index a067ba2df9..ce29465d6e 100644
--- a/apps/web/src/features/block-agent/state/tool-approval-wording.ts
+++ b/apps/web/src/features/block-agent/state/tool-approval-wording.ts
@@ -126,6 +126,7 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {
ReactToChannelMessage: (whose) => `react to messages from ${whose} account`,
ReadActivity: (whose) => `read ${whose} recent activity`,
ReadBookingSettings: (whose) => `read ${whose} booking settings`,
+ ReadCalendarEvent: (whose) => `read ${whose} calendar`,
ReadCallRecord: (whose) => `read ${whose} call recordings`,
ReadChannelMessageContext: (whose) => `read ${whose} channel messages`,
ReadChannelMessages: (whose) => `read ${whose} channel messages`,
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
index e17863640a..fb17547074 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/CalendarTools.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/CalendarTools.tsx
@@ -5,6 +5,7 @@ import CalendarPlus from '@phosphor-icons/core/regular/calendar-plus.svg';
import CalendarX from '@phosphor-icons/core/regular/calendar-x.svg';
import VideoCamera from '@phosphor-icons/core/regular/video-camera.svg';
import type { NamedTool } from '@service-cognition/generated/tools/tool';
+import { Tooltip } from '@ui';
import { format, isSameDay, subDays } from 'date-fns';
import { createSignal, For, Match, Show, Switch } from 'solid-js';
import { BaseTool } from './BaseTool';
@@ -301,6 +302,26 @@ export const deleteCalendarEventHandler = createToolRenderer({
),
});
+export const readCalendarEventHandler = createToolRenderer({
+ name: 'ReadCalendarEvent',
+ render: (ctx) => (
+ <BaseTool icon={CalendarDots} 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">Read calendar event</span>
+ <Show when={ctx.response?.data}>
+ {(event) => (
+ <Tooltip label={event().title} as="span" class="min-w-0">
+ <span class="min-w-0 truncate text-xs text-ink-extra-muted">
+ {event().title}
+ </span>
+ </Tooltip>
+ )}
+ </Show>
+ </div>
+ </BaseTool>
+ ),
+});
+
const ListEventsResponse = (props: { events: CalendarEventListItem[] }) => (
<Tool.List>
<For each={props.events}>
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 f6082a8c81..608b1660ae 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
@@ -51,6 +51,7 @@ import {
deleteCalendarEventHandler,
listCalendarEventsHandler,
listCalendarsHandler,
+ readCalendarEventHandler,
updateCalendarEventHandler,
} from './CalendarTools';
import {
@@ -251,6 +252,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
AddSharedCalendarEvent: addSharedCalendarEventHandler,
ListCalendarEvents: listCalendarEventsHandler,
ListCalendars: listCalendarsHandler,
+ ReadCalendarEvent: readCalendarEventHandler,
GetTeamAvailability: getTeamAvailabilityHandler,
CreateImportEntity: createImportEntityHandler,
DeleteImportEntity: deleteImportEntityHandler,
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 d74d57f305..bff4666a06 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
@@ -12004,6 +12004,79 @@ export const BookingSettingsResult = z.object({
pageUrl: z.string(),
});
+export const ReadCalendarEvent = z.object({
+ eventId: z.string().uuid(),
+ occurrenceKey: z.union([z.string(), z.null()]).optional(),
+});
+
+export const ReadCalendarEventResponse = z.object({
+ access: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('on_your_calendar'),
+ z.literal('invited'),
+ z.literal('snapshot'),
+ z.literal('shared_with_you'),
+ ];
+ 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',
+ });
+ }
+ }),
+ eventId: z.union([z.string().uuid(), z.null()]).optional(),
+ title: z.string(),
+ start: z.string(),
+ end: z.string(),
+ isAllDay: z.boolean(),
+ timeZone: z.union([z.string(), z.null()]).optional(),
+ isRecurring: z.boolean(),
+ recurrenceId: z.union([z.string(), z.null()]).optional(),
+ location: z.union([z.string(), z.null()]).optional(),
+ description: z.union([z.string(), z.null()]).optional(),
+ organizerEmail: z.union([z.string(), z.null()]).optional(),
+ organizerName: z.union([z.string(), z.null()]).optional(),
+ attendeeCount: z.number().int().gte(0),
+ canRequestToJoin: z.boolean(),
+ joinRequestStatus: z
+ .union([
+ z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('pending'),
+ z.literal('accepted'),
+ z.literal('declined'),
+ ];
+ 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(),
+ summary: z.string(),
+});
+
export const ReadCallRecord = z.object({ callId: z.string().uuid() });
export const ReadCallRecordResponse = z.object({
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 33df89cf16..9eae5a16f8 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
@@ -367,6 +367,10 @@ type ToolParserMap = {
call: types.ReadBookingSettings;
response: types.BookingSettingsResult;
};
+ ReadCalendarEvent: {
+ call: types.ReadCalendarEvent;
+ response: types.ReadCalendarEventResponse;
+ };
ReadCallRecord: {
call: types.ReadCallRecord;
response: types.ReadCallRecordResponse;
@@ -932,6 +936,10 @@ const toolParserMap = {
call: schemas.ReadBookingSettings,
response: schemas.BookingSettingsResult,
},
+ ReadCalendarEvent: {
+ call: schemas.ReadCalendarEvent,
+ response: schemas.ReadCalendarEventResponse,
+ },
ReadCallRecord: {
call: schemas.ReadCallRecord,
response: schemas.ReadCallRecordResponse,
@@ -1493,6 +1501,10 @@ type ToolDataMap = {
call: types.ReadBookingSettings;
response: types.BookingSettingsResult;
};
+ ReadCalendarEvent: {
+ call: types.ReadCalendarEvent;
+ response: types.ReadCalendarEventResponse;
+ };
ReadCallRecord: {
call: types.ReadCallRecord;
response: types.ReadCallRecordResponse;
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 af57e9f563..f7538b94ce 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
@@ -4256,6 +4256,18 @@ export type SessionLinkScope = 'off' | 'public' | 'team';
* Ordered from least to most access top -> bottom
*/
export type AccessLevel = 'view' | 'comment' | 'edit' | 'owner';
+/**
+ * How the user holds the event, as its mention card says.
+ */
+export type CalendarEventAccess =
+ | 'on_your_calendar'
+ | 'invited'
+ | 'snapshot'
+ | 'shared_with_you';
+/**
+ * Lifecycle of a request to be added as a guest of a shared event.
+ */
+export type CalendarJoinRequestStatus = 'pending' | 'accepted' | 'declined';
/**
* Scene representation requested by a reader.
*/
@@ -13144,6 +13156,98 @@ export interface EventType {
*/
questions: Question[];
}
+/**
+ * Read one calendar event by id: the `documentId` of a calendar event mention (`blockName` `calendar`) in a message, document, or email, or an `eventId` a calendar tool returned. Returns what the mention's preview card shows: title, time, location, description (truncated), organizer, guest count, and whether it repeats. ReadContent and ReadMetadata read documents only; use this tool for calendar events.
+ *
+ * `access` says how the user holds the meeting, as the card does. `on_your_calendar`: their own event (they organize it, or a delegated inbox holds it). `invited`: they are a guest. `snapshot`: a private copy they added of a shared meeting, which doesn't follow the organizer's changes and where an answer or a new guest would never reach the meeting. In these three, `eventId` is the user's copy for UpdateCalendarEvent and DeleteCalendarEvent. `shared_with_you`: someone shared their copy with a channel the user belongs to and the meeting is on none of the user's calendars. The event is then read-only for the user; AddSharedCalendarEvent adds a snapshot of it, and `canRequestToJoin` and `joinRequestStatus` say whether they can ask the person who shared it to add them as a guest, which they do from the event's card. To read one instance of a recurring event, pass the mention's `occurrenceKey` block param.
+ */
+export interface ReadCalendarEvent {
+ /**
+ * Calendar event id: a calendar mention's documentId, or an eventId from a calendar tool.
+ */
+ eventId: string;
+ /**
+ * Occurrence to read for a recurring event: the mention's occurrenceKey block param, or a recurrenceId from ListCalendarEvents. Omit to read the next upcoming instance, else the latest past one, else the series start.
+ */
+ occurrenceKey?: string | null;
+}
+/**
+ * One calendar event, with the fields its mention preview card shows.
+ */
+export interface ReadCalendarEventResponse {
+ access: CalendarEventAccess;
+ /**
+ * The user's own copy of the meeting, for UpdateCalendarEvent and
+ * DeleteCalendarEvent. It can differ from the id that was read, and is
+ * absent for an event that is only shared with the user.
+ */
+ eventId?: string | null;
+ /**
+ * Display title.
+ */
+ title: string;
+ /**
+ * Start of the instance read: RFC 3339 UTC instant, or YYYY-MM-DD for
+ * all-day events.
+ */
+ start: string;
+ /**
+ * Exclusive end: RFC 3339 UTC instant, or YYYY-MM-DD for all-day events.
+ */
+ end: string;
+ /**
+ * Whether the event covers whole days.
+ */
+ isAllDay: boolean;
+ /**
+ * IANA time zone the event was scheduled in, when known.
+ */
+ timeZone?: string | null;
+ /**
+ * Whether the event repeats.
+ */
+ isRecurring: boolean;
+ /**
+ * Key of the instance read: the requested occurrence when it exists,
+ * otherwise the next upcoming one, else the latest past one, else the
+ * series start.
+ */
+ recurrenceId?: string | null;
+ /**
+ * Location label, when set.
+ */
+ location?: string | null;
+ /**
+ * Event body, truncated for brevity.
+ */
+ description?: string | null;
+ /**
+ * Organizer email address, when known.
+ */
+ organizerEmail?: string | null;
+ /**
+ * Organizer display name, when known.
+ */
+ organizerName?: string | null;
+ /**
+ * Number of guests on the event.
+ */
+ attendeeCount: number;
+ /**
+ * For an event shared with the user, whether the person who shared it
+ * can add them as a guest. Always false for an event on their calendar.
+ */
+ canRequestToJoin: boolean;
+ /**
+ * For an event shared with the user, their request to join it, if they
+ * made one.
+ */
+ joinRequestStatus?: CalendarJoinRequestStatus | null;
+ /**
+ * A human-readable summary of the event.
+ */
+ summary: string;
+}
/**
* Retrieve the transcript for a specific call record. Use ListEntities with includeTypes: ["call"] first to find the callId. Only the transcript is returned — other metadata (participants, duration, etc.) is already available from ListEntities. In transcript segments, speakerId is the associated user/track, not guaranteed speaker identity; use diarizedSpeakerId to distinguish actual voices, and treat different diarizedSpeakerIds as potentially different speakers even if speakerId is the caller/"you".
*/
diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.md
index 59c2c37ce8..822dd42695 100644
--- a/crates/calendar_events/AGENTS.md
+++ b/crates/calendar_events/AGENTS.md
@@ -131,6 +131,11 @@ reminder dispatch, team availability, and provider/Postgres persistence.
`copy_shared_event` refuses with `JoinRequestOpen`: the answer is an
invitation under the meeting's UID, which a snapshot imported meanwhile
would take in. A declined requester may still add a copy.
+- Calendar mentions reach the agent as document mentions (`blockName`
+ `calendar`), but `ReadContent` and `ReadMetadata` need document access, which
+ a channel-shared event never grants. The agent reads a mentioned event with
+ `ReadCalendarEvent` (`src/inbound/toolset/read_calendar_event.rs`), which goes
+ through `mention_previews`: the hover card's visibility and fields.
- `viewer_can` is viewer-relative, like an attendee's `is_self`: resolve it with
`ActorInboxes::mark_event` and the copy's source link wherever a read path
marks the viewer, and never store it. Each connected inbox gets its own copy
diff --git a/crates/calendar_events/src/domain/join_requests.rs b/crates/calendar_events/src/domain/join_requests.rs
index f031332aab..886689acd9 100644
--- a/crates/calendar_events/src/domain/join_requests.rs
+++ b/crates/calendar_events/src/domain/join_requests.rs
@@ -25,6 +25,7 @@ use super::{
/// Lifecycle of a request to be added as a guest of a shared event.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum CalendarJoinRequestStatus {
/// Waiting on the person who shared the event.
diff --git a/crates/calendar_events/src/inbound/toolset.rs b/crates/calendar_events/src/inbound/toolset.rs
index 63d5a60235..81c69653ba 100644
--- a/crates/calendar_events/src/inbound/toolset.rs
+++ b/crates/calendar_events/src/inbound/toolset.rs
@@ -11,6 +11,7 @@ mod create_confirmed_calendar_event;
mod delete_calendar_event;
mod list_calendar_events;
mod list_calendars;
+mod read_calendar_event;
mod update_calendar_event;
#[cfg(test)]
@@ -48,6 +49,7 @@ pub use list_calendar_events::{
CalendarEventListItem, ListCalendarEvents, ListCalendarEventsResponse,
};
pub use list_calendars::{ListCalendars, ListCalendarsToolResponse, ToolCalendar};
+pub use read_calendar_event::{CalendarEventAccess, ReadCalendarEvent, ReadCalendarEventResponse};
pub use update_calendar_event::{
ConferenceChangeInput, RsvpResponseInput, UpdateCalendarEvent, UpdateScopeInput,
};
@@ -122,6 +124,7 @@ where
AsyncToolCollection::new()
.add_tool::<ListCalendarEvents, CalendarToolContext<M, O, L>>()
.add_tool::<ListCalendars, CalendarToolContext<M, O, L>>()
+ .add_tool::<ReadCalendarEvent, CalendarToolContext<M, O, L>>()
.add_tool::<UpdateCalendarEvent, CalendarToolContext<M, O, L>>()
.add_tool::<DeleteCalendarEvent, CalendarToolContext<M, O, L>>()
.add_tool::<AddSharedCalendarEvent, CalendarToolContext<M, O, L>>()
diff --git a/crates/calendar_events/src/inbound/toolset/read_calendar_event.rs b/crates/calendar_events/src/inbound/toolset/read_calendar_event.rs
new file mode 100644
index 0000000000..6488d0c2ae
--- /dev/null
+++ b/crates/calendar_events/src/inbound/toolset/read_calendar_event.rs
@@ -0,0 +1,241 @@
+//! ReadCalendarEvent tool for reading one event by id, such as a mentioned
+//! one, with the same visibility and fields as its mention preview card.
+
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,
+ ToolResult,
+};
+use async_trait::async_trait;
+use rootcause::compat::boxed_error::IntoBoxedError;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::{CalendarToolContext, description_preview, time_fields};
+use crate::domain::{
+ join_requests::CalendarJoinRequestStatus,
+ models::{
+ CalendarMentionEvent, CalendarMentionPreview, CalendarMentionRequestItem,
+ CalendarMentionViewerCopy,
+ },
+ ports::{CalendarMutationService, CalendarOccurrenceService, MeetingLinkProvider},
+};
+
+/// How the user holds the event, as its mention card says.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum CalendarEventAccess {
+ /// The meeting is on one of the user's calendars as their own: they
+ /// organize it, or it sits in a delegated inbox. `eventId` is that copy.
+ OnYourCalendar,
+ /// The user is a guest on the meeting; `eventId` is their copy.
+ Invited,
+ /// The user added a snapshot of a shared meeting: a private copy that
+ /// doesn't follow the organizer's changes, where an answer or a new guest
+ /// would never reach the meeting. `eventId` is the snapshot.
+ Snapshot,
+ /// Someone shared their copy with a channel the user belongs to and the
+ /// meeting is on none of the user's calendars: read-only, with no copy
+ /// of the user's to change.
+ SharedWithYou,
+}
+
+impl CalendarEventAccess {
+ fn of(event: &CalendarMentionEvent) -> Self {
+ match (event.viewer_event_id, event.viewer_copy) {
+ (None, _) => Self::SharedWithYou,
+ (Some(_), Some(CalendarMentionViewerCopy::Snapshot)) => Self::Snapshot,
+ (Some(_), Some(CalendarMentionViewerCopy::Invitation)) => Self::Invited,
+ (Some(_), Some(CalendarMentionViewerCopy::Event) | None) => Self::OnYourCalendar,
+ }
+ }
+}
+
+/// One calendar event, with the fields its mention preview card shows.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ReadCalendarEventResponse {
+ /// How the user holds the event: on their calendar, invited, as a
+ /// snapshot, or only shared with them.
+ pub access: CalendarEventAccess,
+ /// The user's own copy of the meeting, for UpdateCalendarEvent and
+ /// DeleteCalendarEvent. It can differ from the id that was read, and is
+ /// absent for an event that is only shared with the user.
+ pub event_id: Option<Uuid>,
+ /// Display title.
+ pub title: String,
+ /// Start of the instance read: RFC 3339 UTC instant, or YYYY-MM-DD for
+ /// all-day events.
+ pub start: String,
+ /// Exclusive 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>,
+ /// Whether the event repeats.
+ pub is_recurring: bool,
+ /// Key of the instance read: the requested occurrence when it exists,
+ /// otherwise the next upcoming one, else the latest past one, else the
+ /// series start.
+ pub recurrence_id: Option<String>,
+ /// Location label, when set.
+ pub location: Option<String>,
+ /// Event body, truncated for brevity.
+ pub description: Option<String>,
+ /// Organizer email address, when known.
+ pub organizer_email: Option<String>,
+ /// Organizer display name, when known.
+ pub organizer_name: Option<String>,
+ /// Number of guests on the event.
+ pub attendee_count: usize,
+ /// For an event shared with the user, whether the person who shared it
+ /// can add them as a guest. Always false for an event on their calendar.
+ pub can_request_to_join: bool,
+ /// For an event shared with the user, their request to join it, if they
+ /// made one.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub join_request_status: Option<CalendarJoinRequestStatus>,
+ /// A human-readable summary of the event.
+ pub summary: String,
+}
+
+impl ReadCalendarEventResponse {
+ fn from_preview(event: CalendarMentionEvent) -> Self {
+ let access = CalendarEventAccess::of(&event);
+ let (start, end, is_all_day, time_zone) = time_fields(&event.time);
+ let summary = match access {
+ CalendarEventAccess::OnYourCalendar => {
+ format!("{} is on the user's calendar.", event.title)
+ }
+ CalendarEventAccess::Invited => {
+ format!(
+ "The user is invited to {}; it is on their calendar.",
+ event.title
+ )
+ }
+ CalendarEventAccess::Snapshot => format!(
+ "The user's calendar has a snapshot of {}: their own copy of a shared meeting, \
+ which doesn't follow the organizer's changes.",
+ event.title
+ ),
+ CalendarEventAccess::SharedWithYou => format!(
+ "{} was shared with a channel the user belongs to and is not on their calendar.",
+ event.title
+ ),
+ };
+ Self {
+ access,
+ event_id: event.viewer_event_id,
+ title: event.title,
+ start,
+ end,
+ is_all_day,
+ time_zone,
+ is_recurring: event.is_recurring,
+ recurrence_id: event.occurrence_key,
+ location: event.location,
+ description: description_preview(event.description.as_deref()),
+ organizer_email: event.organizer_email,
+ organizer_name: event.organizer_name,
+ attendee_count: event.attendee_count,
+ can_request_to_join: event.can_request_to_join,
+ join_request_status: event.join_request_status,
+ summary,
+ }
+ }
+}
+
+/// Read one calendar event by id.
+#[derive(Debug, Deserialize, JsonSchema, Clone)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "ReadCalendarEvent",
+ description = "\
+Read one calendar event by id: the `documentId` of a calendar event mention (`blockName` \
+`calendar`) in a message, document, or email, or an `eventId` a calendar tool returned. \
+Returns what the mention's preview card shows: title, time, location, description \
+(truncated), organizer, guest count, and whether it repeats. ReadContent and ReadMetadata \
+read documents only; use this tool for calendar events.\n\
+\n\
+`access` says how the user holds the meeting, as the card does. `on_your_calendar`: their own \
+event (they organize it, or a delegated inbox holds it). `invited`: they are a guest. \
+`snapshot`: a private copy they added of a shared meeting, which doesn't follow the organizer's \
+changes and where an answer or a new guest would never reach the meeting. In these three, \
+`eventId` is the user's copy for UpdateCalendarEvent and DeleteCalendarEvent. \
+`shared_with_you`: someone shared their copy with a channel the user belongs to and the meeting \
+is on none of the user's calendars. The event is then read-only for the user; \
+AddSharedCalendarEvent adds a snapshot of it, and `canRequestToJoin` and `joinRequestStatus` say \
+whether they can ask the person who shared it to add them as a guest, which they do from the \
+event's card. To read one instance of a recurring event, pass the mention's `occurrenceKey` \
+block param."
+)]
+pub struct ReadCalendarEvent {
+ /// Calendar event id.
+ #[schemars(
+ description = "Calendar event id: a calendar mention's documentId, or an eventId from a calendar tool."
+ )]
+ pub event_id: Uuid,
+ /// Occurrence of a recurring event to read.
+ #[schemars(
+ description = "Occurrence to read for a recurring event: the mention's occurrenceKey block param, or a recurrenceId from ListCalendarEvents. Omit to read the next upcoming instance, else the latest past one, else the series start."
+ )]
+ pub occurrence_key: Option<String>,
+}
+
+impl ToolAnnotated for ReadCalendarEvent {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Read calendar event");
+}
+
+#[async_trait]
+impl<M, O, L> AsyncTool<CalendarToolContext<M, O, L>> for ReadCalendarEvent
+where
+ M: CalendarMutationService,
+ O: CalendarOccurrenceService,
+ L: MeetingLinkProvider,
+{
+ type Output = ReadCalendarEventResponse;
+
+ #[tracing::instrument(skip_all, fields(event_id=%self.event_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<CalendarToolContext<M, O, L>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let requester_id = request_context.user_id.to_string();
+ let previews = service_context
+ .occurrences
+ .mention_previews(
+ &requester_id,
+ vec![CalendarMentionRequestItem {
+ event_id: self.event_id,
+ occurrence_key: self.occurrence_key.clone(),
+ }],
+ )
+ .await
+ .map_err(|error| ToolCallError {
+ description: "Failed to read the calendar event. Try again shortly.".to_string(),
+ internal_error: anyhow::Error::from_boxed(error.into_boxed_error()),
+ })?;
+ match previews.into_iter().next() {
+ Some(CalendarMentionPreview::Accessible(event)) => {
+ Ok(ReadCalendarEventResponse::from_preview(*event))
+ }
+ Some(CalendarMentionPreview::NoAccess) => Err(not_readable(
+ "The calendar event is not on any of the user's calendars and was not shared \
+ with a channel they belong to, so they cannot see it.",
+ )),
+ Some(CalendarMentionPreview::DoesNotExist) | None => Err(not_readable(
+ "The calendar event no longer exists: it was deleted or cancelled, or the id is \
+ not a calendar event.",
+ )),
+ }
+ }
+}
+
+fn not_readable(description: &str) -> ToolCallError {
+ ToolCallError {
+ description: description.to_string(),
+ internal_error: anyhow::anyhow!(description.to_string()),
+ }
+}
diff --git a/crates/calendar_events/src/inbound/toolset/test.rs b/crates/calendar_events/src/inbound/toolset/test.rs
index 9d3d5b78e1..b2dfa49ecd 100644
--- a/crates/calendar_events/src/inbound/toolset/test.rs
+++ b/crates/calendar_events/src/inbound/toolset/test.rs
@@ -1,4 +1,5 @@
mod add_shared_calendar_event;
+mod read_calendar_event;
use std::sync::Mutex;
@@ -32,6 +33,10 @@ fn tool_input_schemas_satisfy_strict_mode() {
"ListCalendars",
generate_validated_input_schema::<ListCalendars>().map(|schema| schema.name),
),
+ (
+ "ReadCalendarEvent",
+ generate_validated_input_schema::<ReadCalendarEvent>().map(|schema| schema.name),
+ ),
(
"CreateCalendarEvent",
generate_validated_input_schema::<CreateCalendarEvent>().map(|schema| schema.name),
@@ -328,7 +333,7 @@ impl CalendarOccurrenceService for MockOccurrences {
_requester_id: &str,
_items: Vec<crate::domain::models::CalendarMentionRequestItem>,
) -> Result<Vec<crate::domain::models::CalendarMentionPreview>, rootcause::Report> {
- unreachable!("no calendar tool resolves mention previews")
+ unreachable!("these tests read no mentioned events")
}
async fn list_team_out_of_office(
diff --git a/crates/calendar_events/src/inbound/toolset/test/read_calendar_event.rs b/crates/calendar_events/src/inbound/toolset/test/read_calendar_event.rs
new file mode 100644
index 0000000000..5993d287b9
--- /dev/null
+++ b/crates/calendar_events/src/inbound/toolset/test/read_calendar_event.rs
@@ -0,0 +1,203 @@
+use super::*;
+use crate::domain::join_requests::CalendarJoinRequestStatus;
+use crate::domain::models::{
+ CalendarMentionEvent, CalendarMentionPreview, CalendarMentionRequestItem,
+ CalendarMentionViewerCopy, EventTime,
+};
+
+/// Resolves every mention to `preview` and records what was asked for.
+struct PreviewOccurrences {
+ preview: CalendarMentionPreview,
+ requested: Mutex<Vec<CalendarMentionRequestItem>>,
+}
+
+impl CalendarOccurrenceService for PreviewOccurrences {
+ async fn list_occurrences(
+ &self,
+ _requester_id: &str,
+ _range: OccurrenceRange,
+ _cursor: Option<crate::domain::models::CalendarOccurrenceCursor>,
+ _limit: u16,
+ ) -> Result<Vec<crate::domain::models::OccurrenceListing>, rootcause::Report> {
+ unreachable!("reading an event lists no occurrences")
+ }
+
+ async fn sync_status(
+ &self,
+ _requester_id: &str,
+ ) -> Result<CalendarSyncStatus, rootcause::Report> {
+ unreachable!("reading an event checks no sync status")
+ }
+
+ async fn list_visible_calendars(
+ &self,
+ _requester_id: &str,
+ ) -> Result<Vec<VisibleCalendar>, rootcause::Report> {
+ unreachable!("reading an event lists no calendars")
+ }
+
+ async fn mention_previews(
+ &self,
+ _requester_id: &str,
+ items: Vec<CalendarMentionRequestItem>,
+ ) -> Result<Vec<CalendarMentionPreview>, rootcause::Report> {
+ let previews = items.iter().map(|_| self.preview.clone()).collect();
+ self.requested.lock().unwrap().extend(items);
+ Ok(previews)
+ }
+
+ async fn list_team_out_of_office(
+ &self,
+ _requester_id: &str,
+ _range: OccurrenceRange,
+ _limit: u16,
+ ) -> Result<Vec<crate::domain::models::TeamOutOfOffice>, rootcause::Report> {
+ unreachable!("reading an event lists no team out-of-office")
+ }
+
+ async fn primary_time_zone(
+ &self,
+ _requester_id: &str,
+ ) -> Result<Option<String>, rootcause::Report> {
+ unreachable!("reading an event resolves no time zone")
+ }
+
+ async fn event_ics(
+ &self,
+ _requester_id: &str,
+ _event_id: Uuid,
+ ) -> Result<Option<crate::domain::ics::CalendarEventIcs>, rootcause::Report> {
+ unreachable!("reading an event exports nothing")
+ }
+}
+
+fn mention(viewer_event_id: Option<Uuid>) -> CalendarMentionEvent {
+ CalendarMentionEvent {
+ viewer_event_id,
+ viewer_copy: viewer_event_id.map(|_| CalendarMentionViewerCopy::Event),
+ title: "Design review".to_string(),
+ description: Some("Walk through the rollout.".to_string()),
+ time: EventTime::Timed {
+ starts_at: Utc.with_ymd_and_hms(2026, 10, 26, 14, 0, 0).unwrap(),
+ ends_at: Utc.with_ymd_and_hms(2026, 10, 26, 14, 30, 0).unwrap(),
+ time_zone: Some("America/New_York".to_string()),
+ },
+ occurrence_key: None,
+ is_recurring: false,
+ location: Some("Room 4".to_string()),
+ organizer_email: Some("[email protected]".to_string()),
+ organizer_name: Some("Organizer".to_string()),
+ attendee_count: 1,
+ updated_at: Utc.with_ymd_and_hms(2026, 10, 23, 12, 0, 0).unwrap(),
+ can_request_to_join: false,
+ join_request_status: None,
+ }
+}
+
+async fn read(
+ preview: CalendarMentionPreview,
+ args: serde_json::Value,
+) -> (
+ ai_toolset::ToolResult<serde_json::Value>,
+ Vec<CalendarMentionRequestItem>,
+) {
+ let occurrences = std::sync::Arc::new(PreviewOccurrences {
+ preview,
+ requested: Mutex::new(Vec::new()),
+ });
+ let context = CalendarToolContext::new(
+ std::sync::Arc::new(MockMutations::default()),
+ occurrences.clone(),
+ std::sync::Arc::new(MockMeetingLinks::default()),
+ );
+ let result = calendar_toolset()
+ .try_tool_call(context, request_context(), "ReadCalendarEvent", &args)
+ .await
+ .unwrap();
+ let requested = occurrences.requested.lock().unwrap().clone();
+ (result, requested)
+}
+
+#[tokio::test]
+async fn a_channel_shared_event_reads_as_shared_with_its_join_state() {
+ let shared = Uuid::from_u128(41);
+ let mut event = mention(None);
+ event.can_request_to_join = true;
+ event.join_request_status = Some(CalendarJoinRequestStatus::Pending);
+ event.occurrence_key = Some("2026-10-26T14:00:00+00:00".to_string());
+
+ let (result, requested) = read(
+ CalendarMentionPreview::Accessible(Box::new(event)),
+ serde_json::json!({
+ "eventId": shared,
+ "occurrenceKey": "2026-10-26T14:00:00+00:00",
+ }),
+ )
+ .await;
+
+ let read = result.unwrap();
+ assert_eq!(read["access"], "shared_with_you");
+ assert_eq!(read["eventId"], serde_json::Value::Null);
+ assert_eq!(read["title"], "Design review");
+ assert_eq!(read["start"], "2026-10-26T14:00:00+00:00");
+ assert_eq!(read["organizerEmail"], "[email protected]");
+ assert_eq!(read["attendeeCount"], 1);
+ assert_eq!(read["canRequestToJoin"], true);
+ assert_eq!(read["joinRequestStatus"], "pending");
+ assert_eq!(read["recurrenceId"], "2026-10-26T14:00:00+00:00");
+ assert_eq!(
+ requested,
+ vec![CalendarMentionRequestItem {
+ event_id: shared,
+ occurrence_key: Some("2026-10-26T14:00:00+00:00".to_string()),
+ }]
+ );
+}
+
+#[tokio::test]
+async fn an_event_on_the_users_calendar_reads_with_their_own_copy() {
+ let own_copy = Uuid::from_u128(42);
+
+ let (result, _) = read(
+ CalendarMentionPreview::Accessible(Box::new(mention(Some(own_copy)))),
+ serde_json::json!({ "eventId": Uuid::from_u128(43), "occurrenceKey": null }),
+ )
+ .await;
+
+ let read = result.unwrap();
+ assert_eq!(read["access"], "on_your_calendar");
+ assert_eq!(read["eventId"], own_copy.to_string());
+ assert!(read.get("joinRequestStatus").is_none());
+}
+
+#[tokio::test]
+async fn a_copy_reads_the_way_the_card_names_it() {
+ for (copy, access) in [
+ (CalendarMentionViewerCopy::Invitation, "invited"),
+ (CalendarMentionViewerCopy::Snapshot, "snapshot"),
+ ] {
+ let mut event = mention(Some(Uuid::from_u128(45)));
+ event.viewer_copy = Some(copy);
+
+ let (result, _) = read(
+ CalendarMentionPreview::Accessible(Box::new(event)),
+ serde_json::json!({ "eventId": Uuid::from_u128(46), "occurrenceKey": null }),
+ )
+ .await;
+
+ let read = result.unwrap();
+ assert_eq!(read["access"], access);
+ assert_eq!(read["eventId"], Uuid::from_u128(45).to_string());
+ }
+}
+
+#[tokio::test]
+async fn an_unreadable_event_says_why() {
+ let args = serde_json::json!({ "eventId": Uuid::from_u128(44), "occurrenceKey": null });
+
+ let (hidden, _) = read(CalendarMentionPreview::NoAccess, args.clone()).await;
+ let (gone, _) = read(CalendarMentionPreview::DoesNotExist, args).await;
+
+ assert!(hidden.unwrap_err().description.contains("cannot see it"));
+ assert!(gone.unwrap_err().description.contains("no longer exists"));
+}
diff --git a/crates/prompt/src/mentions.rs b/crates/prompt/src/mentions.rs
index f4297dd89b..87b2bcbb74 100644
--- a/crates/prompt/src/mentions.rs
+++ b/crates/prompt/src/mentions.rs
@@ -51,7 +51,7 @@ The `blockName` for a form is always exactly `form` — never `md` or `document`
The `blockName` for a project is always exactly `initiative`, with the initiative id from an initiative tool result (such as ListInitiatives or ReadInitiative); `project` is a folder.
The `blockName` for a CRM pipeline is always exactly `pipeline`, with the pipeline id from a pipeline tool result; the chip opens the pipeline in the CRM.
The `blockName` for an email thread is always exactly `email` — never `thread` or `email_thread`, which the frontend cannot resolve.
-The `blockName` for a calendar event is always exactly `calendar` — never `calendar_event`, which the frontend cannot resolve. `documentId` is the `eventId` a calendar tool returned. To point at one instance of a recurring event, pass that occurrence's `recurrenceId` from ListCalendarEvents as the `occurrenceKey` block param; otherwise omit it and the mention previews the nearest instance. A calendar event mention opens for people who have that event on their own calendar. After it is shared with a channel, current members who do not have a copy see a read-only preview instead. Private and confidential events are never shared.
+The `blockName` for a calendar event is always exactly `calendar` — never `calendar_event`, which the frontend cannot resolve. `documentId` is the `eventId` a calendar tool returned. To point at one instance of a recurring event, pass that occurrence's `recurrenceId` from ListCalendarEvents as the `occurrenceKey` block param; otherwise omit it and the mention previews the nearest instance. A calendar event mention opens for people who have that event on their own calendar. After it is shared with a channel, current members who do not have a copy see a read-only preview instead. Private and confidential events are never shared. To read a calendar event mention you receive, call ReadCalendarEvent with its `documentId` (and its `occurrenceKey` when present); ReadContent and ReadMetadata read documents only.
When a tool returns both a channel id and a channel message id, link the specific message using the channel message mention format. Do not link only the channel unless you are referring to the whole channel.
### People, groups, dates, agent sessions, pull requests, and booking links
diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.md
index c56c390987..6703c519dc 100644
--- a/docs/agent-guide/calendar.md
+++ b/docs/agent-guide/calendar.md
@@ -731,7 +731,9 @@ adds the event or is invited, and switches to that line and `Open` in place. Ope
sheet (`Open`, the title, or Open in New Split) closes it, since the native apps keep the
pane behind the opened one mounted. When Calendar opens on an event its loaded week doesn't
have yet, such as a copy added a moment ago while Calendar was closed, it syncs once and then
-shows the event's details.
+shows the event's details. The agent reads a mentioned event, including one only shared with
+the viewer, with `ReadCalendarEvent`: the same fields, plus how the viewer holds it (their own,
+invited, a snapshot, or only shared with them) and their join request.
## Scheduling — `/app/scheduling`