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(teams): ai teams tool (#3380)

Will Hutchinsond088a97c40b0
diff --git a/js/app/packages/core/component/AI/component/tool/ListTeamMembers.tsx b/js/app/packages/core/component/AI/component/tool/ListTeamMembers.tsx
new file mode 100644
index 0000000000..7a8884b9db
--- /dev/null
+++ b/js/app/packages/core/component/AI/component/tool/ListTeamMembers.tsx
@@ -0,0 +1,120 @@
+import { UserIcon } from '@core/component/UserIcon';
+import { tryMacroId, useDisplayName } from '@core/user';
+import Envelope from '@phosphor-icons/core/regular/envelope.svg';
+import Users from '@phosphor-icons/core/regular/users.svg';
+import type { NamedTool } from '@service-cognition/generated/tools/tool';
+import { For, Show } from 'solid-js';
+import { BaseTool } from './BaseTool';
+import { createToolRenderer } from './ToolRenderer';
+
+type ListTeamMembersResponse = NamedTool<'ListTeamMembers', 'response'>['data'];
+
+type TeamMember = ListTeamMembersResponse['members'][number];
+type TeamInvite = ListTeamMembersResponse['invited'][number];
+
+const formatRole = (role: string) => role.split('_').join(' ');
+
+function TeamMemberRow(props: { member: TeamMember }) {
+ const [displayName] = useDisplayName(tryMacroId(props.member.userId));
+ const name = () => displayName() || props.member.userId;
+
+ return (
+ <div class="flex items-center gap-3 border-b border-edge-muted px-2 py-2 last:border-b-0">
+ <UserIcon id={props.member.userId} isDeleted={false} size="sm" />
+ <div class="min-w-0 flex-1">
+ <div class="truncate text-sm text-ink">{name()}</div>
+ <div class="truncate text-xs capitalize text-ink-extra-muted">
+ {formatRole(props.member.role)}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function TeamInviteRow(props: { invite: TeamInvite }) {
+ return (
+ <div class="flex items-center gap-3 border-b border-edge-muted px-2 py-2 last:border-b-0">
+ <div class="flex size-6 shrink-0 items-center justify-center rounded-full bg-accent/10">
+ <Envelope class="size-4 text-accent" />
+ </div>
+ <div class="min-w-0 flex-1">
+ <div class="truncate text-sm text-ink">{props.invite.email}</div>
+ <div class="truncate text-xs capitalize text-ink-extra-muted">
+ Invited as {formatRole(props.invite.role)}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function TeamMembersToolResponse(props: ListTeamMembersResponse) {
+ const hasMembers = () => props.members.length > 0;
+ const hasInvites = () => props.invited.length > 0;
+
+ return (
+ <div class="max-h-120 overflow-y-auto rounded-xs border border-edge-muted">
+ <Show when={hasMembers()}>
+ <For each={props.members}>
+ {(member) => <TeamMemberRow member={member} />}
+ </For>
+ </Show>
+ <Show when={hasInvites()}>
+ <For each={props.invited}>
+ {(invite) => <TeamInviteRow invite={invite} />}
+ </For>
+ </Show>
+ <Show when={!hasMembers() && !hasInvites()}>
+ <div class="px-2 py-2 text-sm text-ink-extra-muted">
+ No team members found.
+ </div>
+ </Show>
+ </div>
+ );
+}
+
+const pluralize = (count: number, singular: string, plural = `${singular}s`) =>
+ `${count} ${count === 1 ? singular : plural}`;
+
+const listTeamMembersHandler = createToolRenderer({
+ name: 'ListTeamMembers',
+ render: (ctx) => {
+ const members = () => ctx.response?.data.members ?? [];
+ const invited = () => ctx.response?.data.invited ?? [];
+ const statusText = () => {
+ if (!ctx.response) return undefined;
+
+ const parts = [pluralize(members().length, 'member')];
+ if (invited().length > 0) {
+ parts.push(pluralize(invited().length, 'pending invite'));
+ }
+
+ return parts.join(', ');
+ };
+
+ return (
+ <BaseTool
+ icon={Users}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ ctx.response ? (
+ <TeamMembersToolResponse members={members()} invited={invited()} />
+ ) : undefined
+ }
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span>Read team members</span>
+ <Show when={statusText()}>
+ {(text) => (
+ <span class="shrink-0 text-xs text-ink-extra-muted">
+ {text()}
+ </span>
+ )}
+ </Show>
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
+export { listTeamMembersHandler };
diff --git a/js/app/packages/core/component/AI/component/tool/handler.tsx b/js/app/packages/core/component/AI/component/tool/handler.tsx
index b9459bc8d1..c923ccd3f6 100644
--- a/js/app/packages/core/component/AI/component/tool/handler.tsx
+++ b/js/app/packages/core/component/AI/component/tool/handler.tsx
@@ -9,6 +9,7 @@ import { createDocumentHandler } from './CreateDocument';
import { getThreadHandler } from './GetThread';
import { listCallRecordsHandler } from './ListCallRecords';
import { listEntitiesHandler } from './ListEntities';
+import { listTeamMembersHandler } from './ListTeamMembers';
import {
listNotificationsHandler,
markNotificationsDoneHandler,
@@ -48,6 +49,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
ListCallRecords: listCallRecordsHandler,
ListEntities: listEntitiesHandler,
ListNotifications: listNotificationsHandler,
+ ListTeamMembers: listTeamMembersHandler,
MarkNotificationsDone: markNotificationsDoneHandler,
MarkNotificationsSeen: markNotificationsSeenHandler,
bash_code_execution: bashCodeExecutionHandler,
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
index 63e5b4bc7f..fc64bfd16c 100644
--- a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
@@ -559,6 +559,13 @@ export const ListNotificationsResponse = z.object({
),
});
+export const ListTeamMembers = z.record(z.any());
+
+export const ListTeamMembersResponse = z.object({
+ invited: z.array(z.object({ email: z.string(), role: z.string() })),
+ members: z.array(z.object({ role: z.string(), userId: z.string() })),
+});
+
export const MarkNotificationsDone = z.object({
done: z.boolean(),
notificationIds: z.array(z.string().uuid()),
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts b/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts
index 94aec019bf..a3147f5131 100644
--- a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts
@@ -37,6 +37,10 @@ type ToolParserMap = {
call: types.ListNotifications;
response: types.ListNotificationsResponse;
};
+ ListTeamMembers: {
+ call: types.ListTeamMembers;
+ response: types.ListTeamMembersResponse;
+ };
MarkNotificationsDone: {
call: types.MarkNotificationsDone;
response: types.MarkNotificationsResponse;
@@ -120,6 +124,10 @@ const toolParserMap = {
call: schemas.ListNotifications,
response: schemas.ListNotificationsResponse,
},
+ ListTeamMembers: {
+ call: schemas.ListTeamMembers,
+ response: schemas.ListTeamMembersResponse,
+ },
MarkNotificationsDone: {
call: schemas.MarkNotificationsDone,
response: schemas.MarkNotificationsResponse,
@@ -220,6 +228,10 @@ type ToolDataMap = {
call: types.ListNotifications;
response: types.ListNotificationsResponse;
};
+ ListTeamMembers: {
+ call: types.ListTeamMembers;
+ response: types.ListTeamMembersResponse;
+ };
MarkNotificationsDone: {
call: types.MarkNotificationsDone;
response: types.MarkNotificationsResponse;
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
index 52410825fb..6d8b00b7a1 100644
--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
@@ -1260,6 +1260,49 @@ export interface NotificationItem {
*/
senderId?: string | null;
}
+/**
+ * List the current members and pending invites for the authenticated user's team. Requires the caller to be a team member.
+ */
+export type ListTeamMembers = {};
+/**
+ * Response from [`ListTeamMembers`].
+ */
+export interface ListTeamMembersResponse {
+ /**
+ * Pending team invites.
+ */
+ invited: ToolTeamInvite[];
+ /**
+ * Current accepted team members.
+ */
+ members: ToolTeamMember[];
+}
+/**
+ * A pending team invite returned by [`ListTeamMembers`].
+ */
+export interface ToolTeamInvite {
+ /**
+ * The invited email address.
+ */
+ email: string;
+ /**
+ * The role the invited user will receive.
+ */
+ role: string;
+}
+/**
+ * A current team member returned by [`ListTeamMembers`].
+ */
+export interface ToolTeamMember {
+ /**
+ * The user's role in the team.
+ */
+ role: string;
+ /**
+ * The user's Macro user id.
+ */
+ userId: string;
+}
/**
* Mark one or more notifications as done or not done for the current user. Use this when the user has completed the action associated with a notification.
*/
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 2e4443d8d3..94593abb91 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -157,6 +157,7 @@ dependencies = [
"sqs_client",
"strum",
"sync_service_client",
+ "teams",
"tokio",
"tracing",
"utoipa",
@@ -11243,8 +11244,10 @@ checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417"
name = "teams"
version = "0.1.0"
dependencies = [
+ "ai",
"anyhow",
"async-stripe",
+ "async-trait",
"axum",
"chrono",
"entity_access",
@@ -11259,6 +11262,7 @@ dependencies = [
"notification",
"roles_and_permissions",
"rootcause",
+ "schemars",
"serde",
"serde_json",
"sqlx",
diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.toml
index b7ee931cd6..e5809156c2 100644
--- a/rust/cloud-storage/ai_tools/Cargo.toml
+++ b/rust/cloud-storage/ai_tools/Cargo.toml
@@ -60,6 +60,7 @@ serde_json.workspace = true
properties = { path = "../properties", features = ["ai_tools"] }
soup = { path = "../soup", features = ["ai_tools", "outbound"] }
sqs_client = { path = "../sqs_client", default-features = false, features = ["email", "gmail"] }
+teams = { path = "../teams", default-features = false, features = ["ai_tools", "outbound"] }
sqlx.workspace = true
strum.workspace = true
sync_service_client = { path = "../sync_service_client" }
diff --git a/rust/cloud-storage/ai_tools/src/build_context.rs b/rust/cloud-storage/ai_tools/src/build_context.rs
index 091d6f1005..5f01e4dc0f 100644
--- a/rust/cloud-storage/ai_tools/src/build_context.rs
+++ b/rust/cloud-storage/ai_tools/src/build_context.rs
@@ -290,6 +290,7 @@ pub async fn build_tool_service_context_from_env(
notification_tool_context,
chat_tool_context,
channel_tool_context,
+ team_tool_context: crate::tool_context::build_team_tool_context(pool.clone()),
schedule_tool_context: crate::NoOpScheduleContext,
})
}
diff --git a/rust/cloud-storage/ai_tools/src/lib.rs b/rust/cloud-storage/ai_tools/src/lib.rs
index 222c168725..5a9fe72d9f 100644
--- a/rust/cloud-storage/ai_tools/src/lib.rs
+++ b/rust/cloud-storage/ai_tools/src/lib.rs
@@ -21,6 +21,7 @@ use schemas::{anthropic_tools, read};
use soup::inbound::toolset::{ListEntities, SoupToolContext};
use std::sync::Arc;
use subagent::Subagent;
+use teams::inbound::toolset::team_toolset;
pub use build_context::build_tool_service_context_from_env;
pub use search::search_toolset;
@@ -35,7 +36,8 @@ pub use tool_context::{
ToolEntityAccessManagementService, ToolEntityAccessService, ToolFrecencyService,
ToolNotificationQueue, ToolNotificationService, ToolNotificationToolContext,
ToolPropertiesService, ToolPropertiesToolContext, ToolServiceContext, ToolSoupService,
- ToolUserEmailService, build_channel_tool_context,
+ ToolTeamService, ToolTeamToolContext, ToolUserEmailService, build_channel_tool_context,
+ build_team_tool_context,
};
pub type AiToolSet = AsyncToolCollection<ToolServiceContext>;
@@ -68,6 +70,7 @@ pub(crate) fn subagent_toolset() -> AiToolSet {
.add_subtoolset::<ToolCallToolContext>(call_toolset())
.add_subtoolset::<ToolChatToolContext>(chat_toolset())
.add_subtoolset::<ToolChannelToolContext>(channel_toolset())
+ .add_subtoolset::<ToolTeamToolContext>(team_toolset())
}
/// These are actually sent to the AI provider
diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rs
index c9d29079b4..fc599c6b91 100644
--- a/rust/cloud-storage/ai_tools/src/tool_context.rs
+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs
@@ -21,6 +21,7 @@ use notification::inbound::ai_tool::NotificationToolContext;
use properties::inbound::toolset::PropertiesToolContext;
use soup::{domain::service::SoupImpl, inbound::toolset::SoupToolContext};
use std::sync::Arc;
+use teams::{inbound::toolset::TeamToolContext, outbound::team_repo::TeamRepositoryImpl};
pub use ai_toolset::RequestContext;
@@ -60,6 +61,22 @@ pub fn build_channel_tool_context(pool: sqlx::PgPool) -> ToolChannelToolContext
)
}
+/// Type alias for the team member listing service used by AI tools.
+pub type ToolTeamService = TeamRepositoryImpl;
+
+/// Type alias for the team AI tool context.
+pub type ToolTeamToolContext = TeamToolContext<ToolTeamService, ToolEntityAccessService>;
+
+/// Build the team AI tool context from a Postgres pool.
+pub fn build_team_tool_context(pool: sqlx::PgPool) -> ToolTeamToolContext {
+ TeamToolContext::new(
+ TeamRepositoryImpl::new(pool.clone()),
+ entity_access::domain::service::EntityAccessServiceImpl::new(
+ entity_access::outbound::PgAccessRepository::new(pool),
+ ),
+ )
+}
+
/// No-op task properties service (not needed for AI tools)
#[derive(Clone)]
pub struct NoOpTaskProperties;
@@ -421,6 +438,7 @@ pub struct ToolServiceContext {
pub notification_tool_context: ToolNotificationToolContext,
pub chat_tool_context: ToolChatToolContext,
pub channel_tool_context: ToolChannelToolContext,
+ pub team_tool_context: ToolTeamToolContext,
pub schedule_tool_context: NoOpScheduleContext,
}
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
index 3b9ade1294..90415332b7 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
@@ -316,6 +316,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
notification_tool_context: notification_tool_context.clone(),
chat_tool_context,
channel_tool_context: ai_tools::build_channel_tool_context(pool.clone()),
+ team_tool_context: ai_tools::build_team_tool_context(pool.clone()),
schedule_tool_context: ai_tools::no_op_schedule_context(),
};
let all_tools = ai_tools::all_tools();
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index 52d15c09d8..f01816a2e3 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -374,6 +374,7 @@ async fn main() -> anyhow::Result<()> {
notification_tool_context: notification_tool_context.clone(),
chat_tool_context,
channel_tool_context: ai_tools::build_channel_tool_context(db.clone()),
+ team_tool_context: ai_tools::build_team_tool_context(db.clone()),
schedule_tool_context: ai_tools::NoOpScheduleContext,
};
let all_tools = ai_tools::all_tools();
diff --git a/rust/cloud-storage/entity_access/src/domain/models.rs b/rust/cloud-storage/entity_access/src/domain/models.rs
index dee4962769..7a93fde911 100644
--- a/rust/cloud-storage/entity_access/src/domain/models.rs
+++ b/rust/cloud-storage/entity_access/src/domain/models.rs
@@ -269,6 +269,24 @@ pub struct EntityAccessReceipt<T: RequiredPermission> {
}
impl<T: RequiredPermission> EntityAccessReceipt<T> {
+ /// Creates an access receipt for an authenticated user after validating the provided permission.
+ pub fn try_new_authenticated_user(
+ user_id: MacroUserIdStr<'static>,
+ entity: Entity,
+ entity_permission: EntityPermission,
+ ) -> Result<EntityAccessReceipt<T>, AccessError> {
+ if !entity_permission.satisfies::<T>() {
+ return Err(AccessError::Unauthorized);
+ }
+
+ Ok(EntityAccessReceipt {
+ auth: EntityAccessAuth::Authenticated(user_id),
+ entity,
+ entity_permission,
+ _marker: PhantomData,
+ })
+ }
+
/// get the authenticated user or error
pub fn get_authenticated_user(&self) -> Result<&MacroUserIdStr<'static>, AccessError> {
match &self.auth {
diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rs
index 5222ea3478..0336511115 100644
--- a/rust/cloud-storage/mcp_service/src/context.rs
+++ b/rust/cloud-storage/mcp_service/src/context.rs
@@ -306,6 +306,7 @@ async fn build_tool_context(
notification_tool_context,
chat_tool_context,
channel_tool_context: ai_tools::build_channel_tool_context(db.clone()),
+ team_tool_context: ai_tools::build_team_tool_context(db.clone()),
schedule_tool_context: NoOpScheduleContext,
};
diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/memory/src/context.rs
index 50967c3f8e..60759fa6e2 100644
--- a/rust/cloud-storage/memory/src/context.rs
+++ b/rust/cloud-storage/memory/src/context.rs
@@ -211,6 +211,7 @@ pub async fn build_tool_service_context(
notification_tool_context,
chat_tool_context,
channel_tool_context: ai_tools::build_channel_tool_context(pool.clone()),
+ team_tool_context: ai_tools::build_team_tool_context(pool.clone()),
schedule_tool_context: ai_tools::NoOpScheduleContext,
})
}
diff --git a/rust/cloud-storage/teams/Cargo.toml b/rust/cloud-storage/teams/Cargo.toml
index 556608d3ab..1766c1d028 100644
--- a/rust/cloud-storage/teams/Cargo.toml
+++ b/rust/cloud-storage/teams/Cargo.toml
@@ -5,6 +5,13 @@ publish = false
version = "0.1.0"
[features]
+ai_tools = [
+ "dep:ai",
+ "dep:async-trait",
+ "dep:schemars",
+ "entity_access/ports",
+ "ports",
+]
axum = [
"dep:axum",
"dep:model-error-response",
@@ -14,7 +21,7 @@ axum = [
"entity_access/inbound",
"entity_access/ports",
]
-default = ["axum", "inbound", "outbound", "ports"]
+default = ["ai_tools", "axum", "inbound", "outbound", "ports"]
inbound = ["axum", "ports"]
outbound = ["dep:sqlx", "dep:url", "ports"]
ports = [
@@ -26,12 +33,14 @@ ports = [
[dependencies]
# Core
+ai = { path = "../ai", optional = true }
anyhow = { workspace = true }
async-stripe = { workspace = true, default-features = false, features = [
"billing",
"checkout",
"runtime-tokio-hyper-rustls-webpki",
] }
+async-trait = { workspace = true, optional = true }
chrono = { workspace = true }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
@@ -39,6 +48,7 @@ non_empty = { path = "../non_empty" }
roles_and_permissions = { path = "../roles_and_permissions", default-features = false, features = [
"ports",
] }
+schemars = { workspace = true, optional = true }
serde = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
diff --git a/rust/cloud-storage/teams/src/domain/model.rs b/rust/cloud-storage/teams/src/domain/model.rs
index 0c7366a18a..038b7bfb08 100644
--- a/rust/cloud-storage/teams/src/domain/model.rs
+++ b/rust/cloud-storage/teams/src/domain/model.rs
@@ -112,6 +112,15 @@ pub struct TeamWithMembers {
pub members: Vec<TeamMember<'static>>,
}
+/// Current and invited members for a team.
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct TeamMembers {
+ /// Current accepted members of the team.
+ pub members: Vec<TeamMember<'static>>,
+ /// Pending invites for the team.
+ pub invited: Vec<TeamInviteDetails>,
+}
+
/// Detailed information about a team invite
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
diff --git a/rust/cloud-storage/teams/src/domain/team_repo.rs b/rust/cloud-storage/teams/src/domain/team_repo.rs
index dcc9e83c4e..f47e76b95a 100644
--- a/rust/cloud-storage/teams/src/domain/team_repo.rs
+++ b/rust/cloud-storage/teams/src/domain/team_repo.rs
@@ -12,7 +12,7 @@ use crate::domain::model::{
PatchTeamPlanRequest, PatchTeamRequest, RemoveTeamInviteError, RemoveUserFromTeamError,
RestorePermissionsForTeamMembersError, RevokePermissionsForTeamMembersError, Team,
TeamCheckoutError, TeamCheckoutSessionRequest, TeamError, TeamInvite, TeamInviteDetails,
- TeamMember, TeamPlan, TeamRole, TeamWithMembers,
+ TeamMember, TeamMembers, TeamPlan, TeamRole, TeamWithMembers,
};
/// The TeamChannelsRepository defines a set of actions related to team channels
@@ -239,6 +239,15 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {
) -> impl Future<Output = Result<(), TeamError>> + Send;
}
+/// The TeamMembersService defines read-only team membership queries.
+pub trait TeamMembersService: Clone + Send + Sync + 'static {
+ /// Lists current members and pending invites for a team.
+ fn list_team_members(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<MemberTeamRole>,
+ ) -> impl Future<Output = Result<TeamMembers, TeamError>> + Send;
+}
+
/// The TeamService defines a set of actions to perform on the teams
pub trait TeamService: Clone + Send + Sync + 'static {
/// Creates a new team
diff --git a/rust/cloud-storage/teams/src/domain/team_service.rs b/rust/cloud-storage/teams/src/domain/team_service.rs
index 0ecb0b2fe2..5fb2381fd7 100644
--- a/rust/cloud-storage/teams/src/domain/team_service.rs
+++ b/rust/cloud-storage/teams/src/domain/team_service.rs
@@ -28,9 +28,9 @@ use crate::domain::{
PatchTeamPlanRequest, PatchTeamRequest, RemoveTeamInviteError, RemoveUserFromTeamError,
RestorePermissionsForTeamMembersError, RevokePermissionsForTeamMembersError, Team,
TeamCheckoutError, TeamCheckoutSessionRequest, TeamError, TeamInvite, TeamInviteDetails,
- TeamMember, TeamPlan, TeamRole, TeamWithMembers,
+ TeamMember, TeamMembers, TeamPlan, TeamRole, TeamWithMembers,
},
- team_repo::{TeamChannelsRepository, TeamRepository, TeamService},
+ team_repo::{TeamChannelsRepository, TeamMembersService, TeamRepository, TeamService},
};
/// Implementation of the TeamService using a TeamRepository
@@ -211,6 +211,29 @@ impl GetTeamSubscriptionError {
}
}
+impl<TR, CR, TCR, URPS, NI> TeamMembersService for TeamServiceImpl<TR, CR, TCR, URPS, NI>
+where
+ TR: TeamRepository,
+ CR: CustomerRepository,
+ TCR: TeamChannelsRepository,
+ URPS: UserRolesAndPermissionsService,
+ NI: NotificationIngress,
+{
+ #[tracing::instrument(skip(self), err)]
+ async fn list_team_members(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<MemberTeamRole>,
+ ) -> Result<TeamMembers, TeamError> {
+ let team_id =
+ macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();
+
+ let members = self.team_repository.get_team_by_id(&team_id).await?.members;
+ let invited = self.team_repository.get_team_invites(&team_id).await?;
+
+ Ok(TeamMembers { members, invited })
+ }
+}
+
impl<TR, CR, TCR, URPS, NI> TeamService for TeamServiceImpl<TR, CR, TCR, URPS, NI>
where
TR: TeamRepository,
diff --git a/rust/cloud-storage/teams/src/inbound.rs b/rust/cloud-storage/teams/src/inbound.rs
index b30e1e36d6..2f5fb01a15 100644
--- a/rust/cloud-storage/teams/src/inbound.rs
+++ b/rust/cloud-storage/teams/src/inbound.rs
@@ -2,3 +2,6 @@
#[cfg(feature = "axum")]
pub mod axum_router;
+
+#[cfg(feature = "ai_tools")]
+pub mod toolset;
diff --git a/rust/cloud-storage/teams/src/inbound/toolset/list_team_members.rs b/rust/cloud-storage/teams/src/inbound/toolset/list_team_members.rs
new file mode 100644
index 0000000000..02340c8d56
--- /dev/null
+++ b/rust/cloud-storage/teams/src/inbound/toolset/list_team_members.rs
@@ -0,0 +1,159 @@
+//! ListTeamMembers tool for reading the caller's team members.
+
+use super::TeamToolContext;
+use crate::domain::{
+ model::{TeamInviteDetails, TeamMember},
+ team_repo::TeamMembersService,
+};
+use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use async_trait::async_trait;
+use entity_access::domain::{
+ models::{
+ AccessError, Entity, EntityAccessReceipt, EntityPermission, EntityType, MemberTeamRole,
+ },
+ ports::EntityAccessService,
+};
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+/// A current team member returned by [`ListTeamMembers`].
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ToolTeamMember {
+ /// The user's Macro user id.
+ pub user_id: String,
+ /// The user's role in the team.
+ pub role: String,
+}
+
+impl From<TeamMember<'static>> for ToolTeamMember {
+ fn from(member: TeamMember<'static>) -> Self {
+ Self {
+ user_id: member.user_id.to_string(),
+ role: member.role.to_string(),
+ }
+ }
+}
+
+/// A pending team invite returned by [`ListTeamMembers`].
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ToolTeamInvite {
+ /// The invited email address.
+ pub email: String,
+ /// The role the invited user will receive.
+ pub role: String,
+}
+
+impl From<TeamInviteDetails> for ToolTeamInvite {
+ fn from(invite: TeamInviteDetails) -> Self {
+ Self {
+ email: invite.email,
+ role: invite.team_role.to_string(),
+ }
+ }
+}
+
+/// Response from [`ListTeamMembers`].
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ListTeamMembersResponse {
+ /// Current accepted team members.
+ pub members: Vec<ToolTeamMember>,
+ /// Pending team invites.
+ pub invited: Vec<ToolTeamInvite>,
+}
+
+/// List current and invited members of the caller's team.
+#[derive(Debug, Deserialize, JsonSchema, Clone, Default)]
+#[schemars(
+ title = "ListTeamMembers",
+ description = "List the current members and pending invites for the authenticated user's team. Requires the caller to be a team member."
+)]
+#[allow(unused)]
+// empty structs can't be deserialized;
+pub struct ListTeamMembers {}
+
+#[async_trait]
+impl<TSvc, ESvc> AsyncTool<TeamToolContext<TSvc, ESvc>> for ListTeamMembers
+where
+ TSvc: TeamMembersService,
+ ESvc: EntityAccessService,
+{
+ type Output = ListTeamMembersResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<TeamToolContext<TSvc, ESvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ tracing::info!("List team members");
+
+ let entity_access_receipt = team_member_receipt(&service_context, request_context).await?;
+
+ let team_members = service_context
+ .service
+ .list_team_members(entity_access_receipt)
+ .await
+ .map_err(|e| ToolCallError {
+ description: "unable to list team members".to_string(),
+ internal_error: e.into(),
+ })?;
+
+ Ok(ListTeamMembersResponse {
+ members: team_members.members.into_iter().map(Into::into).collect(),
+ invited: team_members.invited.into_iter().map(Into::into).collect(),
+ })
+ }
+}
+
+async fn team_member_receipt<TSvc, ESvc>(
+ service_context: &ServiceContext<TeamToolContext<TSvc, ESvc>>,
+ request_context: RequestContext,
+) -> Result<EntityAccessReceipt<MemberTeamRole>, ToolCallError>
+where
+ TSvc: TeamMembersService,
+ ESvc: EntityAccessService,
+{
+ let team_info = service_context
+ .entity_access_service
+ .get_user_team(&request_context.user_id)
+ .await
+ .map_err(team_access_error)?;
+
+ let Some(team_info) = team_info else {
+ return Err(ToolCallError {
+ description: "user is not in a team".to_string(),
+ internal_error: anyhow::anyhow!("user is not in a team"),
+ });
+ };
+
+ EntityAccessReceipt::try_new_authenticated_user(
+ request_context.user_id,
+ Entity {
+ entity_id: team_info.team_id.to_string(),
+ entity_type: EntityType::Team,
+ },
+ EntityPermission::TeamRole {
+ role: team_info.role,
+ },
+ )
+ .map_err(team_access_error)
+}
+
+fn team_access_error(err: AccessError) -> ToolCallError {
+ let description = match err {
+ AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_) => {
+ "user is not a member of a team"
+ }
+ AccessError::NotFound(_) => "team not found",
+ AccessError::BadRequest(_) => "invalid team membership",
+ AccessError::DatabaseError(_) | AccessError::Internal => "failed to verify team membership",
+ };
+
+ ToolCallError {
+ description: description.to_string(),
+ internal_error: err.into(),
+ }
+}
diff --git a/rust/cloud-storage/teams/src/inbound/toolset/mod.rs b/rust/cloud-storage/teams/src/inbound/toolset/mod.rs
new file mode 100644
index 0000000000..f4f71de0e4
--- /dev/null
+++ b/rust/cloud-storage/teams/src/inbound/toolset/mod.rs
@@ -0,0 +1,60 @@
+//! Toolset inbound adapter for teams.
+
+mod list_team_members;
+
+#[cfg(test)]
+mod test;
+
+use crate::domain::team_repo::TeamMembersService;
+use ai::tool::AsyncToolCollection;
+use entity_access::domain::ports::EntityAccessService;
+use list_team_members::ListTeamMembers;
+use std::sync::Arc;
+
+/// Service context for team AI tools.
+pub struct TeamToolContext<TSvc, ESvc>
+where
+ TSvc: TeamMembersService,
+ ESvc: EntityAccessService,
+{
+ /// The team service used to read team membership data.
+ pub service: Arc<TSvc>,
+ /// The entity access service used to resolve the caller's team membership.
+ pub entity_access_service: Arc<ESvc>,
+}
+
+impl<TSvc, ESvc> Clone for TeamToolContext<TSvc, ESvc>
+where
+ TSvc: TeamMembersService,
+ ESvc: EntityAccessService,
+{
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ entity_access_service: self.entity_access_service.clone(),
+ }
+ }
+}
+
+impl<TSvc, ESvc> TeamToolContext<TSvc, ESvc>
+where
+ TSvc: TeamMembersService,
+ ESvc: EntityAccessService,
+{
+ /// Create a new team tool context.
+ pub fn new(service: TSvc, entity_access_service: ESvc) -> Self {
+ Self {
+ service: Arc::new(service),
+ entity_access_service: Arc::new(entity_access_service),
+ }
+ }
+}
+
+/// Create a team toolset.
+pub fn team_toolset<TSvc, ESvc>() -> AsyncToolCollection<TeamToolContext<TSvc, ESvc>>
+where
+ TSvc: TeamMembersService,
+ ESvc: EntityAccessService,
+{
+ AsyncToolCollection::new().add_tool::<ListTeamMembers, TeamToolContext<TSvc, ESvc>>()
+}
diff --git a/rust/cloud-storage/teams/src/inbound/toolset/test.rs b/rust/cloud-storage/teams/src/inbound/toolset/test.rs
new file mode 100644
index 0000000000..cf057dc6af
--- /dev/null
+++ b/rust/cloud-storage/teams/src/inbound/toolset/test.rs
@@ -0,0 +1,21 @@
+use super::list_team_members::ListTeamMembers;
+use ai::generate_tool_input_schema;
+use ai::tool::types::tool_object::validate_tool_schema;
+
+#[test]
+fn test_list_team_members_schema_validation() {
+ let schema = generate_tool_input_schema!(ListTeamMembers);
+
+ let result = validate_tool_schema(&schema);
+ assert!(result.is_ok(), "{:?}", result);
+
+ let (name, description) = result.unwrap();
+ assert_eq!(
+ name, "ListTeamMembers",
+ "Tool name should match the schemars title"
+ );
+ assert!(
+ description.contains("List"),
+ "Description should contain expected text"
+ );
+}
diff --git a/rust/cloud-storage/teams/src/lib.rs b/rust/cloud-storage/teams/src/lib.rs
index 833cd00b6b..f6284b5f8b 100644
--- a/rust/cloud-storage/teams/src/lib.rs
+++ b/rust/cloud-storage/teams/src/lib.rs
@@ -13,7 +13,7 @@
pub mod domain;
/// The inbound module contains the inbound adapters for teams
-#[cfg(feature = "inbound")]
+#[cfg(any(feature = "inbound", feature = "ai_tools"))]
pub mod inbound;
/// The outbound module contains the outbound logic for teams
diff --git a/rust/cloud-storage/teams/src/outbound/team_repo.rs b/rust/cloud-storage/teams/src/outbound/team_repo.rs
index b58d4d867b..379afe19b5 100644
--- a/rust/cloud-storage/teams/src/outbound/team_repo.rs
+++ b/rust/cloud-storage/teams/src/outbound/team_repo.rs
@@ -3,9 +3,10 @@ use crate::domain::{
model::{
AcceptedTeamInvite, CreateTeamError, InviteUsersToTeamError, PatchTeamRequest,
RemoveTeamInviteError, RemoveUserFromTeamError, Team, TeamError, TeamInvite,
- TeamInviteDetails, TeamInviteSnapshot, TeamMember, TeamPlan, TeamRole, TeamWithMembers,
+ TeamInviteDetails, TeamInviteSnapshot, TeamMember, TeamMembers, TeamPlan, TeamRole,
+ TeamWithMembers,
},
- team_repo::TeamRepository,
+ team_repo::{TeamMembersService, TeamRepository},
};
use macro_user_id::{
cowlike::CowLike, email::Email, lowercased::Lowercase, user_id::MacroUserIdStr,
@@ -163,6 +164,24 @@ impl From<sqlx::Error> for RemoveTeamInviteError {
}
}
+impl TeamMembersService for TeamRepositoryImpl {
+ #[tracing::instrument(skip(self), err)]
+ async fn list_team_members(
+ &self,
+ entity_access_receipt: entity_access::domain::models::EntityAccessReceipt<
+ entity_access::domain::models::MemberTeamRole,
+ >,
+ ) -> Result<TeamMembers, TeamError> {
+ let team_id =
+ macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();
+
+ let members = self.get_team_by_id(&team_id).await?.members;
+ let invited = self.get_team_invites(&team_id).await?;
+
+ Ok(TeamMembers { members, invited })
+ }
+}
+
impl TeamRepository for TeamRepositoryImpl {
#[tracing::instrument(skip(self), err)]
async fn get_stripe_customer_id(