Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(mcp): show MCP client posts as the client's agent, from the user (#9360)
Wolf Mermelstein757f07cc2046
diff --git a/apps/web/src/features/channel/Message/FromPill.tsx b/apps/web/src/features/channel/Message/FromPill.tsxindex 09ded96a5a..08425b1ba4 100644--- a/apps/web/src/features/channel/Message/FromPill.tsx+++ b/apps/web/src/features/channel/Message/FromPill.tsx@@ -10,10 +10,8 @@ type FromPillProps = {/*** Shows who triggered an agent (bot) message, e.g. `from Eric Hayes`, where the- * name is a hoverable user reference (same hover card as an `@mention`), and- * the client they wrote it through when it names one, e.g.- * `from Eric Hayes via Claude Code`. Rendered only when the message's sender- * carries a `triggered_by` user id.+ * name is a hoverable user reference (same hover card as an `@mention`).+ * Rendered only when the message's sender carries a `triggered_by` user id.*/export function FromPill(props: FromPillProps) {const message = useMessage();@@ -28,7 +26,6 @@ export function FromPill(props: FromPillProps) {return id ? macroIdToEmail(id) : (triggeredBy() ?? '');};const label = () => displayName() || email() || (triggeredBy() ?? '');- const via = () => message().sender?.triggered_via ?? undefined;return (<Show when={triggeredBy()}>@@ -53,14 +50,6 @@ export function FromPill(props: FromPillProps) {</span>}/>- <Show when={via()}>- {(client) => (- <>- via- <span class="font-medium text-ink">{client()}</span>- </>- )}- </Show></span></Show>);diff --git a/apps/web/src/features/channel/Message/SenderIcon.test.tsx b/apps/web/src/features/channel/Message/SenderIcon.test.tsxindex 94dad857e2..554e3f1ca0 100644--- a/apps/web/src/features/channel/Message/SenderIcon.test.tsx+++ b/apps/web/src/features/channel/Message/SenderIcon.test.tsx@@ -69,6 +69,21 @@ describe('SenderIcon', () => {}});+ it('draws a post made through an MCP client as that client', () => {+ const { getByTestId, queryByTestId } = renderSender(+ message(MACRO_AGENT_PRINCIPAL_ID, {+ type: 'bot',+ id: '00000000-0000-0000-0000-00000000a1a1',+ name: 'Macro',+ triggered_by: 'macro|[email protected]',+ triggered_via: 'Claude Code',+ })+ );+ expect(getByTestId('bot-icon').textContent).toBe('Claude Code');+ expect(getByTestId('user-card').dataset.name).toBe('Claude Code');+ expect(queryByTestId('user-icon')).toBeNull();+ });+it('draws a team bot with its own uploaded avatar', () => {const { getByTestId, queryByTestId } = renderSender(message(`bot|${TEAM_BOT_ID}`, {diff --git a/apps/web/src/features/channel/Message/SenderIcon.tsx b/apps/web/src/features/channel/Message/SenderIcon.tsxindex da62f9b510..a46f8a9869 100644--- a/apps/web/src/features/channel/Message/SenderIcon.tsx+++ b/apps/web/src/features/channel/Message/SenderIcon.tsx@@ -26,12 +26,15 @@ export function SenderIcon(props: SenderIconProps) {// Team bots render their uploaded avatar; first-party bots have none and// keep their brand mark, which UserIcon draws the same way the mention menu- // does.+ // does. A post a user made through a client is that client's, so it shows+ // the client's initial rather than the mark of the bot that carried it.const botSender = (): MessageSender | undefined => {const current = sender();- if (current.type !== 'bot' || firstPartyBotMark(current.id)) {- return undefined;+ if (current.type !== 'bot') return undefined;+ if (current.triggered_via) {+ return { ...current, name: current.triggered_via, avatar_url: null };}+ if (firstPartyBotMark(current.id)) return undefined;return current;};diff --git a/apps/web/src/lib/queries/messages/message-sender.ts b/apps/web/src/lib/queries/messages/message-sender.tsindex 8785ae5723..0460381153 100644--- a/apps/web/src/lib/queries/messages/message-sender.ts+++ b/apps/web/src/lib/queries/messages/message-sender.ts@@ -40,7 +40,11 @@ export function senderFromStorageId(senderId: string): MessageSender {return { type: 'user', id: senderId };}-/** Resolve a channel bot sender to its display name. */+/**+ * Resolve a channel bot sender to its display name. A bot post a user made+ * through a client, such as an MCP client, is shown as that client's agent+ * ("Claude Code"), not as the bot that carried it.+ */export function getBotDisplayName(senderId: string,sender?: MessageSender,@@ -53,6 +57,7 @@ export function getBotDisplayName(if (parsed.type !== 'bot' && !systemName) return undefined;return (+ parsed.triggered_via ??parsed.name ??systemName ??bots.find((bot) => bot.id === parsed.id)?.name ??diff --git a/apps/web/src/lib/queries/messages/tests/message-sender.test.ts b/apps/web/src/lib/queries/messages/tests/message-sender.test.tsindex 0e336387a2..756eab24bc 100644--- a/apps/web/src/lib/queries/messages/tests/message-sender.test.ts+++ b/apps/web/src/lib/queries/messages/tests/message-sender.test.ts@@ -1,3 +1,4 @@+import { MACRO_AGENT_PRINCIPAL_ID } from '@core/constant/macroAgent';import {MACRO_CODER_NAME,MACRO_CODER_PRINCIPAL_ID,@@ -132,6 +133,28 @@ describe('message sender normalization', () => {);});+ it('names a post made through an MCP client after the client', () => {+ const message = normalizeThreadReplySender({+ id: 'reply-1',+ parent: { type: 'channel', id: 'channel-1' },+ mentions: [],+ sender_id: MACRO_AGENT_PRINCIPAL_ID,+ bot_profile: { name: 'Macro' },+ triggered_by: 'macro|[email protected]',+ triggered_via: 'Claude Code',+ content: 'posted from Claude Code',+ created_at: '2026-11-02T10:00:00.000Z',+ updated_at: '2026-11-02T10:00:00.000Z',+ attachments: [],+ reactions: [],+ });++ expect(getBotDisplayName(message.sender_id, message.sender)).toBe(+ 'Claude Code'+ );+ expect(getBotDisplayName(MACRO_AGENT_PRINCIPAL_ID)).toBe('Macro');+ });+it('uses a generic label rather than exposing an unknown bot UUID', () => {expect(getBotDisplayName('bot|00000000-0000-0000-0000-000000000002')).toBe('Bot'diff --git a/crates/agent_egress/AGENTS.md b/crates/agent_egress/AGENTS.mdindex e0f76dc70f..65bce9492c 100644--- a/crates/agent_egress/AGENTS.md+++ b/crates/agent_egress/AGENTS.md@@ -60,7 +60,9 @@ Session-egress Macro API tokens (`MacroApiTokens::mint`) carry the session'sbound agent (`agent_session.bot_id`, read off the row as `SessionGrant.agent`) astheir signed `agent_id` claim, so Macro's tools write as that agent. The botnever comes from the request. `MacroApiTokenSigner::mint_for_agent` callers-(code mode) choose the claim themselves; `mint_for` signs none.+(code mode) choose the claim themselves, plus an optional signed `agent_via`+client label (public MCP code mode signs the MCP client's name); `mint_for`+signs neither.## Gotchasdiff --git a/crates/agent_egress/src/outbound/macro_mcp.rs b/crates/agent_egress/src/outbound/macro_mcp.rsindex e64bef02dc..e5a8353752 100644--- a/crates/agent_egress/src/outbound/macro_mcp.rs+++ b/crates/agent_egress/src/outbound/macro_mcp.rs@@ -264,16 +264,19 @@ impl MacroApiTokenSigner {owner: &MacroUserIdStr<'static>,lifetime_seconds: usize,) -> Result<String, EgressError> {- self.mint_for_agent(owner, lifetime_seconds, None).await+ self.mint_for_agent(owner, lifetime_seconds, None, None)+ .await}- /// Mint an owner credential with signed agent attribution for SDK messages.- #[tracing::instrument(skip_all, err, fields(?agent_id))]+ /// Mint an owner credential with signed agent attribution for SDK messages,+ /// and the client label (`agent_via`) the agent's posts are shown under.+ #[tracing::instrument(skip_all, err, fields(?agent_id, ?agent_via))]pub async fn mint_for_agent(&self,owner: &MacroUserIdStr<'static>,lifetime_seconds: usize,agent_id: Option<macro_uuid::Uuid>,+ agent_via: Option<String>,) -> Result<String, EgressError> {if !(1..=MINTED_TOKEN_LIFETIME_SECONDS).contains(&lifetime_seconds) {return Err(EgressError::Internal(rootcause::report!(@@ -315,6 +318,7 @@ impl MacroApiTokenSigner {private_key: self.private_key.clone(),expiry_seconds: lifetime_seconds,agent_id,+ agent_via,}).map_err(|error| {EgressError::Internal(rootcause::report!(@@ -330,7 +334,12 @@ impl MacroApiTokens for MacroApiTokenSigner {owner: &MacroUserIdStr<'static>,agent: BotId,) -> Result<String, EgressError> {- self.mint_for_agent(owner, MINTED_TOKEN_LIFETIME_SECONDS, Some(agent.as_uuid()))- .await+ self.mint_for_agent(+ owner,+ MINTED_TOKEN_LIFETIME_SECONDS,+ Some(agent.as_uuid()),+ None,+ )+ .await}}diff --git a/crates/agent_harness/src/inbound/runtime_gateway/test.rs b/crates/agent_harness/src/inbound/runtime_gateway/test.rsindex 3ae2fb1c0b..de2de454c0 100644--- a/crates/agent_harness/src/inbound/runtime_gateway/test.rs+++ b/crates/agent_harness/src/inbound/runtime_gateway/test.rs@@ -31,6 +31,7 @@ impl JwtValidator for FakeJwtValidator {origin: macro_authorization::CredentialOrigin::Session,identity: ValidatedIdentity {agent_id: None,+ agent_via: None,user_id: jwt.to_string(),fusion_user_id: "fusion-user".to_string(),organization_id: None,@@ -65,6 +66,7 @@ impl HarnessAuthorizer for SelfHarnessAuthorizer {acting_user: MacroUserAuthentication {origin: macro_authorization::CredentialOrigin::Harness,agent_id: None,+ agent_via: None,macro_user_id,user_context: model_user::UserContext {user_id,diff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rsindex ce0bb314ad..b74b1dda67 100644--- a/crates/agent_session/src/inbound/axum_router/test.rs+++ b/crates/agent_session/src/inbound/axum_router/test.rs@@ -106,6 +106,7 @@ impl JwtValidator for FakeJwtValidator {origin: macro_authorization::CredentialOrigin::Session,identity: ValidatedIdentity {agent_id: None,+ agent_via: None,user_id: jwt.to_string(),fusion_user_id: "fusion-user".to_string(),organization_id: None,@@ -136,6 +137,7 @@ impl BotAuthorizer for SelfBotAuthorizer {Some(MacroUserAuthentication {origin: macro_authorization::CredentialOrigin::Bot,agent_id: None,+ agent_via: None,macro_user_id,user_context: model_user::UserContext {user_id,@@ -184,6 +186,7 @@ impl HarnessAuthorizer for SelfHarnessAuthorizer {acting_user: MacroUserAuthentication {origin: macro_authorization::CredentialOrigin::Harness,agent_id: None,+ agent_via: None,macro_user_id,user_context: model_user::UserContext {user_id,diff --git a/crates/agent_session/src/inbound/coding_agents/test.rs b/crates/agent_session/src/inbound/coding_agents/test.rsindex c3f1bef08f..f945032b45 100644--- a/crates/agent_session/src/inbound/coding_agents/test.rs+++ b/crates/agent_session/src/inbound/coding_agents/test.rs@@ -26,6 +26,7 @@ impl JwtValidator for UserCredentials {origin: macro_authorization::CredentialOrigin::Session,identity: ValidatedIdentity {agent_id: None,+ agent_via: None,user_id: USER.into(),fusion_user_id: "fusion-owner".into(),organization_id: None,diff --git a/crates/agent_session/src/inbound/routine_sessions/test.rs b/crates/agent_session/src/inbound/routine_sessions/test.rsindex c439d51f0d..adc2876443 100644--- a/crates/agent_session/src/inbound/routine_sessions/test.rs+++ b/crates/agent_session/src/inbound/routine_sessions/test.rs@@ -33,6 +33,7 @@ impl JwtValidator for Credentials {origin: macro_authorization::CredentialOrigin::Session,identity: ValidatedIdentity {agent_id: None,+ agent_via: None,user_id: OWNER.into(),fusion_user_id: "fusion-owner".into(),organization_id: None,@@ -74,6 +75,7 @@ impl HarnessAuthorizer for Credentials {acting_user: MacroUserAuthentication {origin: macro_authorization::CredentialOrigin::Harness,agent_id: None,+ agent_via: None,macro_user_id: MacroUserIdStr::try_from(OWNER).unwrap(),user_context: model_user::UserContext {user_id: OWNER.into(),diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rsindex e1f82e1ef9..f689266253 100644--- a/crates/ai_tools/src/tool_context.rs+++ b/crates/ai_tools/src/tool_context.rs@@ -2191,14 +2191,16 @@ impl ToolServiceContext {/// Run the tools for `caller`, as the public MCP authenticated it: an/// agent writes as itself; an MCP client writes as the Macro bot with its- /// name on the post ("via Claude Code"); a pasted API key writes as the- /// Macro bot.+ /// name on the post, shown as the author ("Claude Code · Agent"); a pasted+ /// API key writes as the Macro bot.pub fn for_caller(self, caller: &ai_toolset::ToolCaller) -> Self {match caller {ai_toolset::ToolCaller::Agent(agent) => self.with_actor(*agent),- ai_toolset::ToolCaller::McpClient { name: Some(name) } => self.with_via(name),- ai_toolset::ToolCaller::McpClient { name: None } | ai_toolset::ToolCaller::ApiKey => {- self+ ai_toolset::ToolCaller::McpClient { .. } | ai_toolset::ToolCaller::ApiKey => {+ match caller.via() {+ Some(client) => self.with_via(client),+ None => self,+ }}}}@@ -2208,6 +2210,7 @@ impl ToolServiceContext {fn with_via(mut self, client: &str) -> Self {self.message_tool_context = self.message_tool_context.with_via(client.to_owned());self.channel_tool_context = self.channel_tool_context.with_via(client.to_owned());+ self.document_tool_context = self.document_tool_context.with_via(client.to_owned());self}diff --git a/crates/ai_toolset/src/caller.rs b/crates/ai_toolset/src/caller.rsindex 34d3d2f096..e302d00ee0 100644--- a/crates/ai_toolset/src/caller.rs+++ b/crates/ai_toolset/src/caller.rs@@ -23,10 +23,11 @@ pub enum ToolCaller {}impl ToolCaller {- /// The label a write made for this caller is shown "via", if any.+ /// The client a write made for this caller is shown under, if any. An+ /// MCP client that registered no name is shown as a generic one.pub fn via(&self) -> Option<&str> {match self {- Self::McpClient { name } => name.as_deref(),+ Self::McpClient { name } => Some(name.as_deref().unwrap_or("MCP client")),Self::Agent(_) | Self::ApiKey => None,}}diff --git a/crates/bots/src/inbound/axum_router/tests.rs b/crates/bots/src/inbound/axum_router/tests.rsindex 0ebfe618aa..1eb7203808 100644--- a/crates/bots/src/inbound/axum_router/tests.rs+++ b/crates/bots/src/inbound/axum_router/tests.rs@@ -431,6 +431,7 @@ impl JwtValidator for FakeJwtValidator {origin: macro_authorization::CredentialOrigin::Session,identity: ValidatedIdentity {agent_id: None,+ agent_via: None,user_id: jwt.to_string(),fusion_user_id: "fusion-user".to_string(),organization_id: None,diff --git a/crates/bots/src/inbound/channel_webhook_router/tests.rs b/crates/bots/src/inbound/channel_webhook_router/tests.rsindex 67a22561f2..5f3ad4e3f2 100644--- a/crates/bots/src/inbound/channel_webhook_router/tests.rs+++ b/crates/bots/src/inbound/channel_webhook_router/tests.rs@@ -742,6 +742,7 @@ impl JwtValidator for FakeJwtValidator {origin: macro_authorization::CredentialOrigin::Session,identity: ValidatedIdentity {agent_id: None,+ agent_via: None,user_id: jwt.to_string(),fusion_user_id: "fusion-user".to_string(),organization_id: None,@@ -832,6 +833,7 @@ fn bot_authentication_with_acting_user(bot_id: BotId) -> BotAuthentication {acting_user: Some(MacroUserAuthentication {origin: macro_authorization::CredentialOrigin::Bot,agent_id: None,+ agent_via: None,macro_user_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),user_context: Default::default(),}),diff --git a/crates/channels/src/domain/message_delivery.rs b/crates/channels/src/domain/message_delivery.rsindex 51692fc3ad..a517105b44 100644--- a/crates/channels/src/domain/message_delivery.rs+++ b/crates/channels/src/domain/message_delivery.rs@@ -63,6 +63,7 @@ fn persisted(channel_id: Uuid, message: &Message) -> MutatedMessage {thread_id: message.thread_id,sender_id: message.sender_id.clone(),triggered_by: message.triggered_by.clone(),+ triggered_via: message.triggered_via.clone(),content: message.content.clone(),created_at: message.created_at,updated_at: message.updated_at,diff --git a/crates/channels/src/domain/models.rs b/crates/channels/src/domain/models.rsindex 617fa7c566..bca1b0ffad 100644--- a/crates/channels/src/domain/models.rs+++ b/crates/channels/src/domain/models.rs@@ -833,6 +833,8 @@ pub struct MutatedMessage {pub sender_id: ChannelSender<'static>,/// For an agent (bot) message, the id of the user who triggered it.pub triggered_by: Option<String>,+ /// The client the user triggered it through, such as "Claude Code".+ pub triggered_via: Option<String>,/// Message body.pub content: String,/// Created timestamp.diff --git a/crates/channels/src/domain/side_effects.rs b/crates/channels/src/domain/side_effects.rsindex 2074299334..85f2c063c7 100644--- a/crates/channels/src/domain/side_effects.rs+++ b/crates/channels/src/domain/side_effects.rs@@ -459,9 +459,16 @@ whereN: ChannelNotificationSender + Clone,K: ChannelContactsDispatcher + Clone,{- /// Resolve the public bot profile when the message sender is a bot.+ /// Resolve the public bot profile when the message sender is a bot. A post+ /// a user made through a client, such as an MCP client, is that client's.async fn bot_profile_for_message(&self, message: &MutatedMessage) -> Option<BotSenderProfile> {let bot_id = message.sender_id.as_bot()?.bot_id();+ if let Some(client) = &message.triggered_via {+ return Some(BotSenderProfile {+ name: client.clone(),+ avatar_url: None,+ });+ }if bot_id == bot_id::MACRO_AI_BOT_ID {return Some(BotSenderProfile {name: bot_id::MACRO_AI_NAME.to_string(),diff --git a/crates/channels/src/domain/side_effects/test.rs b/crates/channels/src/domain/side_effects/test.rsindex 560d5ea239..f8488736d2 100644--- a/crates/channels/src/domain/side_effects/test.rs+++ b/crates/channels/src/domain/side_effects/test.rs@@ -275,6 +275,7 @@ async fn macro_ai_bot_profile_is_builtin_without_context_lookup() {thread_id: None,sender_id: Sender::new_from_bot(bot_id::MACRO_AI_BOT_ID),triggered_by: None,+ triggered_via: None,content: "hello".to_string(),created_at: now,updated_at: now,@@ -292,6 +293,43 @@ async fn macro_ai_bot_profile_is_builtin_without_context_lookup() {assert_eq!(*lookup_count.lock().unwrap(), 0);}+#[tokio::test]+async fn mcp_client_post_is_named_after_the_client() {+ let lookup_count = Arc::new(Mutex::new(0));+ let service = ChannelSideEffectService::new(+ FakeContext {+ bot_profile_lookup_count: lookup_count.clone(),+ ..FakeContext::default()+ },+ FakeRealtime::default(),+ FakeNotifications::default(),+ FakeContacts::default(),+ );+ let now = Utc::now();+ let message = MutatedMessage {+ id: Uuid::new_v4(),+ channel_id: Uuid::new_v4(),+ thread_id: None,+ sender_id: Sender::new_from_bot(bot_id::MACRO_AI_BOT_ID),+ triggered_by: Some("macro|[email protected]".to_string()),+ triggered_via: Some("Claude Code".to_string()),+ content: "hello".to_string(),+ created_at: now,+ updated_at: now,+ edited_at: None,+ deleted_at: None,+ };++ let profile = service+ .bot_profile_for_message(&message)+ .await+ .expect("a client post should have a profile");++ assert_eq!(profile.name, "Claude Code");+ assert_eq!(profile.avatar_url, None);+ assert_eq!(*lookup_count.lock().unwrap(), 0);+}+#[tokio::test]async fn non_macro_bot_profile_uses_context_lookup() {let lookup_count = Arc::new(Mutex::new(0));@@ -311,6 +349,7 @@ async fn non_macro_bot_profile_uses_context_lookup() {thread_id: None,sender_id: Sender::new_from_bot(BotId::new_from_uuid(Uuid::new_v4())),triggered_by: None,+ triggered_via: None,content: "hello".to_string(),created_at: now,updated_at: now,@@ -373,6 +412,7 @@ async fn message_posted_derives_notification_effects_without_legacy_realtime() {thread_id: None,sender_id: Sender::new_from_user(sender.clone()),triggered_by: None,+ triggered_via: None,content: "hello".to_string(),created_at: now,updated_at: now,@@ -438,6 +478,7 @@ fn bot_message_posted_event(thread_id,sender_id: Sender::new_from_bot(BotId::new_from_uuid(Uuid::new_v4())),triggered_by: None,+ triggered_via: None,content: "hello".to_string(),created_at: now,updated_at: now,@@ -495,6 +536,7 @@ async fn silent_message_posted_skips_notifications_only() {thread_id: None,sender_id: Sender::new_from_user(sender),triggered_by: None,+ triggered_via: None,content: "transient".to_string(),created_at: now,updated_at: now,@@ -556,6 +598,7 @@ async fn mentions_only_skips_failing_invite_lookup_and_sends_mention() {thread_id: None,sender_id: Sender::new_from_user(sender),triggered_by: None,+ triggered_via: None,content: "welcome".to_string(),created_at: now,updated_at: now,@@ -832,6 +875,7 @@ async fn document_mentions_notify_participants_except_sender() {thread_id: None,sender_id: Sender::new_from_user(sender.clone()),triggered_by: None,+ triggered_via: None,content: "hello".to_string(),created_at: now,updated_at: now,@@ -1226,6 +1270,7 @@ fn mention_broker_events_map_message_posted_mentions() {thread_id: None,sender_id: Sender::new_from_user(user("[email protected]")),triggered_by: None,+ triggered_via: None,content: "@bot @doc-1".to_string(),created_at: now,updated_at: now,diff --git a/crates/channels/src/inbound/axum_router/test.rs b/crates/channels/src/inbound/axum_router/test.rsindex 1e88456385..4333863914 100644--- a/crates/channels/src/inbound/axum_router/test.rs+++ b/crates/channels/src/inbound/axum_router/test.rs@@ -723,6 +723,7 @@ impl JwtValidator for FakeJwtValidator {origin: macro_authorization::CredentialOrigin::Session,identity: ValidatedIdentity {agent_id: None,+ agent_via: None,user_id: TEST_USER_ID.to_string(),fusion_user_id: "test-fusion-user".to_string(),organization_id,diff --git a/crates/channels/src/inbound/list_router/test.rs b/crates/channels/src/inbound/list_router/test.rsindex a017b47a19..50a78ec35a 100644--- a/crates/channels/src/inbound/list_router/test.rs+++ b/crates/channels/src/inbound/list_router/test.rs@@ -120,6 +120,7 @@ impl JwtValidator for FakeJwtValidator {origin: macro_authorization::CredentialOrigin::Session,identity: ValidatedIdentity {agent_id: None,+ agent_via: None,user_id: BEARER_USER_ID.to_string(),fusion_user_id: "fusion-user-id".to_string(),organization_id: None,diff --git a/crates/chat/src/inbound/test.rs b/crates/chat/src/inbound/test.rsindex f370977a09..dea89c8fe9 100644--- a/crates/chat/src/inbound/test.rs+++ b/crates/chat/src/inbound/test.rs@@ -557,6 +557,7 @@ impl MacroAuthorizationService for FakeAuthorizationService {.map(|user_id| MacroUserAuthentication {origin: macro_authorization::CredentialOrigin::Bot,agent_id: None,+ agent_via: None,macro_user_id: MacroUserIdStr::try_from(user_id.clone()).expect("test user id should be valid"),user_context: UserContext {diff --git a/crates/contacts/src/inbound/http/test.rs b/crates/contacts/src/inbound/http/test.rsindex 6fd0f42583..242d269f24 100644--- a/crates/contacts/src/inbound/http/test.rs+++ b/crates/contacts/src/inbound/http/test.rs@@ -80,6 +80,7 @@ impl JwtValidator for FakeJwtValidator {origin: macro_authorization::CredentialOrigin::Session,identity: ValidatedIdentity {agent_id: None,+ agent_via: None,user_id: user_id.to_string(),fusion_user_id: "fusion-user-id".to_string(),permissions: None,diff --git a/crates/crm/src/inbound/axum_extractors/test.rs b/crates/crm/src/inbound/axum_extractors/test.rsindex d5ebd18652..6203cebf01 100644--- a/crates/crm/src/inbound/axum_extractors/test.rs+++ b/crates/crm/src/inbound/axum_extractors/test.rs@@ -65,6 +65,7 @@ impl JwtValidator for FakeJwtValidator {origin: macro_authorization::CredentialOrigin::Session,identity: ValidatedIdentity {agent_id: None,+ agent_via: None,user_id: USER_ID.to_string(),fusion_user_id: "test-fusion-user".to_string(),organization_id: None,diff --git a/crates/crm/tests/pipelines.rs b/crates/crm/tests/pipelines.rsindex 26b96955b4..c9a2b0b97f 100644--- a/crates/crm/tests/pipelines.rs+++ b/crates/crm/tests/pipelines.rs@@ -743,6 +743,7 @@ async fn http_creation_listing_schema_and_records_use_pipeline_access(pool: PgPoorigin: macro_authorization::CredentialOrigin::Session,identity: ValidatedIdentity {agent_id: None,+ agent_via: None,user_id: if jwt == "owner" { OWNER } else { OUTSIDER }.into(),fusion_user_id: "test-fusion-user".into(),organization_id: None,diff --git a/crates/databases/src/inbound/axum_router/test/fakes.rs b/crates/databases/src/inbound/axum_router/test/fakes.rsindex b1b1f8e8d3..fe15297390 100644--- a/crates/databases/src/inbound/axum_router/test/fakes.rs+++ b/crates/databases/src/inbound/axum_router/test/fakes.rs@@ -51,6 +51,7 @@ impl JwtValidator for ValidToken {origin: macro_authorization::CredentialOrigin::Session,identity: ValidatedIdentity {agent_id: None,+ agent_via: None,user_id: USER.to_string(),fusion_user_id: "fusion-ops-router".to_string(),organization_id: None,diff --git a/crates/databases_sql/src/service/test/http.rs b/crates/databases_sql/src/service/test/http.rsindex e2f74890d6..4cc7a2e695 100644--- a/crates/databases_sql/src/service/test/http.rs+++ b/crates/databases_sql/src/service/test/http.rs@@ -34,6 +34,7 @@ impl JwtValidator for Token {origin: macro_authorization::CredentialOrigin::Session,identity: ValidatedIdentity {agent_id: None,+ agent_via: None,user_id: user_id.into(),fusion_user_id: "fusion-sql-test".into(),organization_id: None,diff --git a/crates/documents/src/inbound/axum_router/tests.rs b/crates/documents/src/inbound/axum_router/tests.rsindex 741d3a3fa9..b43086407e 100644--- a/crates/documents/src/inbound/axum_router/tests.rs+++ b/crates/documents/src/inbound/axum_router/tests.rs@@ -914,6 +914,7 @@ impl MacroAuthorizationService for FakeAuthorizationService {.map(|user_id| MacroUserAuthentication {origin: macro_authorization::CredentialOrigin::Bot,agent_id: None,+ agent_via: None,macro_user_id: user(&user_id),user_context: user_context(&user_id),}),diff --git a/crates/documents/src/inbound/toolset.rs b/crates/documents/src/inbound/toolset.rsindex d234778742..af4dfcee1a 100644--- a/crates/documents/src/inbound/toolset.rs+++ b/crates/documents/src/inbound/toolset.rs@@ -63,7 +63,9 @@ use entity_access::domain::{};use lexical_client::LexicalClient;use macro_user_id::user_id::MacroUserIdStr;-use messages::domain::{api::MessageServiceApi, ports::MessageError, service::MessageWrite};+use messages::domain::{+ api::MessageServiceApi, models::MessageAttribution, ports::MessageError, service::MessageWrite,+};use model_owner::CreationPrincipal;use std::sync::Arc;use sync_service_client::SyncServiceClient;@@ -156,6 +158,10 @@ pub struct DocumentToolContext</// already read, so it hands the name over rather than have every tool/// look it up again.actor_name: Option<EditorName>,++ /// The client the requesting user drives these tools through, such as an+ /// MCP client, set with [`Self::with_via`]; comments carry it as a label.+ via: Option<String>,}impl<@@ -185,6 +191,7 @@ impl<recorder: self.recorder.clone(),actor: self.actor,actor_name: self.actor_name.clone(),+ via: self.via.clone(),}}}@@ -255,6 +262,7 @@ impl<recorder: Arc::new(ai_usage::NoOpUsageRecorder),actor: bot_id::MACRO_AI_BOT_ID,actor_name: None,+ via: None,}}@@ -334,6 +342,23 @@ impl<self}+ /// Label the comments these tools post with the client the requesting+ /// user works through, such as an MCP client.+ pub fn with_via(mut self, client: String) -> Self {+ self.via = Some(client);+ self+ }++ /// How a comment posted by these tools is attributed.+ pub fn attribution(&self) -> MessageAttribution {+ match &self.via {+ Some(client) => MessageAttribution::ActingUserVia {+ client: client.clone(),+ },+ None => MessageAttribution::ActingUser,+ }+ }+/// The name readers see on what these tools write as it happens - the/// label on the cursor the editing worker draws: the host-supplied name,/// else the first-party bot's own. `None` for a user- or team-owned botdiff --git a/crates/documents/src/inbound/toolset/comment_on_text.rs b/crates/documents/src/inbound/toolset/comment_on_text.rsindex 067cc398ce..6251682505 100644--- a/crates/documents/src/inbound/toolset/comment_on_text.rs+++ b/crates/documents/src/inbound/toolset/comment_on_text.rs@@ -6,9 +6,7 @@ use async_trait::async_trait;use entity_access::domain::models::EntityAccessReceipt;use entity_access::domain::ports::EntityAccessService;use macro_sync_service_jwt::DocumentPermissionToken;-use messages::domain::models::{- MessageAttribution, NewThreadAnchor, PostMessage, PostMessageNotificationPolicy,-};+use messages::domain::models::{NewThreadAnchor, PostMessage, PostMessageNotificationPolicy};use messages::domain::service::MessageWrite;use model::document::FileType;use models_permissions::share_permission::access_level::AccessLevel;@@ -177,7 +175,7 @@ whereaccess,PostMessage {id: None,- attribution: MessageAttribution::ActingUser,+ attribution: ctx.attribution(),notification_policy: PostMessageNotificationPolicy::Default,content: self.content.clone(),thread_id: None,@@ -242,7 +240,7 @@ impl CommentOnText {access,PostMessage {id: None,- attribution: MessageAttribution::ActingUser,+ attribution: ctx.attribution(),notification_policy: PostMessageNotificationPolicy::Default,content: self.content.clone(),thread_id: None,diff --git a/crates/documents/src/inbound/toolset/comment_test.rs b/crates/documents/src/inbound/toolset/comment_test.rsindex 46b60e34ca..8fa67cd6de 100644--- a/crates/documents/src/inbound/toolset/comment_test.rs+++ b/crates/documents/src/inbound/toolset/comment_test.rs@@ -288,6 +288,36 @@ async fn comment_on_text_places_the_mark_then_posts_a_thread_anchored_to_it() {assert!(editing.removed_comment_marks.lock().unwrap().is_empty());}+#[tokio::test]+async fn comment_on_text_through_an_mcp_client_carries_its_name() {+ let messages = FakeMessages::default();+ let ServiceContext(context) = context_with(+ AccessLevel::Comment,+ messages.clone(),+ "md",+ FakeEditingWorker::default(),+ );+ comment_on_text("ships on Friday", None)+ .call(+ ServiceContext(context.with_via("Claude Code".to_owned())),+ request(),+ )+ .await+ .unwrap();++ let posts = messages.posts.lock().unwrap();+ let [(access, post)] = posts.as_slice() else {+ panic!("expected one post, got {}", posts.len());+ };+ assert_bot_on_document(access);+ assert_eq!(+ post.attribution,+ MessageAttribution::ActingUserVia {+ client: "Claude Code".to_owned()+ }+ );+}+#[tokio::test]async fn comment_on_text_refused_by_the_document_posts_nothing() {for reason in ["The text appears 2 times.", "The text was not found."] {diff --git a/crates/entity_access/src/inbound/axum_extractors/initiative/test.rs b/crates/entity_access/src/inbound/axum_extractors/initiative/test.rsindex 14afd60f69..2cfb961b49 100644--- a/crates/entity_access/src/inbound/axum_extractors/initiative/test.rs+++ b/crates/entity_access/src/inbound/axum_extractors/initiative/test.rs@@ -87,6 +87,7 @@ fn user_authentication(user_id: &str) -> MacroUserAuthentication {MacroUserAuthentication {origin: macro_authorization::CredentialOrigin::Session,agent_id: None,+ agent_via: None,macro_user_id: MacroUserIdStr::try_from(user_id.to_string()).expect("valid user id"),user_context: UserContext {user_id: user_id.to_string(),diff --git a/crates/entity_access/src/inbound/axum_extractors/principal/test.rs b/crates/entity_access/src/inbound/axum_extractors/principal/test.rsindex d80cac7d85..82599b63ff 100644--- a/crates/entity_access/src/inbound/axum_extractors/principal/test.rs+++ b/crates/entity_access/src/inbound/axum_extractors/principal/test.rs@@ -19,6 +19,7 @@ async fn signed_agent_uses_owner_scope_and_preserves_both_identities() {let principal = MacroAuthorization::User(MacroUserAuthentication {origin: macro_authorization::CredentialOrigin::MacroApiJwt,agent_id: Some(agent_id),+ agent_via: None,macro_user_id: owner,user_context: UserContext {user_id: "macro|[email protected]".into(),@@ -61,6 +62,7 @@ async fn signed_agent_cannot_send_without_owner_access() {let principal = MacroAuthorization::User(MacroUserAuthentication {origin: macro_authorization::CredentialOrigin::MacroApiJwt,agent_id: Some(bot_id::MACRO_NEW_BOT_ID),+ agent_via: None,macro_user_id: "macro|[email protected]".to_string().try_into().unwrap(),user_context: UserContext {user_id: "macro|[email protected]".into(),@@ -87,6 +89,7 @@ async fn signed_agent_does_not_change_caller_identity_for_existing_messages() {let principal = MacroAuthorization::User(MacroUserAuthentication {origin: macro_authorization::CredentialOrigin::MacroApiJwt,agent_id: Some(bot_id::MACRO_NEW_BOT_ID),+ agent_via: None,macro_user_id: "macro|[email protected]".to_string().try_into().unwrap(),user_context: UserContext {user_id: "macro|[email protected]".into(),diff --git a/crates/entity_access/src/inbound/axum_extractors/test_support.rs b/crates/entity_access/src/inbound/axum_extractors/test_support.rsindex 8013c6b362..12df4f36d7 100644--- a/crates/entity_access/src/inbound/axum_extractors/test_support.rs+++ b/crates/entity_access/src/inbound/axum_extractors/test_support.rs@@ -292,6 +292,7 @@ pub(super) fn user_scoped_bot_authentication() -> BotAuthentication {acting_user: Some(MacroUserAuthentication {origin: macro_authorization::CredentialOrigin::Bot,agent_id: None,+ agent_via: None,macro_user_id: MacroUserIdStr::try_from(BOT_ACTING_USER_ID.to_string()).expect("valid bot acting user id"),user_context: user_context_with_organization(diff --git a/crates/entity_registry/entity_registry/src/domain/creation_principal/test.rs b/crates/entity_registry/entity_registry/src/domain/creation_principal/test.rsindex 4bf76f26d0..5f1d7414f4 100644--- a/crates/entity_registry/entity_registry/src/domain/creation_principal/test.rs+++ b/crates/entity_registry/entity_registry/src/domain/creation_principal/test.rs@@ -19,6 +19,7 @@ fn user() -> MacroUserAuthentication {MacroUserAuthentication {origin: macro_authorization::CredentialOrigin::Session,agent_id: None,+ agent_via: None,macro_user_id: user_id(),user_context: Default::default(),}diff --git a/crates/external_chat/src/inbound/router/test.rs b/crates/external_chat/src/inbound/router/test.rsindex 6d688e15ea..af974ff101 100644--- a/crates/external_chat/src/inbound/router/test.rs+++ b/crates/external_chat/src/inbound/router/test.rs@@ -44,6 +44,7 @@ fn verified_owner_api_credentials_remain_distinct_from_sessions_and_bots() {let user = MacroUserAuthentication {origin,agent_id,+ agent_via: None,macro_user_id: "macro|[email protected]".to_string().try_into().unwrap(),user_context: Default::default(),};diff --git a/crates/forms/src/inbound/axum_router/test/fakes.rs b/crates/forms/src/inbound/axum_router/test/fakes.rsindex 9a58277079..01c79f12da 100644--- a/crates/forms/src/inbound/axum_router/test/fakes.rs+++ b/crates/forms/src/inbound/axum_router/test/fakes.rs@@ -57,6 +57,7 @@ impl JwtValidator for Tokens {origin: macro_authorization::CredentialOrigin::MacroApiJwt,identity: ValidatedIdentity {agent_id,+ agent_via: None,user_id: user_id.to_string(),fusion_user_id: format!("fusion-{jwt}"),organization_id: None,diff --git a/crates/local_e2e_test_support/src/jwt.rs b/crates/local_e2e_test_support/src/jwt.rsindex 1e65708af6..5b11404261 100644--- a/crates/local_e2e_test_support/src/jwt.rs+++ b/crates/local_e2e_test_support/src/jwt.rs@@ -95,6 +95,7 @@ pub fn encode_local_jwt_claims_with(encode_macro_api_token(EncodeMacroApiTokenArgs {agent_id: None,+ agent_via: None,fusionauth_id: claims.fusion_user_id.to_owned(),macro_user_id: claims.macro_user_id.to_owned(),organization_id: claims.organization_id,diff --git a/crates/macro_auth/AGENTS.md b/crates/macro_auth/AGENTS.mdindex 98f7f39643..b5cae8be84 100644--- a/crates/macro_auth/AGENTS.md+++ b/crates/macro_auth/AGENTS.md@@ -32,8 +32,9 @@ internal API key, and the Axum JWT-decode middleware.- `cargo test -p macro_auth` (`SQLX_OFFLINE` unset).-Macro API tokens may include a signed `agent_id` for SDK message attribution;-ordinary user token producers leave it absent.+Macro API tokens may include a signed `agent_id` for SDK message attribution,+and with it an `agent_via` client label ("Claude Code"); ordinary user token+producers leave both absent.## Gotchasdiff --git a/crates/macro_auth/src/macro_api_token.rs b/crates/macro_auth/src/macro_api_token.rsindex a278092d15..5c530a50d9 100644--- a/crates/macro_auth/src/macro_api_token.rs+++ b/crates/macro_auth/src/macro_api_token.rs@@ -21,6 +21,10 @@ pub struct MacroApiToken {/// Agent responsible for this user-authorized execution, signed by the harness.#[serde(default, skip_serializing_if = "Option::is_none")]pub agent_id: Option<Uuid>,+ /// Self-reported name of the client the user drives the agent through,+ /// such as "Claude Code"; a display label signed with `agent_id`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub agent_via: Option<String>,}pub struct EncodeMacroApiTokenArgs {@@ -38,6 +42,8 @@ pub struct EncodeMacroApiTokenArgs {pub expiry_seconds: usize,/// Optional agent attribution; never supplied by an API caller.pub agent_id: Option<Uuid>,+ /// Optional client label for `agent_id`; never supplied by an API caller.+ pub agent_via: Option<String>,}#[tracing::instrument(skip(args))]@@ -50,6 +56,7 @@ pub fn encode_macro_api_token(args: EncodeMacroApiTokenArgs) -> anyhow::Result<Slet claims = MacroApiToken {exp: now + args.expiry_seconds,agent_id: args.agent_id,+ agent_via: args.agent_via,iss: args.issuer.clone(),fusion_user_id: args.fusionauth_id.clone(),macro_user_id: args.macro_user_id.clone(),diff --git a/crates/macro_auth/src/middleware/decode_jwt.rs b/crates/macro_auth/src/middleware/decode_jwt.rsindex 5257fe615a..a886de9e5e 100644--- a/crates/macro_auth/src/middleware/decode_jwt.rs+++ b/crates/macro_auth/src/middleware/decode_jwt.rs@@ -432,6 +432,7 @@ CwIDAQABlet claims = MacroApiToken {agent_id: None,+ agent_via: None,exp: now + 3600, // Token expires in 1 houriss: issuer.to_string(),fusion_user_id: fusionauth_id.to_string(),diff --git a/crates/macro_auth/src/middleware/decode_jwt/agent_test.rs b/crates/macro_auth/src/middleware/decode_jwt/agent_test.rsindex 51d2b46cca..ec84f88b1b 100644--- a/crates/macro_auth/src/middleware/decode_jwt/agent_test.rs+++ b/crates/macro_auth/src/middleware/decode_jwt/agent_test.rs@@ -12,6 +12,7 @@ fn signed_execution_token_preserves_owner_agent_and_lifetime() {private_key: tests::PRIVATE_KEY.into(),expiry_seconds: 60,agent_id: Some(agent),+ agent_via: Some("Claude Code".into()),}).unwrap();let args = JwtValidationArgs {@@ -27,6 +28,7 @@ fn signed_execution_token_preserves_owner_agent_and_lifetime() {panic!("expected Macro API token");};assert_eq!(claims.agent_id, Some(agent));+ assert_eq!(claims.agent_via.as_deref(), Some("Claude Code"));assert_eq!(claims.macro_user_id, "macro|[email protected]");assert_eq!(claims.macro_organization_id, Some(42));let now = std::time::SystemTime::now()@@ -58,4 +60,5 @@ fn legacy_user_token_has_no_agent_attribution() {})).unwrap();assert_eq!(claims.agent_id, None);+ assert_eq!(claims.agent_via, None);}diff --git a/crates/macro_auth/src/middleware/decode_jwt/fusionauth_access_token_test.rs b/crates/macro_auth/src/middleware/decode_jwt/fusionauth_access_token_test.rsindex 0c53a9d7e4..426deff6df 100644--- a/crates/macro_auth/src/middleware/decode_jwt/fusionauth_access_token_test.rs+++ b/crates/macro_auth/src/middleware/decode_jwt/fusionauth_access_token_test.rs@@ -99,6 +99,7 @@ fn tokens_not_issued_by_fusionauth_for_this_application_are_rejected() {private_key: tests::PRIVATE_KEY.into(),expiry_seconds: 60,agent_id: None,+ agent_via: None,}).unwrap();diff --git a/crates/macro_authorization/src/domain/bot_authorizer.rs b/crates/macro_authorization/src/domain/bot_authorizer.rsindex dfbbe3508e..7495110a5c 100644--- a/crates/macro_authorization/src/domain/bot_authorizer.rs+++ b/crates/macro_authorization/src/domain/bot_authorizer.rs@@ -155,6 +155,7 @@ fn user_authentication(acting_user: ResolvedBotActingUser) -> MacroUserAuthenticMacroUserAuthentication {origin: CredentialOrigin::Bot,agent_id: None,+ agent_via: None,macro_user_id: acting_user.macro_user_id,user_context: UserContext {user_id,diff --git a/crates/macro_authorization/src/domain/harness_authorizer.rs b/crates/macro_authorization/src/domain/harness_authorizer.rsindex bbfebc43e9..a9f7d34630 100644--- a/crates/macro_authorization/src/domain/harness_authorizer.rs+++ b/crates/macro_authorization/src/domain/harness_authorizer.rs@@ -113,6 +113,7 @@ fn user_authentication(acting_user: ResolvedBotActingUser) -> MacroUserAuthenticMacroUserAuthentication {origin: CredentialOrigin::Harness,agent_id: None,+ agent_via: None,macro_user_id: acting_user.macro_user_id,user_context: UserContext {user_id,diff --git a/crates/macro_authorization/src/domain/models.rs b/crates/macro_authorization/src/domain/models.rsindex b0e5c86704..af7b9e08e5 100644--- a/crates/macro_authorization/src/domain/models.rs+++ b/crates/macro_authorization/src/domain/models.rs@@ -17,6 +17,8 @@ pub struct MacroUserAuthentication {pub origin: CredentialOrigin,/// Signed agent attribution for user-authorized SDK messages, not a bot credential.pub agent_id: Option<BotId>,+ /// Signed label of the client the user drives `agent_id` through.+ pub agent_via: Option<String>,/// The user's parsed Macro identifier.pub macro_user_id: MacroUserIdStr<'static>,/// The authenticated user context.@@ -278,6 +280,8 @@ pub struct InternalAuthConfig {pub struct ValidatedIdentity {/// Agent attribution from a cryptographically verified Macro API token.pub agent_id: Option<BotId>,+ /// Client label signed with `agent_id`, such as "Claude Code".+ pub agent_via: Option<String>,/// The user's Macro identifier.pub user_id: String,/// The user's FusionAuth or root identifier.@@ -304,6 +308,7 @@ impl ValidatedCredential {origin: CredentialOrigin::Session,identity: ValidatedIdentity {agent_id: None,+ agent_via: None,user_id: context.user_id,fusion_user_id: context.fusion_user_id,organization_id: context.organization_id,diff --git a/crates/macro_authorization/src/domain/models/test.rs b/crates/macro_authorization/src/domain/models/test.rsindex da78445e6d..17688df3de 100644--- a/crates/macro_authorization/src/domain/models/test.rs+++ b/crates/macro_authorization/src/domain/models/test.rs@@ -16,6 +16,7 @@ fn user_authentication() -> MacroUserAuthentication {MacroUserAuthentication {origin: crate::CredentialOrigin::Session,agent_id: None,+ agent_via: None,macro_user_id: MacroUserIdStr::try_from("macro|[email protected]".to_string()).expect("valid Macro user id"),user_context: UserContext {diff --git a/crates/macro_authorization/src/domain/service/test.rs b/crates/macro_authorization/src/domain/service/test.rsindex e6bc014c39..0185673ebd 100644--- a/crates/macro_authorization/src/domain/service/test.rs+++ b/crates/macro_authorization/src/domain/service/test.rs@@ -175,6 +175,7 @@ fn bot_authentication() -> BotAuthentication {acting_user: Some(MacroUserAuthentication {origin: crate::CredentialOrigin::Bot,agent_id: None,+ agent_via: None,macro_user_id: MacroUserIdStr::try_from("macro|[email protected]".to_string()).expect("valid Macro user id"),user_context: UserContext {@@ -325,6 +326,7 @@ async fn authorize_constructs_user_context_from_validated_identity() {origin: CredentialOrigin::Session,identity: ValidatedIdentity {agent_id: None,+ agent_via: None,user_id: "macro|[email protected]".to_string(),fusion_user_id: "fusion-user-id".to_string(),organization_id: Some(42),@@ -550,6 +552,7 @@ async fn authorize_identity_keeps_verified_agent_and_owner() {origin: CredentialOrigin::MacroApiJwt,identity: ValidatedIdentity {agent_id: Some(bot_id::MACRO_NEW_BOT_ID),+ agent_via: None,user_id: "macro|[email protected]".into(),fusion_user_id: "fusion-owner".into(),organization_id: Some(42),diff --git a/crates/macro_authorization/src/inbound/axum.rs b/crates/macro_authorization/src/inbound/axum.rsindex aa0093e5d3..e3a89e3fb9 100644--- a/crates/macro_authorization/src/inbound/axum.rs+++ b/crates/macro_authorization/src/inbound/axum.rs@@ -148,6 +148,7 @@ pub(super) fn authenticated_user(Ok(MacroUserAuthentication {origin,agent_id: None,+ agent_via: None,macro_user_id,user_context,})diff --git a/crates/macro_authorization/src/inbound/axum/test.rs b/crates/macro_authorization/src/inbound/axum/test.rsindex ad8a51c3d0..b886d060ec 100644--- a/crates/macro_authorization/src/inbound/axum/test.rs+++ b/crates/macro_authorization/src/inbound/axum/test.rs@@ -190,6 +190,7 @@ fn bot_authentication(bot_scope: BotScope, acting_user_id: Option<&str>) -> BotAacting_user: acting_user_id.map(|user_id| MacroUserAuthentication {origin: crate::CredentialOrigin::Bot,agent_id: None,+ agent_via: None,macro_user_id: MacroUserIdStr::try_from(user_id.to_owned()).expect("valid bot acting user id"),user_context: user_context(user_id, Some(42)),@@ -2219,6 +2220,7 @@ fn macro_user_authentication(user_id: &str) -> MacroUserAuthentication {MacroUserAuthentication {origin: crate::CredentialOrigin::Session,agent_id: None,+ agent_via: None,macro_user_id: MacroUserIdStr::try_from(user_id.to_owned()).expect("valid Macro user ID"),user_context: user_context(user_id, None),}diff --git a/crates/macro_authorization/src/inbound/axum/user.rs b/crates/macro_authorization/src/inbound/axum/user.rsindex d165ee0c9c..c9a68dc8cd 100644--- a/crates/macro_authorization/src/inbound/axum/user.rs+++ b/crates/macro_authorization/src/inbound/axum/user.rs@@ -155,6 +155,7 @@ wherecredential.origin,)?;user.agent_id = identity.agent_id;+ user.agent_via = identity.agent_via;Ok(user)}diff --git a/crates/macro_authorization/src/inbound/axum/user/test.rs b/crates/macro_authorization/src/inbound/axum/user/test.rsindex 65ebf1c764..eb41e38044 100644--- a/crates/macro_authorization/src/inbound/axum/user/test.rs+++ b/crates/macro_authorization/src/inbound/axum/user/test.rs@@ -27,6 +27,7 @@ impl JwtValidator for Validator {match jwt {"execution" | "api" | "user" => Ok(ValidatedIdentity {agent_id: (jwt == "execution").then_some(bot_id::MACRO_NEW_BOT_ID),+ agent_via: None,user_id: "macro|[email protected]".into(),fusion_user_id: "fusion-owner".into(),organization_id: Some(42),diff --git a/crates/macro_authorization/src/outbound/macro_auth.rs b/crates/macro_authorization/src/outbound/macro_auth.rsindex d732bef7b1..52b1e9c49a 100644--- a/crates/macro_authorization/src/outbound/macro_auth.rs+++ b/crates/macro_authorization/src/outbound/macro_auth.rs@@ -49,18 +49,20 @@ fn identity_from_token(token: JwtToken) -> ValidatedCredential {JwtToken::MacroAccessToken(_) => CredentialOrigin::Session,JwtToken::MacroApiToken(_) => CredentialOrigin::MacroApiJwt,};- let (user_id, fusion_user_id, organization_id, agent_id) = match token {+ let (user_id, fusion_user_id, organization_id, agent_id, agent_via) = match token {JwtToken::MacroAccessToken(token) => (token.macro_user_id,token.root_macro_id.unwrap_or(token.fusion_user_id),token.macro_organization_id,None,+ None,),JwtToken::MacroApiToken(token) => (token.macro_user_id,token.fusion_user_id,token.macro_organization_id,token.agent_id.map(bot_id::BotId::new_from_uuid),+ token.agent_id.and(token.agent_via),),};@@ -68,6 +70,7 @@ fn identity_from_token(token: JwtToken) -> ValidatedCredential {origin,identity: ValidatedIdentity {agent_id,+ agent_via,user_id,fusion_user_id,organization_id,diff --git a/crates/macro_authorization/src/outbound/macro_auth/test.rs b/crates/macro_authorization/src/outbound/macro_auth/test.rsindex 53a005d2f6..59df728f0e 100644--- a/crates/macro_authorization/src/outbound/macro_auth/test.rs+++ b/crates/macro_authorization/src/outbound/macro_auth/test.rs@@ -143,6 +143,7 @@ fn preserves_access_token_organization_id() {fn maps_macro_api_token_claims() {let credential = identity_from_token(JwtToken::MacroApiToken(MacroApiToken {agent_id: None,+ agent_via: None,exp: unix_timestamp() + 3_600,iss: String::new(),fusion_user_id: FUSION_USER_ID.to_string(),@@ -164,6 +165,7 @@ fn maps_signed_agent_without_changing_owner_identity() {let agent = bot_id::MACRO_NEW_BOT_ID;let credential = identity_from_token(JwtToken::MacroApiToken(MacroApiToken {agent_id: Some(agent.as_uuid()),+ agent_via: Some("Claude Code".into()),exp: unix_timestamp() + 60,iss: String::new(),fusion_user_id: FUSION_USER_ID.into(),@@ -173,6 +175,22 @@ fn maps_signed_agent_without_changing_owner_identity() {assert_eq!(credential.origin, CredentialOrigin::MacroApiJwt);let identity = credential.identity;assert_eq!(identity.agent_id, Some(agent));+ assert_eq!(identity.agent_via.as_deref(), Some("Claude Code"));assert_eq!(identity.user_id, MACRO_USER_ID);assert_eq!(identity.organization_id, Some(42));}++#[test]+fn ignores_a_client_label_without_a_signed_agent() {+ let credential = identity_from_token(JwtToken::MacroApiToken(MacroApiToken {+ agent_id: None,+ agent_via: Some("Claude Code".into()),+ exp: unix_timestamp() + 60,+ iss: String::new(),+ fusion_user_id: FUSION_USER_ID.into(),+ macro_user_id: MACRO_USER_ID.into(),+ macro_organization_id: None,+ }));+ assert_eq!(credential.identity.agent_id, None);+ assert_eq!(credential.identity.agent_via, None);+}diff --git a/crates/messages/AGENTS.md b/crates/messages/AGENTS.mdindex 21de2b74bd..29a9117b5a 100644--- a/crates/messages/AGENTS.md+++ b/crates/messages/AGENTS.md@@ -65,8 +65,10 @@ post; streaming updates and ordinary edits never do.A bot post made for a user through a named client (an MCP client on the publicMCP) uses `MessageAttribution::ActingUserVia`; the client's self-reported name is-stored in `comms_messages.triggered_via` beside `triggered_by` and shown "via-<client>". It is a display label only.+stored in `comms_messages.triggered_via` beside `triggered_by`, and clients show+the post as that client's ("Claude Code · Agent · from <user>"). It is a display+label only. Over HTTP the label comes only from the signed `agent_via` claim of+a code-mode token, never from the request body.New posts use the message sender receipt to retain signed code-mode agentattribution. All other operations use the caller receipt so attribution cannotdiff --git a/crates/messages/src/inbound/axum_router.rs b/crates/messages/src/inbound/axum_router.rsindex d39808b15f..9b17056fff 100644--- a/crates/messages/src/inbound/axum_router.rs+++ b/crates/messages/src/inbound/axum_router.rs@@ -11,7 +11,8 @@ use entity_access::domain::{ports::EntityAccessService,};use macro_authorization::{- AnyPrincipal, MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,+ AnyPrincipal, MacroAuthorization, MacroAuthorizationExtractor, MacroAuthorizationService,+ MacroAuthorizationState,};use serde::{Deserialize, Serialize};use std::sync::Arc;@@ -239,12 +240,13 @@ pub async fn create<A, Auth>(State(state): State<MessagesRouterState<A, Auth>>,user: MacroAuthorizationExtractor<Auth, AnyPrincipal>,Path(path): Path<ParentPath>,- Json(input): Json<PostMessage>,+ Json(mut input): Json<PostMessage>,) -> Result<Json<Message>, MessageHttpError>whereA: EntityAccessService,Auth: MacroAuthorizationService,{+ input.attribution = sender_attribution(&user.authorization);Ok(Json(state.service@@ -256,6 +258,24 @@ where))}+/// How a new message's signed agent attribution labels it: with the client a+/// user drives the agent through, when the credential names one.+/// Only a user credential carries one; it is set only alongside `agent_id`.+fn sender_attribution(principal: &MacroAuthorization) -> MessageAttribution {+ let via = match principal {+ MacroAuthorization::User(user) => user.agent_via.as_ref(),+ MacroAuthorization::Bot(_)+ | MacroAuthorization::Harness(_)+ | MacroAuthorization::Internal(_) => None,+ };+ match via {+ Some(client) => MessageAttribution::ActingUserVia {+ client: client.clone(),+ },+ None => MessageAttribution::ActingUser,+ }+}+#[utoipa::path(operation_id = "entity_message_get_message", get, path = "/messages/{parent_type}/{parent_id}/items/{id}", params(("parent_type" = String, Path), ("parent_id" = String, Path), ("id" = Uuid, Path)), responses((status = 200, body = Message)))]/// Resolve a message within its parent.pub async fn get_message<A, Auth>(diff --git a/crates/messages/src/outbound/notification_sender.rs b/crates/messages/src/outbound/notification_sender.rsindex adf17f786d..8724386f80 100644--- a/crates/messages/src/outbound/notification_sender.rs+++ b/crates/messages/src/outbound/notification_sender.rs@@ -19,11 +19,19 @@ pub struct MessageNotificationSender<N>(pub std::sync::Arc<N>);impl<N: NotificationIngress> DiscussionNotifier for MessageNotificationSender<N> {async fn send(&self, n: DiscussionNotification<'_>) -> Result<(), rootcause::Report> {let sender_id = n.message.sender_id.as_user().cloned();+ // A bot post a user made through a client, such as an MCP client, is+ // named after that client.let sender_display_name = n.message- .bot_profile- .as_ref()- .map(|profile| profile.name.clone())+ .sender_id+ .as_bot()+ .and(n.message.triggered_via.clone())+ .or_else(|| {+ n.message+ .bot_profile+ .as_ref()+ .map(|profile| profile.name.clone())+ }).or_else(|| n.message.sender_id.as_bot().map(|_| "Agent".to_owned()));let recipient_ids =std::collections::HashSet::from([MacroUserIdStr::try_from(n.recipient)?]);diff --git a/crates/projects/src/inbound/axum_router/tests.rs b/crates/projects/src/inbound/axum_router/tests.rsindex 343f4899d6..066437335e 100644--- a/crates/projects/src/inbound/axum_router/tests.rs+++ b/crates/projects/src/inbound/axum_router/tests.rs@@ -458,6 +458,7 @@ impl MacroAuthorizationService for FakeAuthorizationService {.map(|user_id| MacroUserAuthentication {origin: macro_authorization::CredentialOrigin::Bot,agent_id: None,+ agent_via: None,macro_user_id: user(&user_id),user_context: user_context(&user_id),}),diff --git a/crates/properties/src/inbound/axum_router/test.rs b/crates/properties/src/inbound/axum_router/test.rsindex 6a7df38893..a6f57a516c 100644--- a/crates/properties/src/inbound/axum_router/test.rs+++ b/crates/properties/src/inbound/axum_router/test.rs@@ -230,6 +230,7 @@ impl JwtValidator for FakeJwtValidator {origin: macro_authorization::CredentialOrigin::Session,identity: ValidatedIdentity {agent_id: None,+ agent_via: None,user_id: VALID_USER_ID.to_string(),fusion_user_id: "fusion-valid-user".to_string(),organization_id: Some(ORGANIZATION_ID),diff --git a/crates/scheduled_action/src/inbound/axum_router/test.rs b/crates/scheduled_action/src/inbound/axum_router/test.rsindex 3c8eca37c2..11c4820c84 100644--- a/crates/scheduled_action/src/inbound/axum_router/test.rs+++ b/crates/scheduled_action/src/inbound/axum_router/test.rs@@ -162,6 +162,7 @@ impl MacroAuthorizationService for FakeAuth {let macro_user_id = MacroUserIdStr::try_from(user_id).expect("acting user id");MacroUserAuthentication {agent_id: None,+ agent_via: None,origin: macro_authorization::CredentialOrigin::Bot,user_context: UserContext {user_id: macro_user_id.to_string(),diff --git a/crates/webhook/src/inbound/axum_router/test.rs b/crates/webhook/src/inbound/axum_router/test.rsindex e1977bfbed..107fa6ac70 100644--- a/crates/webhook/src/inbound/axum_router/test.rs+++ b/crates/webhook/src/inbound/axum_router/test.rs@@ -125,6 +125,7 @@ impl MacroAuthorizationService for FakeAuthorizationService {.map(|user_id| macro_authorization::MacroUserAuthentication {origin: macro_authorization::CredentialOrigin::Bot,agent_id: None,+ agent_via: None,macro_user_id: MacroUserIdStr::try_from(user_id).unwrap(),user_context: UserContext::default(),});diff --git a/crates/whatsapp_linked/src/inbound/router/test/http.rs b/crates/whatsapp_linked/src/inbound/router/test/http.rsindex 62d4dc7d53..753f8b221e 100644--- a/crates/whatsapp_linked/src/inbound/router/test/http.rs+++ b/crates/whatsapp_linked/src/inbound/router/test/http.rs@@ -68,6 +68,7 @@ fn acting(user: &str, origin: CredentialOrigin) -> MacroUserAuthentication {MacroUserAuthentication {origin,agent_id: None,+ agent_via: None,macro_user_id: user.to_owned().try_into().unwrap(),user_context: context(user),}@@ -101,6 +102,7 @@ impl MacroAuthorizationService for Credentials {Ok(ValidatedCredential {identity: ValidatedIdentity {agent_id: None,+ agent_via: None,user_id: user.to_owned(),fusion_user_id: "fusion-user-id".to_owned(),organization_id: None,diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.mdindex 3bc19bea43..8d226af129 100644--- a/docs/agent-guide/channels.md+++ b/docs/agent-guide/channels.md@@ -328,14 +328,17 @@ verify that its tool response includes the matching attachment URLs.## Messages sent through an MCP client-A message a user's MCP client (Claude Code, Cursor, ChatGPT) sends through-Macro MCP's `SendChannelMessage` is posted by the Macro bot with a-**from <user> via <client>** pill under the sender name, where the client is the-name it registered with Macro's OAuth broker. A self-hosted agent's message-shows the agent as the sender with **from <user>**, and a message sent with a-pasted Macro API key shows the Macro bot with **from <user>**. To check this,-connect an MCP client over OAuth, ask it to post in a channel, and confirm the-pill names both you and the client on desktop and at phone width.+A message, comment, or thread reply a user's MCP client (Claude Code, Cursor,+ChatGPT) posts through Macro MCP, with a direct tool such as+`SendChannelMessage` or from code mode (`ExecuteCode`), shows the client as its+sender: **Claude Code · Agent** with the client's initial as its avatar and a+**from <user>** pill underneath. The client is the name it registered with+Macro's OAuth broker, or "MCP client" if it registered none. Notifications name+the client as the sender too. A self-hosted agent's message shows the agent as+the sender with **from <user>**, and a message sent with a pasted Macro API key+shows the Macro bot with **from <user>**. To check this, connect an MCP client+over OAuth, ask it to post in a channel and to comment on a document, and+confirm both show the client and the user on desktop and at phone width.## Message composerdiff --git a/services/agent_harness_service/AGENTS.md b/services/agent_harness_service/AGENTS.mdindex 746794b43a..347d39afb7 100644--- a/services/agent_harness_service/AGENTS.md+++ b/services/agent_harness_service/AGENTS.md@@ -147,9 +147,11 @@ listener failure shuts down the process so ECS can replace the task.(`mcp_auth_proxy`) attached, and a call without one is refused: `Agent` (aMacro API token's signed `agent_id`, which egress mints from the session's`agent_session.bot_id`) writes as that agent; `McpClient` (OAuth) writes as- the Macro bot labelled "via <client name>"; `ApiKey` writes as the Macro bot.- Public `ExecuteCode` builds its context per call from the caller and signs an- agent caller into its SDK token. Never read a bot id from the request itself.+ the Macro bot labelled with the client's name (shown as the author); `ApiKey`+ writes as the Macro bot. Public `ExecuteCode` builds its context per call from+ the caller and signs the same attribution into its SDK token: the agent, or+ the Macro bot plus the client name as `agent_via`. Never read a bot id or+ client name from the request itself.- The public MCP server is stateless, so tool calls carry no `clientInfo`; theclient is identified per call by its `User-Agent` / `x-anthropic-client`headers and per session by `$mcp_initialize`.diff --git a/services/agent_harness_service/src/code_mode.rs b/services/agent_harness_service/src/code_mode.rsindex 54c00d90fe..5ead190153 100644--- a/services/agent_harness_service/src/code_mode.rs+++ b/services/agent_harness_service/src/code_mode.rs@@ -29,7 +29,7 @@ impl ExecutionCredentials for RunCredentials {// clock margin; a normal user token expires rather than revoking on exit.let token = self.signer- .mint_for_agent(&actor, 60, Some(identity.agent_id.as_uuid()))+ .mint_for_agent(&actor, 60, Some(identity.agent_id.as_uuid()), None).await.map_err(|error| {tracing::error!(?error, "could not mint execution credential");@@ -46,9 +46,11 @@ impl ExecutionCredentials for RunCredentials {}/// Credentials for public MCP runs: the signed-in user, with no session, and-/// for an agent caller (a self-hosted agent's call through egress) that agent.-/// The MCP client asks the user before each tool call, so there is no owner-/// gate.+/// the agent the run's posts are attributed to: an agent caller (a self-hosted+/// agent's call through egress) as itself, any other caller as the Macro bot,+/// labelled with the MCP client's name - the same attribution the direct MCP+/// tools give. The MCP client asks the user before each tool call, so there is+/// no owner gate.pub struct UserRunCredentials {pub signer: MacroApiTokenSigner,pub hosts: BTreeMap<String, String>,@@ -62,13 +64,20 @@ impl UserExecutionCredentials for UserRunCredentials {caller: &ai_toolset::ToolCaller,) -> Result<RunEnvironment, CodeModeError> {let agent = match caller {- ai_toolset::ToolCaller::Agent(agent) => Some(agent.as_uuid()),- ai_toolset::ToolCaller::McpClient { .. } | ai_toolset::ToolCaller::ApiKey => None,+ ai_toolset::ToolCaller::Agent(agent) => *agent,+ ai_toolset::ToolCaller::McpClient { .. } | ai_toolset::ToolCaller::ApiKey => {+ bot_id::MACRO_AI_BOT_ID+ }};// Same lifetime as session runs: the 30-second deadline plus clock margin.let token = self.signer- .mint_for_agent(user, 60, agent)+ .mint_for_agent(+ user,+ 60,+ Some(agent.as_uuid()),+ caller.via().map(str::to_owned),+ ).await.map_err(|error| {tracing::error!(?error, "could not mint execution credential");diff --git a/services/authentication_service/src/api/jwt/macro_api_token.rs b/services/authentication_service/src/api/jwt/macro_api_token.rsindex e0d64fffba..50f011a09f 100644--- a/services/authentication_service/src/api/jwt/macro_api_token.rs+++ b/services/authentication_service/src/api/jwt/macro_api_token.rs@@ -94,6 +94,7 @@ pub async fn handler(.user.agent_id.map(|agent| agent.as_uuid()),+ agent_via: authorization.authorization.user.agent_via.clone(),macro_user_id,fusionauth_id: user_context.fusion_user_id.clone(),organization_id, // TOOD: get from user profile