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(mcp): attribute public MCP writes to their agent or MCP client (#8978)

Wolf Mermelstein2918d7a26345
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 84d53cfbab..b2de458403 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -2123,6 +2123,7 @@
],
"ai_toolset": [
"crates/ai_toolset",
+ "crates/bot_id",
"crates/cowlike",
"crates/genai_telemetry",
"crates/macro_env_var",
@@ -9951,8 +9952,11 @@
"crates/maybe_send"
],
"mcp_auth_proxy": [
+ "crates/ai_toolset",
+ "crates/bot_id",
"crates/cowlike",
"crates/fusionauth",
+ "crates/genai_telemetry",
"crates/macro_auth",
"crates/macro_env",
"crates/macro_env_var",
@@ -10020,6 +10024,7 @@
],
"mcp_toolset": [
"crates/ai_toolset",
+ "crates/bot_id",
"crates/cowlike",
"crates/genai_telemetry",
"crates/macro_env_var",
diff --git a/.sqlx/query-e154aa110e27cd6530da2cd4e351297414734882c695aa323c7c8a6e46333711.json b/.sqlx/query-c2cb747ab09bc415cb01318a733b986c55ad2b28b7986cd66b402d343ed8df31.json
similarity index 61%
rename from .sqlx/query-e154aa110e27cd6530da2cd4e351297414734882c695aa323c7c8a6e46333711.json
rename to .sqlx/query-c2cb747ab09bc415cb01318a733b986c55ad2b28b7986cd66b402d343ed8df31.json
index 549798adbb..05e69d0af7 100644
--- a/.sqlx/query-e154aa110e27cd6530da2cd4e351297414734882c695aa323c7c8a6e46333711.json
+++ b/.sqlx/query-c2cb747ab09bc415cb01318a733b986c55ad2b28b7986cd66b402d343ed8df31.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "INSERT INTO comms_messages(id, parent_entity_type, parent_entity_id, thread_id,\n sender_id, triggered_by_user_id, content, client_message_id, guest_name)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)",
+ "query": "INSERT INTO comms_messages(id, parent_entity_type, parent_entity_id, thread_id,\n sender_id, triggered_by_user_id, triggered_via, content, client_message_id,\n guest_name)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",
"describe": {
"columns": [],
"parameters": {
@@ -12,11 +12,12 @@
"Text",
"Text",
"Text",
+ "Text",
"Uuid",
"Text"
]
},
"nullable": []
},
- "hash": "e154aa110e27cd6530da2cd4e351297414734882c695aa323c7c8a6e46333711"
+ "hash": "c2cb747ab09bc415cb01318a733b986c55ad2b28b7986cd66b402d343ed8df31"
}
diff --git a/Cargo.lock b/Cargo.lock
index a5d8661ba1..bd07e2eb75 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -351,6 +351,7 @@ dependencies = [
"axum",
"axum-extra",
"base64 0.22.1",
+ "bot_id",
"bytes",
"chrono",
"futures",
@@ -1242,6 +1243,7 @@ dependencies = [
"async-trait",
"axum",
"axum-macros",
+ "bot_id",
"genai_telemetry",
"macro_user_id",
"opentelemetry",
@@ -12555,9 +12557,11 @@ version = "0.1.0"
name = "mcp_auth_proxy"
version = "0.1.0"
dependencies = [
+ "ai_toolset",
"anyhow",
"axum",
"base64 0.22.1",
+ "bot_id",
"fusionauth",
"macro_auth",
"macro_user_id",
diff --git a/apps/web/src/features/channel/Message/FromPill.tsx b/apps/web/src/features/channel/Message/FromPill.tsx
index 08425b1ba4..09ded96a5a 100644
--- a/apps/web/src/features/channel/Message/FromPill.tsx
+++ b/apps/web/src/features/channel/Message/FromPill.tsx
@@ -10,8 +10,10 @@ 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`).
- * 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`), 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.
*/
export function FromPill(props: FromPillProps) {
const message = useMessage();
@@ -26,6 +28,7 @@ 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()}>
@@ -50,6 +53,14 @@ 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/lib/queries/messages/message-sender.ts b/apps/web/src/lib/queries/messages/message-sender.ts
index 1416b1f6f7..8785ae5723 100644
--- a/apps/web/src/lib/queries/messages/message-sender.ts
+++ b/apps/web/src/lib/queries/messages/message-sender.ts
@@ -16,6 +16,7 @@ type WithMaybeSender<
sender?: MessageSender;
bot_profile?: { name: string; avatar_url?: string | null } | null;
triggered_by?: string | null;
+ triggered_via?: string | null;
},
> = Omit<T, 'sender'> & { sender?: MessageSender };
@@ -69,6 +70,7 @@ export function normalizeMessageSender<
sender?: MessageSender;
bot_profile?: { name: string; avatar_url?: string | null } | null;
triggered_by?: string | null;
+ triggered_via?: string | null;
},
>(message: T): T & { sender: MessageSender } {
return message.sender
@@ -79,6 +81,7 @@ export function normalizeMessageSender<
...senderFromStorageId(message.sender_id),
...message.bot_profile,
triggered_by: message.triggered_by,
+ triggered_via: message.triggered_via,
},
};
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index 438708f9f1..a4c4b11551 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -1424,6 +1424,7 @@ export * from './messageTimelineQueryAround';
export * from './messageTimelineQueryCursor';
export * from './messageTimelineQueryLimit';
export * from './messageTriggeredBy';
+export * from './messageTriggeredVia';
export * from './myResponse';
export * from './newAttachment';
export * from './newAttachmentHeight';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/message.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/message.ts
index e35cf2c49f..d3995784ea 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/message.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/message.ts
@@ -15,6 +15,7 @@ import type { MessageImportedAuthor } from './messageImportedAuthor';
import type { MessageParent } from './messageParent';
import type { MessageThreadId } from './messageThreadId';
import type { MessageTriggeredBy } from './messageTriggeredBy';
+import type { MessageTriggeredVia } from './messageTriggeredVia';
import type { SimpleMention } from './simpleMention';
/**
@@ -49,6 +50,9 @@ export interface Message {
thread_id?: MessageThreadId;
/** User who triggered a bot-authored message. */
triggered_by?: MessageTriggeredBy;
+ /** Self-reported name of the client the user triggered it through, such
+as "Claude Code"; a display label only. */
+ triggered_via?: MessageTriggeredVia;
/** Last persisted update. */
updated_at: string;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/messageTriggeredVia.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/messageTriggeredVia.ts
new file mode 100644
index 0000000000..87a8a8d638
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/messageTriggeredVia.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Self-reported name of the client the user triggered it through, such
+as "Claude Code"; a display label only.
+ */
+export type MessageTriggeredVia = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index fb47dc85e0..d029017ec1 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -50219,6 +50219,12 @@ export const messageTimelineResponse = zod
.string()
.nullish()
.describe('User who triggered a bot-authored message.'),
+ triggered_via: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Self-reported name of the client the user triggered it through, such\nas \"Claude Code\"; a display label only.'
+ ),
updated_at: zod.iso.datetime({}).describe('Last persisted update.'),
})
.describe(
@@ -50570,6 +50576,12 @@ export const messageTimelineResponse = zod
.describe(
'User who triggered a bot-authored message.'
),
+ triggered_via: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Self-reported name of the client the user triggered it through, such\nas \"Claude Code\"; a display label only.'
+ ),
updated_at: zod.iso
.datetime({})
.describe('Last persisted update.'),
@@ -50927,6 +50939,12 @@ export const entityMessageCreateResponse = zod
.string()
.nullish()
.describe('User who triggered a bot-authored message.'),
+ triggered_via: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Self-reported name of the client the user triggered it through, such\nas \"Claude Code\"; a display label only.'
+ ),
updated_at: zod.iso.datetime({}).describe('Last persisted update.'),
})
.describe(
@@ -51089,6 +51107,12 @@ export const entityMessageGetMessageResponse = zod
.string()
.nullish()
.describe('User who triggered a bot-authored message.'),
+ triggered_via: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Self-reported name of the client the user triggered it through, such\nas \"Claude Code\"; a display label only.'
+ ),
updated_at: zod.iso.datetime({}).describe('Last persisted update.'),
})
.describe(
@@ -51255,6 +51279,12 @@ export const entityMessageDeleteMessageResponse = zod
.string()
.nullish()
.describe('User who triggered a bot-authored message.'),
+ triggered_via: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Self-reported name of the client the user triggered it through, such\nas \"Claude Code\"; a display label only.'
+ ),
updated_at: zod.iso.datetime({}).describe('Last persisted update.'),
})
.describe(
@@ -51517,6 +51547,12 @@ export const entityMessageEditResponse = zod
.string()
.nullish()
.describe('User who triggered a bot-authored message.'),
+ triggered_via: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Self-reported name of the client the user triggered it through, such\nas \"Claude Code\"; a display label only.'
+ ),
updated_at: zod.iso.datetime({}).describe('Last persisted update.'),
})
.describe(
@@ -51687,6 +51723,12 @@ export const entityMessageReactResponse = zod
.string()
.nullish()
.describe('User who triggered a bot-authored message.'),
+ triggered_via: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Self-reported name of the client the user triggered it through, such\nas \"Claude Code\"; a display label only.'
+ ),
updated_at: zod.iso.datetime({}).describe('Last persisted update.'),
})
.describe(
@@ -51856,6 +51898,12 @@ export const entityMessageLegacyResponse = zod
.string()
.nullish()
.describe('User who triggered a bot-authored message.'),
+ triggered_via: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Self-reported name of the client the user triggered it through, such\nas \"Claude Code\"; a display label only.'
+ ),
updated_at: zod.iso.datetime({}).describe('Last persisted update.'),
})
.describe(
@@ -52045,6 +52093,12 @@ export const entityMessageGetThreadResponse = zod
.string()
.nullish()
.describe('User who triggered a bot-authored message.'),
+ triggered_via: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Self-reported name of the client the user triggered it through, such\nas \"Claude Code\"; a display label only.'
+ ),
updated_at: zod.iso.datetime({}).describe('Last persisted update.'),
})
.describe(
@@ -52210,6 +52264,12 @@ export const entityMessageGetThreadResponse = zod
.string()
.nullish()
.describe('User who triggered a bot-authored message.'),
+ triggered_via: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Self-reported name of the client the user triggered it through, such\nas \"Claude Code\"; a display label only.'
+ ),
updated_at: zod.iso.datetime({}).describe('Last persisted update.'),
})
.describe(
@@ -52810,6 +52870,12 @@ export const messageTimelineEntriesResponse = zod
.string()
.nullish()
.describe('User who triggered a bot-authored message.'),
+ triggered_via: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Self-reported name of the client the user triggered it through, such\nas \"Claude Code\"; a display label only.'
+ ),
updated_at: zod.iso
.datetime({})
.describe('Last persisted update.'),
@@ -53185,6 +53251,12 @@ export const messageTimelineEntriesResponse = zod
.describe(
'User who triggered a bot-authored message.'
),
+ triggered_via: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Self-reported name of the client the user triggered it through, such\nas \"Claude Code\"; a display label only.'
+ ),
updated_at: zod.iso
.datetime({})
.describe('Last persisted update.'),
diff --git a/apps/web/src/lib/service-clients/service-storage/messages.ts b/apps/web/src/lib/service-clients/service-storage/messages.ts
index d7f31b93ee..23e20277e9 100644
--- a/apps/web/src/lib/service-clients/service-storage/messages.ts
+++ b/apps/web/src/lib/service-clients/service-storage/messages.ts
@@ -26,6 +26,8 @@ export type MessageSender = {
avatar_url?: string | null;
/** For an agent (bot) message, the id of the user who triggered it. */
triggered_by?: string | null;
+ /** The client the user triggered it through, such as "Claude Code". */
+ triggered_via?: string | null;
};
export type Message = StoredMessage & { sender?: MessageSender };
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index baba6916e3..54fa1cca4d 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -34953,6 +34953,10 @@
"type": ["string", "null"],
"description": "User who triggered a bot-authored message."
},
+ "triggered_via": {
+ "type": ["string", "null"],
+ "description": "Self-reported name of the client the user triggered it through, such\nas \"Claude Code\"; a display label only."
+ },
"updated_at": {
"type": "string",
"format": "date-time",
diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.json
index aa1ef3b73d..3e06024fa8 100644
--- a/crates/agent_code_mode/src/domain/documentation.json
+++ b/crates/agent_code_mode/src/domain/documentation.json
@@ -672,7 +672,7 @@
"storage.Meeting": "# Type Alias: Meeting\n\n> **Meeting** = \\{ `callId?`: `string` \\| `null`; `channelId?`: `string` \\| `null`; `id`: `string`; `scheduledEnd?`: `string` \\| `null`; `scheduledStart?`: `string` \\| `null`; `shareToken`: `MeetingToken`; `title`: `string`; \\}\n\nPersistent meeting metadata. No channel contents or archived media are exposed.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-callid\"></a> `callId?` | `string` \\| `null` | Currently active call session, if any. |\n| <a id=\"property-channelid\"></a> `channelId?` | `string` \\| `null` | Associated channel, for links to existing channel calls only. |\n| <a id=\"property-id\"></a> `id` | `string` | Persistent meeting identifier. |\n| <a id=\"property-scheduledend\"></a> `scheduledEnd?` | `string` \\| `null` | Scheduled end, or none for an instant meeting. |\n| <a id=\"property-scheduledstart\"></a> `scheduledStart?` | `string` \\| `null` | Scheduled start, or none for an instant meeting. |\n| <a id=\"property-sharetoken\"></a> `shareToken` | `MeetingToken` | Bearer capability embedded in the invitation URL. |\n| <a id=\"property-title\"></a> `title` | `string` | Human-readable meeting title. |",
"MeetingInvitePermissions": "# Type Alias: MeetingInvitePermissions\n\n> **MeetingInvitePermissions** = \\{ `canInvite`: `boolean`; \\}\n\nWhether the authenticated caller can invite teammates to this meeting.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-caninvite\"></a> `canInvite` | `boolean` | True for the owner of an uncancelled standalone meeting. |",
"MeetingToken": "# Type Alias: MeetingToken\n\n> **MeetingToken** = `string`\n\nAn invitation capability for joining a meeting's RTC room. Chat additionally\nrequires the resulting participant credential and current guest membership.",
- "storage.Message": "# Type Alias: Message\n\n> **Message** = \\{ `attachments`: `MessageAttachment`[]; `bot_profile?`: `null` \\| `BotSenderProfile`; `content`: `string`; `created_at`: `string`; `deleted_at?`: `string` \\| `null`; `edited_at?`: `string` \\| `null`; `guest_name?`: `string` \\| `null`; `id`: `string`; `imported_author?`: `null` \\| `ImportedAuthor`; `mentions`: `SimpleMention`[]; `parent`: `storage.MessageParent`; `reactions`: `CountedReaction`[]; `sender_id`: `string`; `thread_id?`: `string` \\| `null`; `triggered_by?`: `string` \\| `null`; `updated_at`: `string`; \\}\n\nShared message representation for channel timelines and entity discussions.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments` | `MessageAttachment`[] | Attached entities. |\n| <a id=\"property-bot_profile\"></a> `bot_profile?` | `null` \\| `BotSenderProfile` | - |\n| <a id=\"property-content\"></a> `content` | `string` | Macro Markdown body. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Creation time. |\n| <a id=\"property-deleted_at\"></a> `deleted_at?` | `string` \\| `null` | Message tombstone, independent of thread deletion. |\n| <a id=\"property-edited_at\"></a> `edited_at?` | `string` \\| `null` | Last content edit, if any. |\n| <a id=\"property-guest_name\"></a> `guest_name?` | `string` \\| `null` | Display name of a verified call guest, retained after the call ends. |\n| <a id=\"property-id\"></a> `id` | `string` | Message UUID. |\n| <a id=\"property-imported_author\"></a> `imported_author?` | `null` \\| `ImportedAuthor` | - |\n| <a id=\"property-mentions\"></a> `mentions` | `SimpleMention`[] | Tracked mentions, retained when a caller changes attachments only. |\n| <a id=\"property-parent\"></a> `parent` | `storage.MessageParent` | Entity that owns this conversation. |\n| <a id=\"property-reactions\"></a> `reactions` | `CountedReaction`[] | Aggregated reactions. |\n| <a id=\"property-sender_id\"></a> `sender_id` | `string` | Authenticated actor or owner of imported content. |\n| <a id=\"property-thread_id\"></a> `thread_id?` | `string` \\| `null` | Root message UUID for replies; absent on roots. |\n| <a id=\"property-triggered_by\"></a> `triggered_by?` | `string` \\| `null` | User who triggered a bot-authored message. |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | Last persisted update. |",
+ "storage.Message": "# Type Alias: Message\n\n> **Message** = \\{ `attachments`: `MessageAttachment`[]; `bot_profile?`: `null` \\| `BotSenderProfile`; `content`: `string`; `created_at`: `string`; `deleted_at?`: `string` \\| `null`; `edited_at?`: `string` \\| `null`; `guest_name?`: `string` \\| `null`; `id`: `string`; `imported_author?`: `null` \\| `ImportedAuthor`; `mentions`: `SimpleMention`[]; `parent`: `storage.MessageParent`; `reactions`: `CountedReaction`[]; `sender_id`: `string`; `thread_id?`: `string` \\| `null`; `triggered_by?`: `string` \\| `null`; `triggered_via?`: `string` \\| `null`; `updated_at`: `string`; \\}\n\nShared message representation for channel timelines and entity discussions.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments` | `MessageAttachment`[] | Attached entities. |\n| <a id=\"property-bot_profile\"></a> `bot_profile?` | `null` \\| `BotSenderProfile` | - |\n| <a id=\"property-content\"></a> `content` | `string` | Macro Markdown body. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Creation time. |\n| <a id=\"property-deleted_at\"></a> `deleted_at?` | `string` \\| `null` | Message tombstone, independent of thread deletion. |\n| <a id=\"property-edited_at\"></a> `edited_at?` | `string` \\| `null` | Last content edit, if any. |\n| <a id=\"property-guest_name\"></a> `guest_name?` | `string` \\| `null` | Display name of a verified call guest, retained after the call ends. |\n| <a id=\"property-id\"></a> `id` | `string` | Message UUID. |\n| <a id=\"property-imported_author\"></a> `imported_author?` | `null` \\| `ImportedAuthor` | - |\n| <a id=\"property-mentions\"></a> `mentions` | `SimpleMention`[] | Tracked mentions, retained when a caller changes attachments only. |\n| <a id=\"property-parent\"></a> `parent` | `storage.MessageParent` | Entity that owns this conversation. |\n| <a id=\"property-reactions\"></a> `reactions` | `CountedReaction`[] | Aggregated reactions. |\n| <a id=\"property-sender_id\"></a> `sender_id` | `string` | Authenticated actor or owner of imported content. |\n| <a id=\"property-thread_id\"></a> `thread_id?` | `string` \\| `null` | Root message UUID for replies; absent on roots. |\n| <a id=\"property-triggered_by\"></a> `triggered_by?` | `string` \\| `null` | User who triggered a bot-authored message. |\n| <a id=\"property-triggered_via\"></a> `triggered_via?` | `string` \\| `null` | Self-reported name of the client the user triggered it through, such as \"Claude Code\"; a display label only. |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | Last persisted update. |",
"MessageAttachment": "# Type Alias: MessageAttachment\n\n> **MessageAttachment** = \\{ `created_at`: `string`; `entity_id`: `string`; `entity_type`: `string`; `height?`: `number` \\| `null`; `id`: `string`; `width?`: `number` \\| `null`; \\}\n\nAn entity attached to a message.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | When the attachment was added. |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Attached entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | `string` | Attached entity type. |\n| <a id=\"property-height\"></a> `height?` | `number` \\| `null` | Optional media height. |\n| <a id=\"property-id\"></a> `id` | `string` | Attachment UUID. |\n| <a id=\"property-width\"></a> `width?` | `number` \\| `null` | Optional media width. |",
"MessageCursor": "# Type Alias: MessageCursor\n\n> **MessageCursor** = \\{ `created_at`: `string`; `id`: `string`; \\}\n\nCursor for a chronological parent timeline.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Last message creation time or activity occurrence time. |\n| <a id=\"property-id\"></a> `id` | `string` | Last entry UUID, used to break timestamp ties across both sources. |",
"MessageDirection": "# Type Alias: MessageDirection\n\n> **MessageDirection** = `\"older\"` \\| `\"newer\"`\n\nDirection through a parent timeline, retaining channel cursor semantics.",
diff --git a/crates/agent_code_mode/src/domain/user.rs b/crates/agent_code_mode/src/domain/user.rs
index a25e835125..74eb36c1f1 100644
--- a/crates/agent_code_mode/src/domain/user.rs
+++ b/crates/agent_code_mode/src/domain/user.rs
@@ -3,6 +3,7 @@ use super::{
CodeModeError, ExecutionActivity, ExecutionStatus,
service::{Reviews, settle, validate_request},
};
+use ai_toolset::ToolCaller;
use async_trait::async_trait;
use code_execution::domain::{ExecuteRequest, ProgramExecutor, RunEnvironment};
use macro_user_id::user_id::MacroUserIdStr;
@@ -15,8 +16,13 @@ use tokio_util::sync::CancellationToken;
/// Mint a short-lived credential for the user a run acts as.
#[async_trait]
pub trait UserExecutionCredentials: Send + Sync + 'static {
- /// The user comes from the authenticated request, never from generated code.
- async fn issue(&self, user: &MacroUserIdStr<'static>) -> Result<RunEnvironment, CodeModeError>;
+ /// The user and caller come from the authenticated request, never from
+ /// generated code; an agent caller's SDK writes are attributed to it.
+ async fn issue(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ caller: &ToolCaller,
+ ) -> Result<RunEnvironment, CodeModeError>;
}
/// Outcome returned straight to the caller; nothing is persisted.
@@ -43,6 +49,7 @@ pub trait UserCodeMode: Send + Sync + 'static {
async fn execute(
&self,
user: &MacroUserIdStr<'static>,
+ caller: &ToolCaller,
request: ExecuteRequest,
cancel: CancellationToken,
) -> Result<UserExecutionReceipt, CodeModeError>;
@@ -83,11 +90,12 @@ impl UserCodeMode for UserCodeModeService {
async fn execute(
&self,
user: &MacroUserIdStr<'static>,
+ caller: &ToolCaller,
request: ExecuteRequest,
cancel: CancellationToken,
) -> Result<UserExecutionReceipt, CodeModeError> {
validate_request(&request)?;
- let environment = self.credentials.issue(user).await?;
+ let environment = self.credentials.issue(user, caller).await?;
let (progress, mut updates) = tokio::sync::mpsc::channel(512);
let execution = self.executor.execute_program_with_progress(
request,
diff --git a/crates/agent_code_mode/src/domain/user/test.rs b/crates/agent_code_mode/src/domain/user/test.rs
index a330cf425c..87dfc490f7 100644
--- a/crates/agent_code_mode/src/domain/user/test.rs
+++ b/crates/agent_code_mode/src/domain/user/test.rs
@@ -4,11 +4,18 @@ use serde_json::json;
use std::sync::Mutex;
#[derive(Default)]
-struct Credentials(Mutex<Vec<String>>);
+struct Credentials(Mutex<Vec<(String, ToolCaller)>>);
#[async_trait]
impl UserExecutionCredentials for Credentials {
- async fn issue(&self, user: &MacroUserIdStr<'static>) -> Result<RunEnvironment, CodeModeError> {
- self.0.lock().unwrap().push(user.to_string());
+ async fn issue(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ caller: &ToolCaller,
+ ) -> Result<RunEnvironment, CodeModeError> {
+ self.0
+ .lock()
+ .unwrap()
+ .push((user.to_string(), caller.clone()));
Ok(RunEnvironment {
token: "run-only-secret".into(),
..Default::default()
@@ -68,8 +75,11 @@ async fn runs_as_the_authenticated_user_and_returns_data_with_activity() {
let service =
UserCodeModeService::new(Arc::new(Returns(json!({"data": 42}))), credentials.clone());
+ let caller = ToolCaller::Agent(bot_id::BotId::new_from_uuid(macro_uuid::Uuid::from_u128(
+ 0xA1,
+ )));
let receipt = service
- .execute(&user(), request(), CancellationToken::new())
+ .execute(&user(), &caller, request(), CancellationToken::new())
.await
.unwrap();
@@ -84,7 +94,7 @@ async fn runs_as_the_authenticated_user_and_returns_data_with_activity() {
);
assert_eq!(
*credentials.0.lock().unwrap(),
- ["macro|[email protected]"]
+ [("macro|[email protected]".to_owned(), caller)]
);
}
@@ -98,7 +108,12 @@ async fn review_references_fail_outside_a_session() {
);
let receipt = service
- .execute(&user(), request(), CancellationToken::new())
+ .execute(
+ &user(),
+ &ToolCaller::ApiKey,
+ request(),
+ CancellationToken::new(),
+ )
.await
.unwrap();
@@ -124,7 +139,12 @@ async fn invalid_requests_are_rejected_before_minting_a_credential() {
] {
assert!(matches!(
service
- .execute(&user(), request, CancellationToken::new())
+ .execute(
+ &user(),
+ &ToolCaller::ApiKey,
+ request,
+ CancellationToken::new()
+ )
.await,
Err(CodeModeError::Invalid(_))
));
@@ -140,7 +160,12 @@ async fn an_empty_reviews_list_is_dropped() {
);
let receipt = service
- .execute(&user(), request(), CancellationToken::new())
+ .execute(
+ &user(),
+ &ToolCaller::ApiKey,
+ request(),
+ CancellationToken::new(),
+ )
.await
.unwrap();
diff --git a/crates/agent_code_mode/src/inbound/toolset.rs b/crates/agent_code_mode/src/inbound/toolset.rs
index c8410c595d..9dba5aba41 100644
--- a/crates/agent_code_mode/src/inbound/toolset.rs
+++ b/crates/agent_code_mode/src/inbound/toolset.rs
@@ -46,6 +46,9 @@ pub struct UserCodeModeToolContext {
pub service: Arc<dyn UserCodeMode>,
/// Jev, for selecting documentation by task; absent falls back to the catalog.
pub cognition: Option<Arc<dyn Cognition>>,
+ /// Who the authenticated request came from; the adapter builds a context
+ /// per call, so there is no default.
+ pub caller: ai_toolset::ToolCaller,
}
/// Code mode for clients outside agent sessions, such as the public MCP.
@@ -184,6 +187,7 @@ impl AsyncTool<UserCodeModeToolContext> for UserExecuteCode {
.service
.execute(
&request.user_id,
+ &context.caller,
ExecuteRequest {
source: self.source.clone(),
timeout_ms: self.timeout_ms,
diff --git a/crates/agent_egress/AGENTS.md b/crates/agent_egress/AGENTS.md
index 598285eca2..e0f76dc70f 100644
--- a/crates/agent_egress/AGENTS.md
+++ b/crates/agent_egress/AGENTS.md
@@ -56,8 +56,11 @@ retain their existing session/repository identities.
- `cargo test -p agent_egress` (`SQLX_OFFLINE` unset).
-Code-mode minting attaches the session agent to a short-lived selected-user token;
-ordinary MCP owner tokens omit agent attribution.
+Session-egress Macro API tokens (`MacroApiTokens::mint`) carry the session's
+bound agent (`agent_session.bot_id`, read off the row as `SessionGrant.agent`) as
+their signed `agent_id` claim, so Macro's tools write as that agent. The bot
+never comes from the request. `MacroApiTokenSigner::mint_for_agent` callers
+(code mode) choose the claim themselves; `mint_for` signs none.
## Gotchas
diff --git a/crates/agent_egress/Cargo.toml b/crates/agent_egress/Cargo.toml
index 9b319c6118..b366137d01 100644
--- a/crates/agent_egress/Cargo.toml
+++ b/crates/agent_egress/Cargo.toml
@@ -18,6 +18,8 @@ axum = { workspace = true }
# session-token extraction would otherwise hand-roll.
axum-extra = { workspace = true, features = ["typed-header"] }
base64 = { workspace = true }
+# The session's agent, signed into Macro's own MCP credential.
+bot_id = { path = "../bot_id" }
bytes = { workspace = true }
# Holding a tool call for the owner: the stream it answers with.
futures = { workspace = true }
@@ -67,6 +69,7 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
anyhow = { workspace = true }
+bot_id = { path = "../bot_id", features = ["test-utils"] }
futures = { workspace = true }
# Building the stored OAuth grants the custom-server resolver reads.
rmcp = { workspace = true, features = ["auth"] }
diff --git a/crates/agent_egress/src/domain/model.rs b/crates/agent_egress/src/domain/model.rs
index 84d0953fbd..123f761239 100644
--- a/crates/agent_egress/src/domain/model.rs
+++ b/crates/agent_egress/src/domain/model.rs
@@ -237,6 +237,9 @@ pub struct SessionGrant {
pub session: AgentSessionId,
/// Whose connected servers it may reach.
pub owner: MacroUserIdStr<'static>,
+ /// The agent the session is bound to. Macro's own tools write as it,
+ /// never as a bot the sandbox names.
+ pub agent: bot_id::BotId,
/// The repository git egress is pinned to, if this session chose one.
pub repo: Option<RepoSlug>,
/// The apps the agent listed for this session, for naming only.
diff --git a/crates/agent_egress/src/domain/ports.rs b/crates/agent_egress/src/domain/ports.rs
index 21b68bf201..9013e2bb1d 100644
--- a/crates/agent_egress/src/domain/ports.rs
+++ b/crates/agent_egress/src/domain/ports.rs
@@ -39,6 +39,9 @@ pub trait SessionAuthority: Send + Sync {
/// OAuth.
pub trait McpCredentials: Send + Sync {
/// The upstream and credential for `destination`, on behalf of `owner`.
+ /// `agent` is the session's bound agent: Macro's own server signs it into
+ /// the credential so tool writes are attributed to it; connected and
+ /// custom servers ignore it.
///
/// Resolution is scoped to `owner`: a slug that names somebody else's
/// server is never somebody else's server. [`McpResolution::Connected`]
@@ -49,6 +52,7 @@ pub trait McpCredentials: Send + Sync {
fn resolve(
&self,
owner: &MacroUserIdStr<'static>,
+ agent: bot_id::BotId,
destination: &McpDestination,
) -> impl Future<Output = Result<McpResolution, EgressError>> + Send;
}
diff --git a/crates/agent_egress/src/domain/service.rs b/crates/agent_egress/src/domain/service.rs
index d22e3cf599..47ca00d73a 100644
--- a/crates/agent_egress/src/domain/service.rs
+++ b/crates/agent_egress/src/domain/service.rs
@@ -225,7 +225,7 @@ where
) => {
let (call, answer): (UpstreamCall, Option<Answer>) = match self
.credentials
- .resolve(&grant.owner, destination)
+ .resolve(&grant.owner, grant.agent, destination)
.await?
{
McpResolution::Connected(call) => (call, None),
diff --git a/crates/agent_egress/src/domain/service/actor.rs b/crates/agent_egress/src/domain/service/actor.rs
index 2985cccb1b..c6f8583fb4 100644
--- a/crates/agent_egress/src/domain/service/actor.rs
+++ b/crates/agent_egress/src/domain/service/actor.rs
@@ -68,7 +68,7 @@ where
(actor, user)
};
tracing::info!(session = %grant.session, ?actor, listing, "resolved MCP actor");
- let resolution = match self.credentials.resolve(user, destination).await {
+ let resolution = match self.credentials.resolve(user, grant.agent, destination).await {
Ok(resolution) => resolution,
Err(EgressError::UnknownCustomServer(_)) if !listing => return Ok(tool_result_response(id,
"This custom MCP server is not connected for the selected actor. Ask them to add or reconnect that server in Agents → Connections. Do not switch accounts unless they requested it.".into())),
diff --git a/crates/agent_egress/src/domain/service/test.rs b/crates/agent_egress/src/domain/service/test.rs
index 855f9d302a..8635da2014 100644
--- a/crates/agent_egress/src/domain/service/test.rs
+++ b/crates/agent_egress/src/domain/service/test.rs
@@ -4,6 +4,7 @@ use crate::domain::model::{
McpServerListing, McpServerSlug, ProxyBody, RepoSlug, SessionGrant, UpstreamCall,
UpstreamCredential,
};
+use bot_id::BotId;
use http::header::{AUTHORIZATION, HeaderMap, HeaderName, HeaderValue};
use http::{Method, StatusCode};
use http_body_util::{BodyExt, Empty, Full};
@@ -51,6 +52,7 @@ impl StubSessions {
Self(Ok(SessionGrant {
session: AgentSessionId::new(),
owner: owner(),
+ agent: BotId::TEST_A,
repo: Some(session_repo()),
mcp_servers: servers,
prompter: None,
@@ -89,6 +91,8 @@ enum Knowledge {
/// Records who it was asked about, and answers with a fixed upstream.
struct SpyCredentials {
asked: Mutex<Vec<(String, String)>>,
+ /// The agent each resolution was attributed to.
+ agents: Mutex<Vec<BotId>>,
known: Knowledge,
url: String,
scope: HeaderMap,
@@ -103,6 +107,7 @@ impl SpyCredentials {
fn at(url: &str) -> Self {
Self {
asked: Mutex::default(),
+ agents: Mutex::default(),
known: Knowledge::Connected,
url: url.to_owned(),
scope: HeaderMap::new(),
@@ -156,6 +161,7 @@ impl SpyCredentials {
fn empty() -> Self {
Self {
asked: Mutex::default(),
+ agents: Mutex::default(),
known: Knowledge::Unknown,
url: String::new(),
scope: HeaderMap::new(),
@@ -170,8 +176,10 @@ impl McpCredentials for SpyCredentials {
async fn resolve(
&self,
owner: &MacroUserIdStr<'static>,
+ agent: BotId,
destination: &McpDestination,
) -> Result<McpResolution, EgressError> {
+ self.agents.lock().expect("lock").push(agent);
let slug = match destination {
McpDestination::Connected(slug) => slug.clone(),
McpDestination::Preview => unreachable!("preview must never resolve owner credentials"),
@@ -885,6 +893,7 @@ async fn a_session_owned_outside_macro_is_proxied_with_its_owners_credentials()
StubSessions(Ok(SessionGrant {
session: AgentSessionId::new(),
owner: visitor.clone(),
+ agent: BotId::TEST_A,
repo: None,
mcp_servers: Vec::new(),
prompter: None,
@@ -1197,6 +1206,7 @@ async fn a_session_without_a_repository_can_use_mcp_but_cannot_mint_git_credenti
StubSessions(Ok(SessionGrant {
session: AgentSessionId::new(),
owner: owner(),
+ agent: BotId::TEST_A,
repo: None,
mcp_servers: Vec::new(),
prompter: None,
diff --git a/crates/agent_egress/src/domain/service/test/actor.rs b/crates/agent_egress/src/domain/service/test/actor.rs
index 438c06b241..1283c6aa95 100644
--- a/crates/agent_egress/src/domain/service/test/actor.rs
+++ b/crates/agent_egress/src/domain/service/test/actor.rs
@@ -215,3 +215,43 @@ async fn an_owner_approval_cannot_execute_after_the_original_turn_is_superseded(
assert_eq!(body_json(response).await["result"]["isError"], true);
assert!(!service.forward.was_called());
}
+
+/// Macro's own tools write as the agent the session row is bound to. A bot
+/// the agent names in its arguments never reaches the credential.
+#[tokio::test]
+async fn macro_tools_are_attributed_to_the_sessions_agent_not_one_the_caller_names() {
+ let StubSessions(Ok(mut grant)) = prompted_by(Some(asker())) else {
+ unreachable!("granting grants");
+ };
+ grant.agent = BotId::TEST_B;
+ let transport = Arc::new(ActorTransport::default());
+ let service =
+ gated(StubSessions(Ok(grant)), SpyCredentials::knowing()).with_actor_mcp(transport.clone());
+ let request = json_request(
+ &json!({"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"Comment","arguments":{
+ "acting_as":"requester",
+ "bot_id": BotId::TEST_A.to_string(),
+ "agent_id": BotId::TEST_A.to_string(),
+ }}})
+ .to_string(),
+ );
+
+ let response = service
+ .proxy(
+ &SessionToken::new("session"),
+ EgressTarget::McpServer(McpDestination::Macro),
+ request,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ body_json(response).await["result"]["content"][0]["text"],
+ "ok"
+ );
+ assert_eq!(*service.credentials.agents.lock().unwrap(), [BotId::TEST_B]);
+ assert_eq!(
+ service.credentials.asked.lock().unwrap()[0].0,
+ asker().to_string()
+ );
+}
diff --git a/crates/agent_egress/src/outbound/custom_mcp.rs b/crates/agent_egress/src/outbound/custom_mcp.rs
index 38cad2135f..9eef249abc 100644
--- a/crates/agent_egress/src/outbound/custom_mcp.rs
+++ b/crates/agent_egress/src/outbound/custom_mcp.rs
@@ -87,10 +87,11 @@ where
async fn resolve(
&self,
owner: &MacroUserIdStr<'static>,
+ agent: bot_id::BotId,
destination: &McpDestination,
) -> Result<McpResolution, EgressError> {
let McpDestination::Custom(key) = destination else {
- return self.inner.resolve(owner, destination).await;
+ return self.inner.resolve(owner, agent, destination).await;
};
// Unlike a Pipedream slug there is nothing to address without a row:
diff --git a/crates/agent_egress/src/outbound/custom_mcp/test.rs b/crates/agent_egress/src/outbound/custom_mcp/test.rs
index d7fddc47cd..2807c3f1ee 100644
--- a/crates/agent_egress/src/outbound/custom_mcp/test.rs
+++ b/crates/agent_egress/src/outbound/custom_mcp/test.rs
@@ -1,5 +1,6 @@
use super::*;
use crate::domain::model::{McpServerSlug, UpstreamCredential};
+use bot_id::BotId;
use mcp_client::domain::models::StoredCredentials;
use rmcp::transport::auth::OAuthTokenResponse;
use std::sync::Mutex;
@@ -27,6 +28,7 @@ impl McpCredentials for &SpyInner {
async fn resolve(
&self,
_owner: &MacroUserIdStr<'static>,
+ _agent: BotId,
destination: &McpDestination,
) -> Result<McpResolution, EgressError> {
let McpDestination::Connected(slug) = destination else {
@@ -136,7 +138,7 @@ async fn a_connected_server_resolves_to_its_url_with_the_owners_bearer() {
let credentials = WithCustomMcp::new(&inner, Arc::clone(&servers));
let McpResolution::Connected(call) = credentials
- .resolve(&owner(), &custom(WIKI))
+ .resolve(&owner(), BotId::TEST_A, &custom(WIKI))
.await
.expect("resolved")
else {
@@ -165,7 +167,7 @@ async fn a_server_with_no_account_resolves_anonymously() {
let credentials = WithCustomMcp::new(&inner, servers);
let McpResolution::Connected(call) = credentials
- .resolve(&owner(), &custom(WIKI))
+ .resolve(&owner(), BotId::TEST_A, &custom(WIKI))
.await
.expect("resolved")
else {
@@ -184,7 +186,7 @@ async fn a_dead_grant_is_reported_disconnected_by_name() {
let credentials = WithCustomMcp::new(&inner, servers);
let McpResolution::Disconnected { call, name } = credentials
- .resolve(&owner(), &custom(WIKI))
+ .resolve(&owner(), BotId::TEST_A, &custom(WIKI))
.await
.expect("resolved")
else {
@@ -207,7 +209,7 @@ async fn an_unknown_or_disabled_key_is_refused() {
let credentials = WithCustomMcp::new(&inner, servers);
let refusal = credentials
- .resolve(&owner(), &custom(WIKI))
+ .resolve(&owner(), BotId::TEST_A, &custom(WIKI))
.await
.expect_err("disabled");
assert!(
@@ -215,7 +217,11 @@ async fn an_unknown_or_disabled_key_is_refused() {
);
let refusal = credentials
- .resolve(&owner(), &custom("https://nobody.example.com/mcp"))
+ .resolve(
+ &owner(),
+ BotId::TEST_A,
+ &custom("https://nobody.example.com/mcp"),
+ )
.await
.expect_err("unknown");
assert!(matches!(refusal, EgressError::UnknownCustomServer(_)));
@@ -231,7 +237,7 @@ async fn a_cleartext_server_is_refused() {
let credentials = WithCustomMcp::new(&inner, servers);
let refusal = credentials
- .resolve(&owner(), &custom(PLAIN))
+ .resolve(&owner(), BotId::TEST_A, &custom(PLAIN))
.await
.expect_err("cleartext");
assert!(matches!(refusal, EgressError::InsecureUpstream(_)));
@@ -244,7 +250,7 @@ async fn every_other_destination_delegates_to_the_inner_resolver() {
let credentials = WithCustomMcp::new(&inner, Arc::clone(&servers));
let refusal = credentials
- .resolve(&owner(), &connected("linear"))
+ .resolve(&owner(), BotId::TEST_A, &connected("linear"))
.await
.expect_err("the spy refuses everything");
diff --git a/crates/agent_egress/src/outbound/macro_mcp.rs b/crates/agent_egress/src/outbound/macro_mcp.rs
index 4f248d8301..e64bef02dc 100644
--- a/crates/agent_egress/src/outbound/macro_mcp.rs
+++ b/crates/agent_egress/src/outbound/macro_mcp.rs
@@ -4,7 +4,9 @@
//! their rows - every session gets it, because every session's owner is a
//! Macro user. What has to be resolved per owner is the credential:
//! `mcp_service` authenticates a *user*, so the proxy exchanges the session
-//! owner's identity for a short-lived Macro API token and stamps that.
+//! owner's identity for a short-lived Macro API token and stamps that. The
+//! token also carries the session's bound agent as its signed `agent_id`
+//! claim, so the tools write as that agent rather than the generic Macro bot.
//!
//! The exchange is local signing with the same RS256 key
//! `authentication_service` uses - this process holds a key that can
@@ -13,6 +15,7 @@
//! network; what limits the blast radius is that every token minted here is
//! single-user, scoped to the session's owner, and minutes from expiry.
+use bot_id::BotId;
use chrono::{DateTime, Duration as ChronoDuration, TimeZone, Utc};
use lru::LruCache;
use macro_auth::macro_api_token::{EncodeMacroApiTokenArgs, encode_macro_api_token};
@@ -37,10 +40,11 @@ const EXPIRY_MARGIN_MINUTES: i64 = 5;
/// Implementations own the whole exchange - including finding whatever else
/// the minting side needs to know about the owner beyond their id.
pub trait MacroApiTokens: Send + Sync {
- /// A token that acts as `owner`, and nobody else.
+ /// A token that acts as `owner`, and nobody else, attributed to `agent`.
fn mint(
&self,
owner: &MacroUserIdStr<'static>,
+ agent: BotId,
) -> impl Future<Output = Result<String, EgressError>> + Send;
}
@@ -56,11 +60,11 @@ pub struct WithMacroMcp<Inner, Tokens> {
/// Whether [`UpstreamCall::bearer_over_local_cleartext`] is permitted.
/// Set only by a composition root that has checked `ENVIRONMENT=local`.
local_cleartext: bool,
- /// Keyed by owner: the token *is* the owner's identity, so a cache hit
- /// for one owner can never answer for another. Bounded, so the map cannot
- /// grow with every owner ever seen; freshness still comes from each
- /// token's own expiry, never from cache residency.
- cached: Mutex<LruCache<MacroUserIdStr<'static>, CachedToken>>,
+ /// Keyed by owner and agent: the token *is* both identities, so a cache
+ /// hit for one owner or agent can never answer for another. Bounded, so
+ /// the map cannot grow with every owner ever seen; freshness still comes
+ /// from each token's own expiry, never from cache residency.
+ cached: Mutex<LruCache<(MacroUserIdStr<'static>, BotId), CachedToken>>,
}
/// How many owners' tokens are kept at once. Far past any real concurrency;
@@ -109,10 +113,15 @@ where
})
}
- async fn token(&self, owner: &MacroUserIdStr<'static>) -> Result<String, EgressError> {
+ async fn token(
+ &self,
+ owner: &MacroUserIdStr<'static>,
+ agent: BotId,
+ ) -> Result<String, EgressError> {
+ let key = (owner.clone(), agent);
{
let mut cached = self.cached.lock().expect("token cache poisoned");
- match usable(cached.get(owner).cloned()) {
+ match usable(cached.get(&key).cloned()) {
Some(live) => {
tracing::debug!(%owner, "macro api token cache hit");
return Ok(live.token);
@@ -120,16 +129,16 @@ where
// A stale entry is evicted now rather than on capacity
// pressure: there is no reason to keep a dead credential.
None => {
- let expired = cached.pop(owner).is_some();
+ let expired = cached.pop(&key).is_some();
tracing::debug!(%owner, expired, "macro api token cache miss; minting");
}
}
}
- let token = self.tokens.mint(owner).await?;
+ let token = self.tokens.mint(owner, agent).await?;
let expires_at = token_expiry(&token)?;
self.cached.lock().expect("token cache poisoned").put(
- owner.clone(),
+ key,
CachedToken {
token: token.clone(),
expires_at,
@@ -145,17 +154,18 @@ where
Inner: McpCredentials,
Tokens: MacroApiTokens,
{
- #[tracing::instrument(skip_all, err, fields(%owner, ?destination))]
+ #[tracing::instrument(skip_all, err, fields(%owner, %agent, ?destination))]
async fn resolve(
&self,
owner: &MacroUserIdStr<'static>,
+ agent: BotId,
destination: &McpDestination,
) -> Result<McpResolution, EgressError> {
if *destination != McpDestination::Macro {
- return self.inner.resolve(owner, destination).await;
+ return self.inner.resolve(owner, agent, destination).await;
}
- let token = BearerToken::new(self.token(owner).await?);
+ let token = BearerToken::new(self.token(owner, agent).await?);
// Every session has Macro's own server; there is no grant to lack.
let call = if self.local_cleartext && self.url.scheme() != "https" {
UpstreamCall::bearer_over_local_cleartext(self.url.clone(), token)
@@ -315,7 +325,12 @@ impl MacroApiTokenSigner {
}
impl MacroApiTokens for MacroApiTokenSigner {
- async fn mint(&self, owner: &MacroUserIdStr<'static>) -> Result<String, EgressError> {
- self.mint_for(owner, MINTED_TOKEN_LIFETIME_SECONDS).await
+ async fn mint(
+ &self,
+ owner: &MacroUserIdStr<'static>,
+ agent: BotId,
+ ) -> Result<String, EgressError> {
+ self.mint_for_agent(owner, MINTED_TOKEN_LIFETIME_SECONDS, Some(agent.as_uuid()))
+ .await
}
}
diff --git a/crates/agent_egress/src/outbound/macro_mcp/test.rs b/crates/agent_egress/src/outbound/macro_mcp/test.rs
index c1489035fb..8af6efdc00 100644
--- a/crates/agent_egress/src/outbound/macro_mcp/test.rs
+++ b/crates/agent_egress/src/outbound/macro_mcp/test.rs
@@ -24,9 +24,11 @@ fn jwt_expiring_at(exp: i64) -> String {
)
}
-/// Counts mints and answers with a fixed-expiry token.
+/// Counts mints, records the agent each was for, and answers with a
+/// fixed-expiry token.
struct CountingTokens {
minted: AtomicUsize,
+ agents: Mutex<Vec<BotId>>,
expires_at: DateTime<Utc>,
}
@@ -34,6 +36,7 @@ impl CountingTokens {
fn expiring_at(expires_at: DateTime<Utc>) -> Self {
Self {
minted: AtomicUsize::new(0),
+ agents: Mutex::new(Vec::new()),
expires_at,
}
}
@@ -44,7 +47,12 @@ impl CountingTokens {
}
impl MacroApiTokens for &CountingTokens {
- async fn mint(&self, _owner: &MacroUserIdStr<'static>) -> Result<String, EgressError> {
+ async fn mint(
+ &self,
+ _owner: &MacroUserIdStr<'static>,
+ agent: BotId,
+ ) -> Result<String, EgressError> {
+ self.agents.lock().expect("lock").push(agent);
let count = self.minted.fetch_add(1, Ordering::SeqCst) + 1;
Ok(format!(
"{}#{count}",
@@ -63,6 +71,7 @@ impl McpCredentials for &SpyInner {
async fn resolve(
&self,
_owner: &MacroUserIdStr<'static>,
+ _agent: BotId,
destination: &McpDestination,
) -> Result<McpResolution, EgressError> {
let McpDestination::Connected(slug) = destination else {
@@ -84,7 +93,7 @@ async fn answers_macros_own_destination_with_a_minted_token() {
let credentials = WithMacroMcp::new(&inner, &tokens, macro_url(), false).expect("constructed");
let McpResolution::Connected(call) = credentials
- .resolve(&owner(), &McpDestination::Macro)
+ .resolve(&owner(), BotId::TEST_A, &McpDestination::Macro)
.await
.expect("resolved")
else {
@@ -108,7 +117,7 @@ async fn reuses_a_token_until_it_nears_expiry() {
for _ in 0..3 {
credentials
- .resolve(&owner(), &McpDestination::Macro)
+ .resolve(&owner(), BotId::TEST_A, &McpDestination::Macro)
.await
.expect("resolved");
}
@@ -116,6 +125,28 @@ async fn reuses_a_token_until_it_nears_expiry() {
assert_eq!(tokens.minted.load(Ordering::SeqCst), 1);
}
+/// The token carries the session's agent, so one owner's two agents must
+/// each get their own: a hit for one would post the other's comments under
+/// the wrong name.
+#[tokio::test]
+async fn each_agent_of_one_owner_gets_its_own_token() {
+ let tokens = CountingTokens::fresh();
+ let inner = SpyInner::default();
+ let credentials = WithMacroMcp::new(&inner, &tokens, macro_url(), false).expect("constructed");
+
+ for agent in [BotId::TEST_A, BotId::TEST_B, BotId::TEST_A] {
+ credentials
+ .resolve(&owner(), agent, &McpDestination::Macro)
+ .await
+ .expect("resolved");
+ }
+
+ assert_eq!(
+ *tokens.agents.lock().expect("lock"),
+ [BotId::TEST_A, BotId::TEST_B]
+ );
+}
+
#[tokio::test]
async fn a_token_about_to_expire_is_replaced() {
// Inside the margin from the start, so every resolve re-mints.
@@ -125,7 +156,7 @@ async fn a_token_about_to_expire_is_replaced() {
for _ in 0..2 {
credentials
- .resolve(&owner(), &McpDestination::Macro)
+ .resolve(&owner(), BotId::TEST_A, &McpDestination::Macro)
.await
.expect("resolved");
}
@@ -140,7 +171,7 @@ async fn every_other_slug_delegates_to_the_inner_resolver() {
let credentials = WithMacroMcp::new(&inner, &tokens, macro_url(), false).expect("constructed");
let refusal = credentials
- .resolve(&owner(), &connected("linear"))
+ .resolve(&owner(), BotId::TEST_A, &connected("linear"))
.await
.expect_err("the spy refuses everything");
@@ -164,7 +195,7 @@ async fn refuses_a_cleartext_url_unless_local_dev_permits_it() {
let inner = SpyInner::default();
let permitted = WithMacroMcp::new(&inner, &tokens, url, true).expect("constructed");
let McpResolution::Connected(call) = permitted
- .resolve(&owner(), &McpDestination::Macro)
+ .resolve(&owner(), BotId::TEST_A, &McpDestination::Macro)
.await
.expect("resolved")
else {
diff --git a/crates/agent_egress/src/outbound/mcp_credentials.rs b/crates/agent_egress/src/outbound/mcp_credentials.rs
index 2e65965d46..e008f5e354 100644
--- a/crates/agent_egress/src/outbound/mcp_credentials.rs
+++ b/crates/agent_egress/src/outbound/mcp_credentials.rs
@@ -88,6 +88,7 @@ where
async fn resolve(
&self,
owner: &MacroUserIdStr<'static>,
+ _agent: bot_id::BotId,
destination: &McpDestination,
) -> Result<McpResolution, EgressError> {
// Macro's own server is the composition root's to layer on with
diff --git a/crates/agent_egress/src/outbound/mcp_credentials/test.rs b/crates/agent_egress/src/outbound/mcp_credentials/test.rs
index 36f6cd6bca..dbe7174ad6 100644
--- a/crates/agent_egress/src/outbound/mcp_credentials/test.rs
+++ b/crates/agent_egress/src/outbound/mcp_credentials/test.rs
@@ -1,5 +1,6 @@
use super::*;
use crate::domain::model::{McpDestination, McpResolution};
+use bot_id::BotId;
use http::header::{HeaderMap, HeaderValue};
use pipedream_mcp::outbound::api::McpUpstreamCall;
use std::sync::Mutex;
@@ -108,7 +109,7 @@ async fn resolves_an_app_slug_verbatim() {
);
let McpResolution::Connected(call) = credentials
- .resolve(&owner(), &connected("google_sheets"))
+ .resolve(&owner(), BotId::TEST_A, &connected("google_sheets"))
.await
.expect("resolved")
else {
@@ -130,7 +131,7 @@ async fn carries_the_scoping_headers_next_to_the_bearer() {
);
let McpResolution::Connected(call) = credentials
- .resolve(&owner(), &connected("linear"))
+ .resolve(&owner(), BotId::TEST_A, &connected("linear"))
.await
.expect("resolved")
else {
@@ -164,7 +165,7 @@ async fn a_disabled_connection_resolves_as_unconnected() {
);
let resolution = credentials
- .resolve(&owner(), &connected("linear"))
+ .resolve(&owner(), BotId::TEST_A, &connected("linear"))
.await
.expect("resolved");
@@ -190,7 +191,7 @@ async fn a_slug_nobody_connected_resolves_as_unconnected_for_the_owner() {
PipedreamMcpCredentials::new(Arc::new(FixedConnections(Vec::new())), upstream.clone());
let McpResolution::Unconnected(call) = credentials
- .resolve(&owner(), &connected("linear"))
+ .resolve(&owner(), BotId::TEST_A, &connected("linear"))
.await
.expect("resolved")
else {
@@ -219,7 +220,7 @@ async fn refuses_a_cleartext_upstream() {
);
let refusal = credentials
- .resolve(&owner(), &connected("linear"))
+ .resolve(&owner(), BotId::TEST_A, &connected("linear"))
.await
.expect_err("refused");
diff --git a/crates/agent_egress/src/outbound/session_authority.rs b/crates/agent_egress/src/outbound/session_authority.rs
index cdc561204b..f095676077 100644
--- a/crates/agent_egress/src/outbound/session_authority.rs
+++ b/crates/agent_egress/src/outbound/session_authority.rs
@@ -121,6 +121,7 @@ where
Ok(SessionGrant {
session: session.id,
owner,
+ agent: session.bot_id,
repo,
mcp_servers,
prompter,
diff --git a/crates/agent_harness/src/outbound/channel_announcer/test.rs b/crates/agent_harness/src/outbound/channel_announcer/test.rs
index 0e75590912..1262f43f6e 100644
--- a/crates/agent_harness/src/outbound/channel_announcer/test.rs
+++ b/crates/agent_harness/src/outbound/channel_announcer/test.rs
@@ -382,6 +382,7 @@ async fn an_answer_the_thread_may_not_carry_points_at_the_session() {
sender_id: channel_sender::ChannelSender::new_from_user(
MacroUserIdStr::try_from_email("[email protected]").unwrap(),
),
+ triggered_via: None,
triggered_by: None,
bot_profile: None,
mentions: vec![],
@@ -497,6 +498,7 @@ async fn shared_thread_and_dm_snapshots_omit_raw_tool_details() {
sender_id: channel_sender::ChannelSender::new_from_user(
MacroUserIdStr::try_from_email("[email protected]").unwrap(),
),
+ triggered_via: None,
triggered_by: None,
bot_profile: None,
mentions: vec![],
diff --git a/crates/agent_harness/src/outbound/channel_prompt_context/test.rs b/crates/agent_harness/src/outbound/channel_prompt_context/test.rs
index 8bdb306286..23d2f71355 100644
--- a/crates/agent_harness/src/outbound/channel_prompt_context/test.rs
+++ b/crates/agent_harness/src/outbound/channel_prompt_context/test.rs
@@ -64,6 +64,7 @@ fn posted(
sender_id: channel_sender::ChannelSender::new_from_user(
MacroUserIdStr::try_from_email(email).unwrap(),
),
+ triggered_via: None,
triggered_by: None,
bot_profile: None,
mentions: vec![],
diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rs
index fade1a3786..673aa0f2dd 100644
--- a/crates/agent_session/src/outbound/postgres/test.rs
+++ b/crates/agent_session/src/outbound/postgres/test.rs
@@ -2744,6 +2744,7 @@ async fn a_document_session_preserves_its_origin_and_inherits_live_document_acce
canonical_root_id: None,
parent: parent.clone(),
actor: OWNER.to_owned().try_into().unwrap(),
+ triggered_via: None,
triggered_by: None,
input: PostMessage {
id: None,
diff --git a/crates/agent_trigger/src/domain/task_assignment/test.rs b/crates/agent_trigger/src/domain/task_assignment/test.rs
index 6ef615fc7c..493c71f01b 100644
--- a/crates/agent_trigger/src/domain/task_assignment/test.rs
+++ b/crates/agent_trigger/src/domain/task_assignment/test.rs
@@ -153,6 +153,7 @@ fn discussion(assignment: &TaskAssignment) -> messages::domain::models::Message
parent: assignment.parent.clone(),
thread_id: None,
sender_id: channel_sender::ChannelSender::new_from_bot(BotId::TEST_A),
+ triggered_via: None,
triggered_by: None,
bot_profile: None,
guest_name: None,
diff --git a/crates/agent_trigger/src/outbound/discussion_context/test.rs b/crates/agent_trigger/src/outbound/discussion_context/test.rs
index 7b305790f1..c530d556a3 100644
--- a/crates/agent_trigger/src/outbound/discussion_context/test.rs
+++ b/crates/agent_trigger/src/outbound/discussion_context/test.rs
@@ -129,6 +129,7 @@ fn posted(
sender_id: channel_sender::ChannelSender::new_from_user(
MacroUserIdStr::try_from_email(email).unwrap(),
),
+ triggered_via: None,
triggered_by: None,
bot_profile: None,
mentions: vec![],
diff --git a/crates/agent_trigger/src/outbound/message_thread_history/test.rs b/crates/agent_trigger/src/outbound/message_thread_history/test.rs
index a8ca6010cf..9ac993d0e1 100644
--- a/crates/agent_trigger/src/outbound/message_thread_history/test.rs
+++ b/crates/agent_trigger/src/outbound/message_thread_history/test.rs
@@ -45,6 +45,7 @@ fn message(id: Uuid, deleted: bool) -> Message {
parent: parent(),
thread_id: (id != root()).then_some(root()),
sender_id: channel_sender::ChannelSender::new_from_user(user()),
+ triggered_via: None,
triggered_by: None,
bot_profile: None,
mentions: vec![],
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index 553e90dc39..7f56f48279 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -2125,6 +2125,28 @@ impl ToolServiceContext {
self
}
+ /// 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.
+ 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
+ }
+ }
+ }
+
+ /// Label the posts the tools make with the client the user works
+ /// through.
+ 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
+ }
+
/// Name the actor set with [`Self::with_actor`], so what the tools write
/// is presented under the agent's own name where a reader sees it live -
/// the cursor the editing worker draws while it types. First-party bots
diff --git a/crates/ai_toolset/Cargo.toml b/crates/ai_toolset/Cargo.toml
index f8bb8d2787..04ebbf0daa 100644
--- a/crates/ai_toolset/Cargo.toml
+++ b/crates/ai_toolset/Cargo.toml
@@ -12,6 +12,7 @@ schemars = { workspace = true }
async-trait = { workspace = true }
thiserror = { workspace = true }
anyhow = { workspace = true }
+bot_id = { path = "../bot_id" }
macro_user_id = { path = "../macro_user_id" }
genai_telemetry = { path = "../genai_telemetry" }
axum = { workspace = true }
diff --git a/crates/ai_toolset/src/caller.rs b/crates/ai_toolset/src/caller.rs
new file mode 100644
index 0000000000..34d3d2f096
--- /dev/null
+++ b/crates/ai_toolset/src/caller.rs
@@ -0,0 +1,33 @@
+//! Who a tool call came from, for hosts that serve more than one kind of caller.
+
+use bot_id::BotId;
+
+/// The caller behind a tool call that a host authenticated. Hosts that serve
+/// several kinds of caller (the public MCP) pick one per call; there is no
+/// default, so a write never falls back to a bot without saying why.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum ToolCaller {
+ /// An agent session's call, carrying the agent its credential was signed
+ /// for. Writes are attributed to that agent on the user's behalf.
+ Agent(BotId),
+ /// An OAuth MCP client acting for the user. `name` is the name the client
+ /// registered under: self-reported, so a display label only, never an
+ /// identity or a permission. Absent for a token the broker issued before
+ /// it recorded which client it went to.
+ McpClient {
+ /// The client's registered name, such as "Claude Code".
+ name: Option<String>,
+ },
+ /// A Macro API key the user pasted into a client, which names no client.
+ ApiKey,
+}
+
+impl ToolCaller {
+ /// The label a write made for this caller is shown "via", if any.
+ pub fn via(&self) -> Option<&str> {
+ match self {
+ Self::McpClient { name } => name.as_deref(),
+ Self::Agent(_) | Self::ApiKey => None,
+ }
+ }
+}
diff --git a/crates/ai_toolset/src/lib.rs b/crates/ai_toolset/src/lib.rs
index 4142b36f71..9ace412994 100644
--- a/crates/ai_toolset/src/lib.rs
+++ b/crates/ai_toolset/src/lib.rs
@@ -156,6 +156,7 @@
pub mod actor;
mod annotations;
+mod caller;
mod context;
pub mod schema;
pub mod telemetry;
@@ -164,6 +165,7 @@ pub mod tool_search;
mod toolset;
pub use annotations::{ToolAnnotated, ToolAnnotations, ToolKind};
+pub use caller::ToolCaller;
pub use context::{RequestContext, ServiceContext};
pub use tool::{AsyncTool, NoContext, ToolCallError, ToolResult};
pub use tool_search::{SearchableTool, ToolLoader};
diff --git a/crates/bots/src/inbound/channel_webhook_router/tests.rs b/crates/bots/src/inbound/channel_webhook_router/tests.rs
index f51140cbe2..67a22561f2 100644
--- a/crates/bots/src/inbound/channel_webhook_router/tests.rs
+++ b/crates/bots/src/inbound/channel_webhook_router/tests.rs
@@ -577,6 +577,7 @@ impl messages::domain::api::MessageCommands for TestChannelPoster {
imported_author: None,
bot_profile: None,
mentions: Vec::new(),
+ triggered_via: None,
triggered_by,
content: input.content,
created_at: chrono::Utc::now(),
diff --git a/crates/channel_bots/src/domain/test.rs b/crates/channel_bots/src/domain/test.rs
index b9206b7d3b..a2ebcd1757 100644
--- a/crates/channel_bots/src/domain/test.rs
+++ b/crates/channel_bots/src/domain/test.rs
@@ -68,6 +68,7 @@ pub(crate) fn message(id: u128, thread: Option<Uuid>, body: &str) -> Message {
mentions: vec![],
guest_name: None,
imported_author: None,
+ triggered_via: None,
triggered_by: None,
content: body.into(),
created_at: chrono::Utc::now(),
diff --git a/crates/channels/src/domain/message_delivery/test.rs b/crates/channels/src/domain/message_delivery/test.rs
index a234849e4a..2da0c273a6 100644
--- a/crates/channels/src/domain/message_delivery/test.rs
+++ b/crates/channels/src/domain/message_delivery/test.rs
@@ -111,6 +111,7 @@ fn message() -> Message {
parent: MessageParent::Channel(CHANNEL),
thread_id: None,
sender_id: SENDER.to_owned().try_into().unwrap(),
+ triggered_via: None,
triggered_by: None,
bot_profile: None,
mentions: vec![],
diff --git a/crates/channels/src/inbound/toolset.rs b/crates/channels/src/inbound/toolset.rs
index 4394a71268..dff11fa376 100644
--- a/crates/channels/src/inbound/toolset.rs
+++ b/crates/channels/src/inbound/toolset.rs
@@ -41,6 +41,7 @@ use entity_access::domain::{
use macro_user_id::user_id::MacroUserIdStr;
use messages::domain::{
api::MessageServiceApi,
+ models::MessageAttribution,
ports::MessageError,
service::{MessageView, MessageWrite},
};
@@ -73,6 +74,8 @@ where
/// The bot these tools act as, on behalf of the requesting user. Defaults
/// to Macro AI; hosts running a specific agent set it with [`Self::with_actor`].
pub actor: BotId,
+ /// The client the requesting user works through, labelled on posts.
+ pub via: Option<String>,
}
impl<Svc, AccessSvc> Clone for ChannelToolContext<Svc, AccessSvc>
@@ -86,6 +89,7 @@ where
service: self.service.clone(),
entity_access_service: self.entity_access_service.clone(),
actor: self.actor,
+ via: self.via.clone(),
}
}
}
@@ -106,6 +110,7 @@ where
service: Arc::new(service),
entity_access_service: Arc::new(entity_access_service),
actor: bot_id::MACRO_AI_BOT_ID,
+ via: None,
}
}
@@ -132,6 +137,23 @@ where
self
}
+ /// Label the posts these tools make 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 post made by these tools is attributed.
+ pub fn attribution(&self) -> MessageAttribution {
+ match &self.via {
+ Some(client) => MessageAttribution::ActingUserVia {
+ client: client.clone(),
+ },
+ None => MessageAttribution::ActingUser,
+ }
+ }
+
/// Mint the requesting user's own channel write capability, for actions
/// the app attributes to the user rather than to the tool actor bot.
pub async fn require_user_message_write(
diff --git a/crates/channels/src/inbound/toolset/send_channel_message.rs b/crates/channels/src/inbound/toolset/send_channel_message.rs
index d2ed3d9237..ad66f774fa 100644
--- a/crates/channels/src/inbound/toolset/send_channel_message.rs
+++ b/crates/channels/src/inbound/toolset/send_channel_message.rs
@@ -9,7 +9,7 @@ use crate::domain::ports::ChannelService;
use crate::inbound::toolset::{ChannelToolContext, types::ChannelMessageAttachmentInput};
use entity_access::domain::ports::EntityAccessService;
use messages::domain::{
- models::{MessageAttribution, NewAttachment, PostMessage, PostMessageNotificationPolicy},
+ models::{NewAttachment, PostMessage, PostMessageNotificationPolicy},
ports::MessageError,
};
@@ -79,7 +79,7 @@ where
access,
PostMessage {
id: None,
- attribution: MessageAttribution::ActingUser,
+ attribution: service_context.attribution(),
notification_policy: PostMessageNotificationPolicy::Default,
content: self.content.clone(),
thread_id: self.thread_id,
diff --git a/crates/channels/src/inbound/toolset/test.rs b/crates/channels/src/inbound/toolset/test.rs
index 611356a219..3a0b1f2e64 100644
--- a/crates/channels/src/inbound/toolset/test.rs
+++ b/crates/channels/src/inbound/toolset/test.rs
@@ -91,6 +91,7 @@ impl RecordingMessages {
imported_author: None,
bot_profile: None,
mentions: vec![],
+ triggered_via: None,
triggered_by: None,
content: "stored".to_string(),
created_at: chrono::Utc::now(),
@@ -156,6 +157,7 @@ impl messages::domain::api::MessageCommands for RecordingMessages {
imported_author: None,
bot_profile: None,
mentions: vec![],
+ triggered_via: None,
triggered_by: access
.acting_user_id()
.map(|user| user.as_ref().to_string()),
diff --git a/crates/channels/src/inbound/toolset/types/test.rs b/crates/channels/src/inbound/toolset/types/test.rs
index c809e859ed..4400564479 100644
--- a/crates/channels/src/inbound/toolset/types/test.rs
+++ b/crates/channels/src/inbound/toolset/types/test.rs
@@ -10,6 +10,7 @@ fn reply(seconds: i64) -> Message {
parent: messages::domain::models::MessageParent::Channel(Uuid::nil()),
thread_id: Some(Uuid::from_u128(1)),
sender_id: "macro|[email protected]".to_owned().try_into().unwrap(),
+ triggered_via: None,
triggered_by: None,
bot_profile: None,
guest_name: None,
diff --git a/crates/crm/src/outbound/lookup/test/message_store.rs b/crates/crm/src/outbound/lookup/test/message_store.rs
index 0682306e16..ba1c0617e7 100644
--- a/crates/crm/src/outbound/lookup/test/message_store.rs
+++ b/crates/crm/src/outbound/lookup/test/message_store.rs
@@ -229,6 +229,7 @@ async fn crm_discussion_lifecycle_cascades_on_company_deletion(pool: PgPool) {
parent: company,
actor: USER.to_owned().try_into().unwrap(),
triggered_by: None,
+ triggered_via: None,
input: input("race", None),
};
assert!(matches!(
diff --git a/crates/documents/src/domain/comments/test.rs b/crates/documents/src/domain/comments/test.rs
index 1ea47669c3..f6ba76686f 100644
--- a/crates/documents/src/domain/comments/test.rs
+++ b/crates/documents/src/domain/comments/test.rs
@@ -52,6 +52,7 @@ fn message(n: u128, root: Option<u128>, content: &str) -> Message {
imported_author: None,
bot_profile: None,
mentions: vec![],
+ triggered_via: None,
triggered_by: None,
content: content.to_owned(),
created_at: at(n as u32),
diff --git a/crates/documents/src/inbound/toolset/comment_test.rs b/crates/documents/src/inbound/toolset/comment_test.rs
index d2f61d82d4..46b60e34ca 100644
--- a/crates/documents/src/inbound/toolset/comment_test.rs
+++ b/crates/documents/src/inbound/toolset/comment_test.rs
@@ -121,6 +121,7 @@ impl MessageCommands for FakeMessages {
imported_author: None,
bot_profile: None,
mentions: vec![],
+ triggered_via: None,
triggered_by: Some(USER.to_owned()),
content: input.content.clone(),
created_at: at,
diff --git a/crates/macro_db_client/migrations/20261029164852_add_comms_messages_triggered_via.sql b/crates/macro_db_client/migrations/20261029164852_add_comms_messages_triggered_via.sql
new file mode 100644
index 0000000000..a33c883e52
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261029164852_add_comms_messages_triggered_via.sql
@@ -0,0 +1,13 @@
+-- Record which client a user triggered an agent-authored message through.
+--
+-- A user's MCP client (for example Claude Code) writes through the public MCP
+-- as the Macro bot on the user's behalf. `triggered_by_user_id` names the
+-- user; this column keeps the client's self-reported registration name so
+-- clients can render "from <user> via <client>". A display label only.
+--
+-- Nullable with no default: every other message leaves it NULL, and the
+-- column adds without a table rewrite or backfill.
+SET lock_timeout = '5s';
+
+ALTER TABLE public.comms_messages
+ ADD COLUMN IF NOT EXISTS triggered_via text;
diff --git a/crates/macro_db_client/src/annotations/create_anchor/test.rs b/crates/macro_db_client/src/annotations/create_anchor/test.rs
index 05d1a85f12..01e578c38d 100644
--- a/crates/macro_db_client/src/annotations/create_anchor/test.rs
+++ b/crates/macro_db_client/src/annotations/create_anchor/test.rs
@@ -32,6 +32,7 @@ async fn standalone_highlight_remains_unthreaded_until_a_message_attaches_it(poo
canonical_root_id: None,
parent: MessageParent::parse("document", "document-with-comments").unwrap(),
actor: "macro|[email protected]".to_owned().try_into().unwrap(),
+ triggered_via: None,
triggered_by: None,
input: PostMessage {
id: None,
diff --git a/crates/messages/AGENTS.md b/crates/messages/AGENTS.md
index 50904af955..3508aa7473 100644
--- a/crates/messages/AGENTS.md
+++ b/crates/messages/AGENTS.md
@@ -59,6 +59,11 @@ they need.
- `cargo test -p messages --all-features` (`SQLX_OFFLINE` unset).
+A bot post made for a user through a named client (an MCP client on the public
+MCP) 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.
+
New posts use the message sender receipt to retain signed code-mode agent
attribution. All other operations use the caller receipt so attribution cannot
grant users another agent invocation's edit, deletion, or reaction authority.
diff --git a/crates/messages/src/domain/delivery/test.rs b/crates/messages/src/domain/delivery/test.rs
index cda3fbdc1f..b743ba2685 100644
--- a/crates/messages/src/domain/delivery/test.rs
+++ b/crates/messages/src/domain/delivery/test.rs
@@ -79,6 +79,7 @@ fn event() -> MessageEvent {
mentions: vec![],
guest_name: None,
imported_author: None,
+ triggered_via: None,
triggered_by: None,
content: "A private discussion".into(),
created_at: Utc::now(),
diff --git a/crates/messages/src/domain/models.rs b/crates/messages/src/domain/models.rs
index 3fbad9d903..9ad3d0f23f 100644
--- a/crates/messages/src/domain/models.rs
+++ b/crates/messages/src/domain/models.rs
@@ -458,6 +458,10 @@ pub struct Message {
pub mentions: Vec<SimpleMention>,
/// User who triggered a bot-authored message.
pub triggered_by: Option<String>,
+ /// Self-reported name of the client the user triggered it through, such
+ /// as "Claude Code"; a display label only.
+ #[serde(default)]
+ pub triggered_via: Option<String>,
/// Macro Markdown body.
pub content: String,
/// Creation time.
@@ -521,15 +525,31 @@ pub enum PatchMessageNotificationPolicy {
}
/// Attribution of a trusted bot post, distinct from the scope used to authorize it.
-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum MessageAttribution {
/// A user invoked the agent; use the verified acting user from its capability.
#[default]
ActingUser,
+ /// A user invoked the agent through a named client, such as an MCP client;
+ /// the post records the acting user and the client's label.
+ ActingUserVia {
+ /// The client's self-reported name, for display only.
+ client: String,
+ },
/// Autonomous webhook delivery has no invoking user.
Unprompted,
}
+impl MessageAttribution {
+ /// Whether the post records the verified acting user as its trigger.
+ pub fn has_acting_user(&self) -> bool {
+ match self {
+ Self::ActingUser | Self::ActingUserVia { .. } => true,
+ Self::Unprompted => false,
+ }
+ }
+}
+
/// Create a root or reply. Thread state may only be supplied on a root.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
diff --git a/crates/messages/src/domain/ports.rs b/crates/messages/src/domain/ports.rs
index 5333f315e8..c0944ddb99 100644
--- a/crates/messages/src/domain/ports.rs
+++ b/crates/messages/src/domain/ports.rs
@@ -167,6 +167,8 @@ pub struct CreateMessage {
pub guest_name: Option<String>,
/// User who triggered a bot message, if applicable.
pub triggered_by: Option<String>,
+ /// Label of the client the user triggered it through, if any.
+ pub triggered_via: Option<String>,
/// Parsed message input.
pub input: PostMessage,
}
diff --git a/crates/messages/src/domain/service.rs b/crates/messages/src/domain/service.rs
index 17bd2ebdb4..5c43f2224a 100644
--- a/crates/messages/src/domain/service.rs
+++ b/crates/messages/src/domain/service.rs
@@ -382,11 +382,16 @@ impl<R: MessageRepository, E: MessageEventPublisher> MessageService<R, E> {
guest_name: None,
triggered_by: access
.acting_user_id()
- .filter(|_| {
- actor.as_bot().is_some()
- && input.attribution == MessageAttribution::ActingUser
- })
+ .filter(|_| actor.as_bot().is_some() && input.attribution.has_acting_user())
.map(ToString::to_string),
+ triggered_via: match &input.attribution {
+ MessageAttribution::ActingUserVia { client } if actor.as_bot().is_some() => {
+ Some(client.clone())
+ }
+ MessageAttribution::ActingUserVia { .. }
+ | MessageAttribution::ActingUser
+ | MessageAttribution::Unprompted => None,
+ },
input,
})
.await?;
diff --git a/crates/messages/src/domain/service/guest_chat.rs b/crates/messages/src/domain/service/guest_chat.rs
index 64aefed00b..c33e6e9298 100644
--- a/crates/messages/src/domain/service/guest_chat.rs
+++ b/crates/messages/src/domain/service/guest_chat.rs
@@ -162,6 +162,7 @@ impl<R: MessageRepository, E: MessageEventPublisher> GuestChatApi for GuestChatS
parent: parent.clone(),
actor: actor.clone(),
guest_name: Some(access.name),
+ triggered_via: None,
triggered_by: None,
input: PostMessage {
id: Some(input.id),
diff --git a/crates/messages/src/domain/service/test.rs b/crates/messages/src/domain/service/test.rs
index 61be35ab5e..c0680cc01b 100644
--- a/crates/messages/src/domain/service/test.rs
+++ b/crates/messages/src/domain/service/test.rs
@@ -254,6 +254,7 @@ fn fixture() -> Repo {
imported_author: Some(ImportedAuthor {
name: "External PDF author".into(),
}),
+ triggered_via: None,
triggered_by: None,
content: "root".into(),
created_at: Utc::now(),
@@ -1140,12 +1141,26 @@ async fn bot_posts_and_edits_extract_mentions_and_preserve_trusted_attribution_a
input.attribution = MessageAttribution::Unprompted;
assert!(
service
- .post(receipt(), input)
+ .post(receipt(), input.clone())
.await
.unwrap()
.triggered_by
.is_none()
);
+ input.attribution = MessageAttribution::ActingUserVia {
+ client: "Claude Code".into(),
+ };
+ service.post(receipt(), input).await.unwrap();
+ {
+ let creates = repo.creates.lock().unwrap();
+ let via = creates.last().unwrap();
+ assert_eq!(
+ via.triggered_by.as_deref(),
+ Some("macro|[email protected]")
+ );
+ assert_eq!(via.triggered_via.as_deref(), Some("Claude Code"));
+ assert!(creates[0].triggered_via.is_none());
+ }
service
.patch(
receipt(),
@@ -1169,7 +1184,7 @@ async fn bot_posts_and_edits_extract_mentions_and_preserve_trusted_attribution_a
}
));
assert!(matches!(
- events[2].change,
+ events[3].change,
MessageChange::Edited {
notification_policy: PatchMessageNotificationPolicy::NotifyAsPostedMessage,
..
diff --git a/crates/messages/src/domain/service/timeline/test.rs b/crates/messages/src/domain/service/timeline/test.rs
index 8266c7b622..af122e286f 100644
--- a/crates/messages/src/domain/service/timeline/test.rs
+++ b/crates/messages/src/domain/service/timeline/test.rs
@@ -24,6 +24,7 @@ fn message(id: u128) -> MessageListItem {
bot_profile: None,
mentions: vec![],
imported_author: None,
+ triggered_via: None,
triggered_by: None,
content: "hello".into(),
created_at: at,
diff --git a/crates/messages/src/inbound/toolset.rs b/crates/messages/src/inbound/toolset.rs
index 9edea2dcc7..23eef616d5 100644
--- a/crates/messages/src/inbound/toolset.rs
+++ b/crates/messages/src/inbound/toolset.rs
@@ -31,7 +31,7 @@ pub use resolve_comment::ResolveComment;
use crate::domain::{
api::MessageServiceApi,
- models::{InvalidParent, MessageParent},
+ models::{InvalidParent, MessageAttribution, MessageParent},
ports::MessageError,
service::{MessageView, MessageWrite},
};
@@ -46,6 +46,8 @@ pub struct MessageToolContext<ESvc: EntityAccessService> {
/// Defaults to Macro AI; hosts running a specific agent set it with
/// [`Self::with_actor`].
pub actor: BotId,
+ /// The client the requesting user works through, labelled on posts.
+ pub via: Option<String>,
}
impl<ESvc: EntityAccessService> Clone for MessageToolContext<ESvc> {
@@ -54,6 +56,7 @@ impl<ESvc: EntityAccessService> Clone for MessageToolContext<ESvc> {
messages: self.messages.clone(),
entity_access_service: self.entity_access_service.clone(),
actor: self.actor,
+ via: self.via.clone(),
}
}
}
@@ -65,6 +68,7 @@ impl<ESvc: EntityAccessService> MessageToolContext<ESvc> {
messages,
entity_access_service,
actor: bot_id::MACRO_AI_BOT_ID,
+ via: None,
}
}
@@ -74,6 +78,23 @@ impl<ESvc: EntityAccessService> MessageToolContext<ESvc> {
self
}
+ /// Label the posts these tools make 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 post made by these tools is attributed.
+ pub fn attribution(&self) -> MessageAttribution {
+ match &self.via {
+ Some(client) => MessageAttribution::ActingUserVia {
+ client: client.clone(),
+ },
+ None => MessageAttribution::ActingUser,
+ }
+ }
+
/// The requesting user's own view of a discussion.
async fn discussion_view(
&self,
diff --git a/crates/messages/src/inbound/toolset/comment.rs b/crates/messages/src/inbound/toolset/comment.rs
index 5214c783d6..6592339c01 100644
--- a/crates/messages/src/inbound/toolset/comment.rs
+++ b/crates/messages/src/inbound/toolset/comment.rs
@@ -10,7 +10,7 @@ use uuid::Uuid;
use super::{DiscussionParentType, MessageToolContext, comment_error, parse_target};
use crate::domain::{
- models::{MessageAttribution, PostMessage, PostMessageNotificationPolicy},
+ models::{PostMessage, PostMessageNotificationPolicy},
ports::MessageError,
};
@@ -95,7 +95,7 @@ impl<ESvc: EntityAccessService> AsyncTool<MessageToolContext<ESvc>> for Comment
access,
PostMessage {
id: None,
- attribution: MessageAttribution::ActingUser,
+ attribution: ctx.attribution(),
notification_policy: PostMessageNotificationPolicy::Default,
content: self.content.clone(),
thread_id: self.thread_id,
diff --git a/crates/messages/src/inbound/toolset/test.rs b/crates/messages/src/inbound/toolset/test.rs
index b0779ad758..214938b02f 100644
--- a/crates/messages/src/inbound/toolset/test.rs
+++ b/crates/messages/src/inbound/toolset/test.rs
@@ -67,6 +67,7 @@ fn message(id: Uuid, thread_id: Option<Uuid>, sender: ChannelSender<'static>) ->
imported_author: None,
bot_profile: None,
mentions: vec![],
+ triggered_via: None,
triggered_by: None,
content: format!("comment {id}"),
created_at: at(),
@@ -555,6 +556,77 @@ async fn comment_on_a_project_posts_as_the_bot_for_the_user() {
assert!(messages.parent_lookups.lock().unwrap().is_empty());
}
+/// A host running a specific agent (the public MCP for a self-hosted
+/// session, the in-memory runtime) posts each agent's comments as that agent,
+/// still on the acting user's behalf.
+#[tokio::test]
+async fn comments_from_two_agents_post_as_each_agent_for_the_user() {
+ let reviewer = bot_id::BotId::new_from_uuid(Uuid::from_u128(0xA1));
+ let planner = bot_id::BotId::new_from_uuid(Uuid::from_u128(0xA2));
+ let messages = FakeMessages::default();
+ for agent in [reviewer, planner] {
+ let ServiceContext(tool_context) = context(AccessLevel::Comment, messages.clone());
+ comment_on_initiative("Looks good.")
+ .call(ServiceContext(tool_context.with_actor(agent)), request())
+ .await
+ .unwrap();
+ }
+
+ let posts = messages.posts.lock().unwrap();
+ let authors: Vec<_> = posts
+ .iter()
+ .map(|(access, post)| {
+ let EntityAccessAuth::Bot(bot) = access.auth() else {
+ panic!("expected a bot post, got {:?}", access.auth());
+ };
+ assert_eq!(
+ access.acting_user_id().map(|user| user.as_ref()),
+ Some(USER)
+ );
+ assert_eq!(post.attribution, MessageAttribution::ActingUser);
+ bot.bot_id()
+ })
+ .collect();
+ assert_eq!(authors, [reviewer, planner]);
+}
+
+/// A user's MCP client posts as the Macro bot for the user, with the client
+/// named on the post; a pasted API key posts the same way without a label.
+#[tokio::test]
+async fn a_comment_through_an_mcp_client_names_the_client() {
+ let messages = FakeMessages::default();
+ let ServiceContext(tool_context) = context(AccessLevel::Comment, messages.clone());
+ comment_on_initiative("Looks good.")
+ .call(
+ ServiceContext(tool_context.clone().with_via("Claude Code".to_owned())),
+ request(),
+ )
+ .await
+ .unwrap();
+ comment_on_initiative("Looks good.")
+ .call(ServiceContext(tool_context), request())
+ .await
+ .unwrap();
+
+ let posts = messages.posts.lock().unwrap();
+ let [(via_access, via_post), (key_access, key_post)] = posts.as_slice() else {
+ panic!("expected two posts, got {}", posts.len());
+ };
+ for access in [via_access, key_access] {
+ let EntityAccessAuth::Bot(bot) = access.auth() else {
+ panic!("expected a bot post, got {:?}", access.auth());
+ };
+ assert_eq!(bot.bot_id(), bot_id::MACRO_AI_BOT_ID);
+ }
+ assert_eq!(
+ via_post.attribution,
+ MessageAttribution::ActingUserVia {
+ client: "Claude Code".to_owned()
+ }
+ );
+ assert_eq!(key_post.attribution, MessageAttribution::ActingUser);
+}
+
#[tokio::test]
async fn reply_by_thread_id_alone_finds_its_item() {
let messages = FakeMessages::default();
diff --git a/crates/messages/src/outbound/broker/test.rs b/crates/messages/src/outbound/broker/test.rs
index d7c6dc1668..ed4b1dc4aa 100644
--- a/crates/messages/src/outbound/broker/test.rs
+++ b/crates/messages/src/outbound/broker/test.rs
@@ -51,6 +51,7 @@ fn reply(parent: MessageParent, attachments: Vec<MessageAttachment>) -> Message
imported_author: None,
bot_profile: None,
mentions: vec![],
+ triggered_via: None,
triggered_by: None,
content: "hello @someone".into(),
created_at: Utc::now(),
diff --git a/crates/messages/src/outbound/pg_message_repo.rs b/crates/messages/src/outbound/pg_message_repo.rs
index 2d0582c283..2aa39cb69a 100644
--- a/crates/messages/src/outbound/pg_message_repo.rs
+++ b/crates/messages/src/outbound/pg_message_repo.rs
@@ -30,6 +30,7 @@ struct StoredMessage {
guest_name: Option<String>,
imported_author: Option<String>,
triggered_by_user_id: Option<String>,
+ triggered_via: Option<String>,
content: String,
created_at: DateTime<Utc>,
updated_at: DateTime<Utc>,
@@ -260,6 +261,7 @@ impl PgMessageRepository {
imported_author: r.imported_author.map(|name| ImportedAuthor { name }),
guest_name: r.guest_name,
triggered_by: r.triggered_by_user_id,
+ triggered_via: r.triggered_via,
content: if deleted { String::new() } else { r.content },
created_at: r.created_at,
updated_at: r.updated_at,
@@ -741,14 +743,16 @@ impl MessageRepository for PgMessageRepository {
}
sqlx::query!(
r#"INSERT INTO comms_messages(id, parent_entity_type, parent_entity_id, thread_id,
- sender_id, triggered_by_user_id, content, client_message_id, guest_name)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)"#,
+ sender_id, triggered_by_user_id, triggered_via, content, client_message_id,
+ guest_name)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)"#,
id,
command.parent.entity_type(),
command.parent.entity_id(),
command.input.thread_id,
command.actor.as_ref(),
command.triggered_by,
+ command.triggered_via,
command.input.content,
command.canonical_root_id.and(command.input.id),
command.guest_name,
diff --git a/crates/messages/src/outbound/pg_message_repo/test.rs b/crates/messages/src/outbound/pg_message_repo/test.rs
index 3214ce99ee..a3d8e73b4a 100644
--- a/crates/messages/src/outbound/pg_message_repo/test.rs
+++ b/crates/messages/src/outbound/pg_message_repo/test.rs
@@ -36,6 +36,7 @@ fn command(document: &str, root: Option<Uuid>, content: &str) -> CreateMessage {
canonical_root_id: None,
parent: MessageParent::parse("document", document).unwrap(),
actor: USER.to_owned().try_into().unwrap(),
+ triggered_via: None,
triggered_by: None,
input: PostMessage {
id: None,
@@ -80,12 +81,15 @@ async fn shared_reads_preserve_system_and_deleted_bot_profiles(pool: PgPool) {
let mut input = command("message-doc-a", None, "Agent answer");
input.actor = channel_sender::ChannelSender::new_from_bot(bot_id);
input.triggered_by = Some(USER.to_owned());
+ input.triggered_via = Some("Claude Code".to_owned());
let message = repo.create(input).await.unwrap();
let read = repo
.get(&message.parent, message.id)
.await
.unwrap()
.unwrap();
+ assert_eq!(read.triggered_by.as_deref(), Some(USER));
+ assert_eq!(read.triggered_via.as_deref(), Some("Claude Code"));
assert_eq!(
read.bot_profile,
Some(BotSenderProfile {
diff --git a/crates/scheduled_action/src/outbound/event_content/routine_event/test.rs b/crates/scheduled_action/src/outbound/event_content/routine_event/test.rs
index 64eceb33b5..754a7904a5 100644
--- a/crates/scheduled_action/src/outbound/event_content/routine_event/test.rs
+++ b/crates/scheduled_action/src/outbound/event_content/routine_event/test.rs
@@ -438,6 +438,7 @@ fn a_channel_reply_carries_its_thread_through_the_message() {
imported_author: None,
bot_profile: None,
mentions: Vec::new(),
+ triggered_via: None,
triggered_by: None,
content: "Still broken on Safari 17, can someone look?".into(),
created_at: at(4),
@@ -473,6 +474,7 @@ fn a_channel_reply_carries_its_thread_through_the_message() {
imported_author: None,
bot_profile: None,
mentions: Vec::new(),
+ triggered_via: None,
triggered_by: None,
content: "Login crashes on Safari".into(),
created_at: at(1),
@@ -492,6 +494,7 @@ fn a_channel_reply_carries_its_thread_through_the_message() {
imported_author: None,
bot_profile: None,
mentions: Vec::new(),
+ triggered_via: None,
triggered_by: None,
content: "Fixed in #812".into(),
created_at: at(2),
@@ -510,6 +513,7 @@ fn a_channel_reply_carries_its_thread_through_the_message() {
imported_author: None,
bot_profile: None,
mentions: Vec::new(),
+ triggered_via: None,
triggered_by: None,
content: "oops".into(),
created_at: at(3),
@@ -529,6 +533,7 @@ fn a_channel_reply_carries_its_thread_through_the_message() {
imported_author: None,
bot_profile: None,
mentions: Vec::new(),
+ triggered_via: None,
triggered_by: None,
content: "Looking".into(),
created_at: at(5),
diff --git a/crates/scheduled_action/src/outbound/event_content/test.rs b/crates/scheduled_action/src/outbound/event_content/test.rs
index 3f7edae62a..66216147a3 100644
--- a/crates/scheduled_action/src/outbound/event_content/test.rs
+++ b/crates/scheduled_action/src/outbound/event_content/test.rs
@@ -122,6 +122,7 @@ fn message(content: &str) -> Message {
imported_author: None,
bot_profile: None,
mentions: Vec::new(),
+ triggered_via: None,
triggered_by: None,
content: content.into(),
created_at: at,
diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.md
index 3548ada7a9..707dc9a711 100644
--- a/docs/agent-guide/channels.md
+++ b/docs/agent-guide/channels.md
@@ -285,6 +285,17 @@ be loaded or exceeds the inline limit, its URL remains available. To check this,
ask the agent to inspect an image on a channel message and a video on a reply;
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.
+
## Message composer
Channel messages and thread replies have a microphone next to Send on pointer
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/Message.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/Message.md
index d310401ccd..f78d8d538e 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/Message.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/Message.md
@@ -1,6 +1,6 @@
# Type Alias: Message
-> **Message** = \{ `attachments`: [`MessageAttachment`](MessageAttachment.md)[]; `bot_profile?`: `null` \| [`BotSenderProfile`](BotSenderProfile.md); `content`: `string`; `created_at`: `string`; `deleted_at?`: `string` \| `null`; `edited_at?`: `string` \| `null`; `guest_name?`: `string` \| `null`; `id`: `string`; `imported_author?`: `null` \| [`ImportedAuthor`](ImportedAuthor.md); `mentions`: [`SimpleMention`](SimpleMention.md)[]; `parent`: [`MessageParent`](MessageParent.md); `reactions`: [`CountedReaction`](CountedReaction.md)[]; `sender_id`: `string`; `thread_id?`: `string` \| `null`; `triggered_by?`: `string` \| `null`; `updated_at`: `string`; \}
+> **Message** = \{ `attachments`: [`MessageAttachment`](MessageAttachment.md)[]; `bot_profile?`: `null` \| [`BotSenderProfile`](BotSenderProfile.md); `content`: `string`; `created_at`: `string`; `deleted_at?`: `string` \| `null`; `edited_at?`: `string` \| `null`; `guest_name?`: `string` \| `null`; `id`: `string`; `imported_author?`: `null` \| [`ImportedAuthor`](ImportedAuthor.md); `mentions`: [`SimpleMention`](SimpleMention.md)[]; `parent`: [`MessageParent`](MessageParent.md); `reactions`: [`CountedReaction`](CountedReaction.md)[]; `sender_id`: `string`; `thread_id?`: `string` \| `null`; `triggered_by?`: `string` \| `null`; `triggered_via?`: `string` \| `null`; `updated_at`: `string`; \}
Shared message representation for channel timelines and entity discussions.
@@ -23,4 +23,5 @@ Shared message representation for channel timelines and entity discussions.
| <a id="property-sender_id"></a> `sender_id` | `string` | Authenticated actor or owner of imported content. |
| <a id="property-thread_id"></a> `thread_id?` | `string` \| `null` | Root message UUID for replies; absent on roots. |
| <a id="property-triggered_by"></a> `triggered_by?` | `string` \| `null` | User who triggered a bot-authored message. |
+| <a id="property-triggered_via"></a> `triggered_via?` | `string` \| `null` | Self-reported name of the client the user triggered it through, such as "Claude Code"; a display label only. |
| <a id="property-updated_at"></a> `updated_at` | `string` | Last persisted update. |
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index cff8b34a07..44c5048cc1 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -10044,6 +10044,11 @@ export type Message = {
* User who triggered a bot-authored message.
*/
triggered_by?: string | null;
+ /**
+ * Self-reported name of the client the user triggered it through, such
+ * as "Claude Code"; a display label only.
+ */
+ triggered_via?: string | null;
/**
* Last persisted update.
*/
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index baba6916e3..54fa1cca4d 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -34953,6 +34953,10 @@
"type": ["string", "null"],
"description": "User who triggered a bot-authored message."
},
+ "triggered_via": {
+ "type": ["string", "null"],
+ "description": "Self-reported name of the client the user triggered it through, such\nas \"Claude Code\"; a display label only."
+ },
"updated_at": {
"type": "string",
"format": "date-time",
diff --git a/services/agent_harness_service/AGENTS.md b/services/agent_harness_service/AGENTS.md
index e19e93f0ec..41e04c548f 100644
--- a/services/agent_harness_service/AGENTS.md
+++ b/services/agent_harness_service/AGENTS.md
@@ -140,6 +140,13 @@ listener failure shuts down the process so ECS can replace the task.
- Analytics record the tool name, outcome, duration, and client headers only;
never add tool arguments or results to them.
+- Public MCP tool calls run for the `ToolCaller` the bearer middleware
+ (`mcp_auth_proxy`) attached, and a call without one is refused: `Agent` (a
+ Macro 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 public MCP server is stateless, so tool calls carry no `clientInfo`; the
client 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.rs
index d9999215a6..54c00d90fe 100644
--- a/services/agent_harness_service/src/code_mode.rs
+++ b/services/agent_harness_service/src/code_mode.rs
@@ -45,8 +45,10 @@ impl ExecutionCredentials for RunCredentials {
}
}
-/// Credentials for public MCP runs: the signed-in user, with no session or agent.
-/// The MCP client asks the user before each tool call, so there is no owner gate.
+/// 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.
pub struct UserRunCredentials {
pub signer: MacroApiTokenSigner,
pub hosts: BTreeMap<String, String>,
@@ -54,12 +56,24 @@ pub struct UserRunCredentials {
#[async_trait]
impl UserExecutionCredentials for UserRunCredentials {
- async fn issue(&self, user: &MacroUserIdStr<'static>) -> Result<RunEnvironment, CodeModeError> {
+ async fn issue(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ 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,
+ };
// Same lifetime as session runs: the 30-second deadline plus clock margin.
- let token = self.signer.mint_for(user, 60).await.map_err(|error| {
- tracing::error!(?error, "could not mint execution credential");
- CodeModeError::Unavailable
- })?;
+ let token = self
+ .signer
+ .mint_for_agent(user, 60, agent)
+ .await
+ .map_err(|error| {
+ tracing::error!(?error, "could not mint execution credential");
+ CodeModeError::Unavailable
+ })?;
Ok(RunEnvironment {
token,
trace_headers: trace_headers(),
diff --git a/services/agent_harness_service/src/public_mcp.rs b/services/agent_harness_service/src/public_mcp.rs
index bc5d1de7e5..0157e88618 100644
--- a/services/agent_harness_service/src/public_mcp.rs
+++ b/services/agent_harness_service/src/public_mcp.rs
@@ -76,10 +76,8 @@ pub async fn router(
Arc::new(CodeModeSurface {
native: ai_tools::tools_for_mcp_code_mode().toolset,
tools: Arc::new(agent_code_mode::inbound::toolset::user_toolset()),
- context: agent_code_mode::inbound::toolset::UserCodeModeToolContext {
- service: code_mode.service,
- cognition: tool_context.cognition_tool_context.service.clone(),
- },
+ service: code_mode.service,
+ cognition: tool_context.cognition_tool_context.service.clone(),
selector: Arc::new(CachedToolMode::new(code_mode.selector)),
})
});
diff --git a/services/agent_harness_service/src/public_mcp/tool_service.rs b/services/agent_harness_service/src/public_mcp/tool_service.rs
index 110f39631c..4206967c54 100644
--- a/services/agent_harness_service/src/public_mcp/tool_service.rs
+++ b/services/agent_harness_service/src/public_mcp/tool_service.rs
@@ -3,9 +3,11 @@ use crate::public_mcp::analytics::{
};
use crate::public_mcp::markdown_images::MarkdownImageResolver;
use crate::public_mcp::tool_response::tool_result_with_media;
-use agent_code_mode::inbound::toolset::UserCodeModeToolContext;
+use agent_code_mode::{domain::UserCodeMode, inbound::toolset::UserCodeModeToolContext};
use agent_inmem::domain::tool_mode::{ToolMode, ToolModeSelector};
+use ai_toolset::ToolCaller;
use ai_toolset::{AsyncToolCollection, RequestContext, ToolSet};
+use cognition::domain::Cognition;
use macro_user_id::user_id::MacroUserIdStr;
use rmcp::{
handler::server::ServerHandler,
@@ -41,14 +43,32 @@ fn definitions<Context>(toolset: &AsyncToolCollection<Context>) -> impl Iterator
})
}
+/// A tool context that runs its tools for the caller the request authenticated.
+pub trait CalledBy {
+ /// Run mutating tools for `caller`, still on the authenticated user's behalf.
+ fn called_by(self, caller: &ToolCaller) -> Self;
+}
+
+impl CalledBy for ai_tools::ToolServiceContext {
+ fn called_by(self, caller: &ToolCaller) -> Self {
+ self.for_caller(caller)
+ }
+}
+
+impl CalledBy for () {
+ fn called_by(self, _caller: &ToolCaller) -> Self {}
+}
+
/// Code mode for flagged users: SDK-covered native tools give way to the SDK.
pub struct CodeModeSurface<Context> {
/// Native tools still listed in code mode, from `tools_for_mcp_code_mode`.
pub native: Arc<AsyncToolCollection<Context>>,
/// `ExecuteCode`, `DescribeCodeTools` and `ReadCodeDocs`.
pub tools: Arc<AsyncToolCollection<UserCodeModeToolContext>>,
- /// User-scoped execution and Jev.
- pub context: UserCodeModeToolContext,
+ /// User-scoped execution.
+ pub service: Arc<dyn UserCodeMode>,
+ /// Jev, for selecting documentation by task.
+ pub cognition: Option<Arc<dyn Cognition>>,
/// The `ai-code-mode` flag, per user.
pub selector: Arc<dyn ToolModeSelector>,
}
@@ -136,12 +156,24 @@ impl<Context> AuthenticatedToolService<Context> {
}
}
+/// The caller the bearer middleware authenticated the request as. Every
+/// authenticated request carries one; there is no default to fall back to.
+/// Nothing the request says for itself (headers, arguments) can name a bot.
+fn caller(extensions: &rmcp::model::Extensions) -> Result<ToolCaller, rmcp::ErrorData> {
+ extensions
+ .get::<http::request::Parts>()
+ .and_then(|parts| parts.extensions.get::<ToolCaller>().cloned())
+ .ok_or_else(|| {
+ rmcp::ErrorData::internal_error("missing tool caller — is auth configured?", None)
+ })
+}
+
#[cfg(test)]
mod test;
impl<Context> ServerHandler for AuthenticatedToolService<Context>
where
- Context: Clone + Send + Sync + MarkdownImageResolver + 'static,
+ Context: Clone + Send + Sync + MarkdownImageResolver + CalledBy + 'static,
{
fn get_info(&self) -> ServerInfo {
let mut info = ServerInfo::new(ServerCapabilities::builder().enable_tools().build());
@@ -247,7 +279,7 @@ where
impl<Context> AuthenticatedToolService<Context>
where
- Context: Clone + Send + Sync + MarkdownImageResolver + 'static,
+ Context: Clone + Send + Sync + MarkdownImageResolver + CalledBy + 'static,
{
/// Runs one tool call and classifies how it ended, for analytics.
async fn run_tool(
@@ -260,6 +292,10 @@ where
Result<rmcp::model::CallToolResult, rmcp::ErrorData>,
) {
let mut request_context = RequestContext::new(user_id.clone());
+ let caller = match caller(&context.extensions) {
+ Ok(caller) => caller,
+ Err(error) => return (ToolCallOutcome::InvalidRequest, Err(error)),
+ };
let Some(arguments) = request.arguments.map(serde_json::Value::Object) else {
return (
@@ -284,7 +320,11 @@ where
let result = match code_mode
.tools
.try_tool_call(
- code_mode.context.clone(),
+ UserCodeModeToolContext {
+ service: code_mode.service.clone(),
+ cognition: code_mode.cognition.clone(),
+ caller,
+ },
request_context,
&request.name,
&arguments,
@@ -317,7 +357,7 @@ where
let result = match self
.toolset
.try_tool_call(
- self.context.clone(),
+ self.context.clone().called_by(&caller),
request_context,
&request.name,
&arguments,
diff --git a/services/agent_harness_service/src/public_mcp/tool_service/test.rs b/services/agent_harness_service/src/public_mcp/tool_service/test.rs
index 4ce670574e..51e51e242f 100644
--- a/services/agent_harness_service/src/public_mcp/tool_service/test.rs
+++ b/services/agent_harness_service/src/public_mcp/tool_service/test.rs
@@ -1,5 +1,6 @@
use super::*;
use ai_toolset::AsyncToolCollection;
+use bot_id::BotId;
use rmcp::{handler::server::ServerHandler, model::ErrorCode};
fn empty_service() -> AuthenticatedToolService<()> {
@@ -220,6 +221,51 @@ fn authenticated_user_id_requires_user_extension_inside_request_parts() {
assert_eq!(error.message, "missing user identity — is auth configured?");
}
+fn call_extensions(
+ caller: Option<ToolCaller>,
+ headers: &[(&str, &str)],
+) -> rmcp::model::Extensions {
+ let mut request = http::Request::new(());
+ for (name, value) in headers {
+ request.headers_mut().insert(
+ http::HeaderName::from_bytes(name.as_bytes()).unwrap(),
+ http::HeaderValue::from_str(value).unwrap(),
+ );
+ }
+ let mut parts = request.into_parts().0;
+ if let Some(caller) = caller {
+ parts.extensions.insert(caller);
+ }
+ let mut extensions = rmcp::model::Extensions::new();
+ extensions.insert(parts);
+ extensions
+}
+
+/// The caller is whatever the bearer middleware authenticated; a bot the
+/// request names for itself never replaces it.
+#[test]
+fn the_caller_is_the_authenticated_one_not_one_the_request_names() {
+ let forged = BotId::TEST_A.to_string();
+
+ assert_eq!(
+ caller(&call_extensions(
+ Some(ToolCaller::ApiKey),
+ &[("x-macro-agent-id", &forged), ("x-macro-bot-id", &forged)],
+ ))
+ .unwrap(),
+ ToolCaller::ApiKey
+ );
+}
+
+/// With no authenticated caller there is nothing to write as, so the call
+/// fails instead of falling back to the Macro bot.
+#[test]
+fn a_call_without_a_caller_is_refused() {
+ let error = caller(&call_extensions(None, &[])).expect_err("no caller");
+
+ assert_eq!(error.code, ErrorCode::INTERNAL_ERROR);
+}
+
mod code_mode {
use super::*;
use agent_code_mode::domain::{
@@ -257,17 +303,19 @@ mod code_mode {
}
}
- /// Records who ran what and returns the source length as data.
+ /// Records who ran what, as which agent, and returns the source length as data.
#[derive(Default)]
- struct Runs(Mutex<Vec<(String, String)>>);
+ struct Runs(Mutex<Vec<(String, String)>>, Mutex<Vec<ToolCaller>>);
#[async_trait::async_trait]
impl UserCodeMode for Runs {
async fn execute(
&self,
user: &MacroUserIdStr<'static>,
+ caller: &ToolCaller,
request: ExecuteRequest,
_: CancellationToken,
) -> Result<UserExecutionReceipt, CodeModeError> {
+ self.1.lock().unwrap().push(caller.clone());
self.0
.lock()
.unwrap()
@@ -286,10 +334,8 @@ mod code_mode {
let surface = Arc::new(CodeModeSurface {
native: Arc::new(AsyncToolCollection::new()),
tools: Arc::new(agent_code_mode::inbound::toolset::user_toolset()),
- context: agent_code_mode::inbound::toolset::UserCodeModeToolContext {
- service: runs,
- cognition: None,
- },
+ service: runs,
+ cognition: None,
selector: Arc::new(Flag),
});
let mut config =
@@ -301,7 +347,8 @@ mod code_mode {
Arc::new(LocalSessionManager::default()),
config,
);
- // Stands in for the OAuth bearer middleware, which inserts the user id.
+ // Stands in for the bearer middleware's user id; each request carries
+ // its caller as the middleware would leave it.
axum::Router::new()
.nest_service("/mcp", service)
.layer(axum::middleware::from_fn(
@@ -321,9 +368,24 @@ mod code_mode {
method: &str,
params: serde_json::Value,
) -> serde_json::Value {
+ rpc_as(app, user, Some(ToolCaller::ApiKey), method, params).await
+ }
+
+ /// An RPC the bearer middleware authenticated as `caller`.
+ async fn rpc_as(
+ app: axum::Router,
+ user: &str,
+ caller: Option<ToolCaller>,
+ method: &str,
+ params: serde_json::Value,
+ ) -> serde_json::Value {
+ let mut request = Request::builder();
+ if let Some(caller) = caller {
+ request = request.extension(caller);
+ }
let response = app
.oneshot(
- Request::builder()
+ request
.method("POST")
.uri("/mcp")
.header("host", "localhost")
@@ -417,6 +479,54 @@ mod code_mode {
);
}
+ /// `ExecuteCode` runs for exactly the caller the middleware
+ /// authenticated, one per kind, so its credential can be minted for it.
+ #[tokio::test]
+ async fn execute_code_runs_for_each_kind_of_caller() {
+ let runs = Arc::new(Runs::default());
+ let app = app(runs.clone());
+ let call = serde_json::json!({
+ "name": "ExecuteCode",
+ "arguments": {"source": "export async function main() { return {data: 1}; }"},
+ });
+ let callers = [
+ ToolCaller::Agent(BotId::TEST_A),
+ ToolCaller::McpClient {
+ name: Some("Claude Code".to_owned()),
+ },
+ ToolCaller::ApiKey,
+ ];
+
+ for caller in callers.clone() {
+ rpc_as(
+ app.clone(),
+ FLAGGED,
+ Some(caller),
+ "tools/call",
+ call.clone(),
+ )
+ .await;
+ }
+
+ assert_eq!(*runs.1.lock().unwrap(), callers);
+ }
+
+ /// A request the middleware left without a caller runs nothing.
+ #[tokio::test]
+ async fn execute_code_without_a_caller_runs_nothing() {
+ let runs = Arc::new(Runs::default());
+ let app = app(runs.clone());
+ let call = serde_json::json!({
+ "name": "ExecuteCode",
+ "arguments": {"source": "export async function main() { return {data: 1}; }"},
+ });
+
+ let response = rpc_as(app, FLAGGED, None, "tools/call", call).await;
+
+ assert!(response.get("error").is_some());
+ assert!(runs.1.lock().unwrap().is_empty());
+ }
+
#[test]
fn code_mode_tools_meet_directory_requirements() {
for (name, tool) in agent_code_mode::inbound::toolset::user_toolset()
@@ -436,6 +546,7 @@ mod code_mode {
async fn issue(
&self,
_: &MacroUserIdStr<'static>,
+ _: &ToolCaller,
) -> Result<code_execution::domain::RunEnvironment, CodeModeError> {
Ok(code_execution::domain::RunEnvironment::default())
}
diff --git a/services/mcp_auth_proxy/Cargo.toml b/services/mcp_auth_proxy/Cargo.toml
index 4fa791d2aa..79dbf278b8 100644
--- a/services/mcp_auth_proxy/Cargo.toml
+++ b/services/mcp_auth_proxy/Cargo.toml
@@ -8,7 +8,9 @@ version = "0.1.0"
[features]
default = ["inbound", "outbound"]
inbound = [
+ "dep:ai_toolset",
"dep:axum",
+ "dep:bot_id",
"dep:macro_auth",
"dep:macro_user_id",
"dep:tower",
@@ -18,8 +20,10 @@ outbound = ["dep:fusionauth"]
[dependencies]
anyhow = { workspace = true }
+ai_toolset = { path = "../../crates/ai_toolset", optional = true }
axum = { workspace = true, features = ["tower-log"], optional = true }
base64 = { workspace = true }
+bot_id = { path = "../../crates/bot_id", optional = true }
fusionauth = { path = "../../crates/fusionauth", optional = true }
macro_auth = { path = "../../crates/macro_auth", optional = true }
macro_user_id = { path = "../../crates/macro_user_id", optional = true }
diff --git a/services/mcp_auth_proxy/README.md b/services/mcp_auth_proxy/README.md
index f24fab2c28..1e1262998b 100644
--- a/services/mcp_auth_proxy/README.md
+++ b/services/mcp_auth_proxy/README.md
@@ -86,6 +86,19 @@ refresh: the new token is bound before the superseded one is dropped, so a
replay of a token the broker has already rotated past finds no binding and is
refused.
+Access tokens are recorded the same way, so the `/mcp` route can tell which
+client a request comes from: both grants bind the access token they hand out to
+the same client and grant, through the same `RefreshTokenBindingStore`, under a
+SHA-256 digest taken with a fixed prefix so it can never match a refresh token's
+binding (`domain/access_token_clients.rs`). The bearer middleware reads the
+binding and the client's registered `client_name` and attaches the request's
+caller (`ai_toolset::ToolCaller`) for the tools, which label what the client
+writes "via <client_name>". The name is self-reported at `/register`: a display
+label, never an identity or permission. A token issued before its binding was
+recorded carries no name; the client's next refresh records one. Reading the
+records only through the existing ports keeps them working on any store
+backend.
+
Refresh tokens issued before this scheme existed have no binding, so the clients
holding them authorize once more. Rate limiting of `/register` belongs at the
edge; the broker bounds each registration's size but not how many a caller may
diff --git a/services/mcp_auth_proxy/src/domain.rs b/services/mcp_auth_proxy/src/domain.rs
index e6e4903fc6..395f0c4199 100644
--- a/services/mcp_auth_proxy/src/domain.rs
+++ b/services/mcp_auth_proxy/src/domain.rs
@@ -1,5 +1,7 @@
//! Domain logic for the MCP OAuth broker.
+/// Which registered client each issued access token went to.
+pub mod access_token_clients;
/// Domain models for broker-managed OAuth state and request payloads.
pub mod models;
/// Domain port traits for upstream OAuth providers and broker state stores.
diff --git a/services/mcp_auth_proxy/src/domain/access_token_clients.rs b/services/mcp_auth_proxy/src/domain/access_token_clients.rs
new file mode 100644
index 0000000000..57cfe6f490
--- /dev/null
+++ b/services/mcp_auth_proxy/src/domain/access_token_clients.rs
@@ -0,0 +1,85 @@
+//! Which registered client an access token was issued to.
+//!
+//! The upstream access token names the user but not the client, so the broker
+//! records the client at every token exchange and the MCP route reads it back
+//! to label what the client writes ("via Claude Code"). The record goes
+//! through the same binding store as refresh tokens, under a digest no refresh
+//! token can produce, so every store backend answers both without a new port.
+
+#[cfg(test)]
+mod test;
+
+use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
+use sha2::{Digest, Sha256};
+use std::sync::Arc;
+
+use super::{
+ models::RefreshTokenBinding,
+ ports::{ClientRegistrationStore, RefreshTokenBindingStore},
+};
+
+/// Prefixed to an access token before hashing, so its digest can never match
+/// a refresh token's and be honored by the refresh exchange.
+const ACCESS_TOKEN_DIGEST_DOMAIN: &str = "mcp_auth_proxy:access_token:";
+
+/// The longest client name a label carries; registration does not bound it.
+const MAX_CLIENT_NAME_CHARS: usize = 64;
+
+/// Records and reads the client behind each access token the broker issues.
+#[derive(Clone)]
+pub struct AccessTokenClients {
+ bindings: Arc<dyn RefreshTokenBindingStore>,
+ clients: Arc<dyn ClientRegistrationStore>,
+}
+
+impl AccessTokenClients {
+ /// Build over the broker's binding and registration stores.
+ pub fn new(
+ bindings: Arc<dyn RefreshTokenBindingStore>,
+ clients: Arc<dyn ClientRegistrationStore>,
+ ) -> Self {
+ Self { bindings, clients }
+ }
+
+ /// Record that `access_token` was issued under `binding`.
+ pub async fn bind(
+ &self,
+ access_token: &str,
+ binding: &RefreshTokenBinding,
+ ) -> anyhow::Result<()> {
+ self.bindings
+ .bind(&access_token_digest(access_token), binding)
+ .await
+ }
+
+ /// The registered name of the client `access_token` was issued to.
+ /// `None` when the broker never recorded one: a token issued before it
+ /// did, or one whose client registration has lapsed.
+ pub async fn client_name(&self, access_token: &str) -> anyhow::Result<Option<String>> {
+ let Some(binding) = self
+ .bindings
+ .binding(&access_token_digest(access_token))
+ .await?
+ else {
+ return Ok(None);
+ };
+ Ok(self
+ .clients
+ .find_client(&binding.client_id)
+ .await?
+ .map(|client| {
+ client
+ .client_name
+ .chars()
+ .take(MAX_CLIENT_NAME_CHARS)
+ .collect()
+ }))
+ }
+}
+
+fn access_token_digest(access_token: &str) -> String {
+ let mut hasher = Sha256::new();
+ hasher.update(ACCESS_TOKEN_DIGEST_DOMAIN.as_bytes());
+ hasher.update(access_token.as_bytes());
+ URL_SAFE_NO_PAD.encode(hasher.finalize())
+}
diff --git a/services/mcp_auth_proxy/src/domain/access_token_clients/test.rs b/services/mcp_auth_proxy/src/domain/access_token_clients/test.rs
new file mode 100644
index 0000000000..a2834b4834
--- /dev/null
+++ b/services/mcp_auth_proxy/src/domain/access_token_clients/test.rs
@@ -0,0 +1,72 @@
+use super::*;
+use crate::{domain::models::RegisteredClient, test_support::FakeClientRegistry};
+
+fn clients(registry: &Arc<FakeClientRegistry>) -> AccessTokenClients {
+ AccessTokenClients::new(
+ Arc::clone(registry) as Arc<dyn RefreshTokenBindingStore>,
+ Arc::clone(registry) as Arc<dyn ClientRegistrationStore>,
+ )
+}
+
+#[tokio::test]
+async fn an_access_token_names_the_client_it_was_issued_to() {
+ let registry = Arc::new(FakeClientRegistry::default());
+ registry
+ .insert_client(&RegisteredClient {
+ client_id: "client-1".to_owned(),
+ client_name: "Claude Code".to_owned(),
+ redirect_uris: vec![],
+ })
+ .await
+ .unwrap();
+ let clients = clients(&registry);
+ clients
+ .bind(
+ "access-token",
+ &RefreshTokenBinding {
+ client_id: "client-1".to_owned(),
+ grant_id: "grant-1".to_owned(),
+ },
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ clients
+ .client_name("access-token")
+ .await
+ .unwrap()
+ .as_deref(),
+ Some("Claude Code")
+ );
+ assert_eq!(clients.client_name("another-token").await.unwrap(), None);
+}
+
+#[tokio::test]
+async fn a_long_self_reported_name_is_cut_to_a_label() {
+ let registry = Arc::new(FakeClientRegistry::default());
+ registry
+ .insert_client(&RegisteredClient {
+ client_id: "client-1".to_owned(),
+ client_name: "x".repeat(500),
+ redirect_uris: vec![],
+ })
+ .await
+ .unwrap();
+ let clients = clients(&registry);
+ clients
+ .bind(
+ "access-token",
+ &RefreshTokenBinding {
+ client_id: "client-1".to_owned(),
+ grant_id: "grant-1".to_owned(),
+ },
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ clients.client_name("access-token").await.unwrap(),
+ Some("x".repeat(64))
+ );
+}
diff --git a/services/mcp_auth_proxy/src/domain/service.rs b/services/mcp_auth_proxy/src/domain/service.rs
index a691531221..2d069d356c 100644
--- a/services/mcp_auth_proxy/src/domain/service.rs
+++ b/services/mcp_auth_proxy/src/domain/service.rs
@@ -12,6 +12,7 @@ use std::{
};
use super::{
+ access_token_clients::AccessTokenClients,
models::{
AuthorizeRequest, CallbackRequest, ClientRegistrationRequest, ClientRegistrationResponse,
IssuedAuthorizationCode, PendingAuthorization, RefreshToken, RefreshTokenBinding,
@@ -145,6 +146,7 @@ pub struct McpAuthProxyServiceImpl<I> {
inflight_auth: Arc<I>,
client_registrations: Arc<dyn ClientRegistrationStore>,
refresh_token_bindings: Arc<dyn RefreshTokenBindingStore>,
+ access_token_clients: AccessTokenClients,
oauth_provider: Arc<dyn OAuthProvider>,
redirect_uri_policy: RedirectUriPolicy,
public_url: String,
@@ -156,6 +158,7 @@ impl<I> Clone for McpAuthProxyServiceImpl<I> {
inflight_auth: Arc::clone(&self.inflight_auth),
client_registrations: Arc::clone(&self.client_registrations),
refresh_token_bindings: Arc::clone(&self.refresh_token_bindings),
+ access_token_clients: self.access_token_clients.clone(),
oauth_provider: Arc::clone(&self.oauth_provider),
redirect_uri_policy: self.redirect_uri_policy.clone(),
public_url: self.public_url.clone(),
@@ -180,6 +183,10 @@ where
Self {
inflight_auth,
+ access_token_clients: AccessTokenClients::new(
+ Arc::clone(&refresh_token_bindings),
+ Arc::clone(&client_registrations),
+ ),
client_registrations,
refresh_token_bindings,
oauth_provider,
@@ -188,6 +195,28 @@ where
}
}
+ /// The record of which client each issued access token went to, for the
+ /// MCP route to label what a client writes.
+ pub fn access_token_clients(&self) -> AccessTokenClients {
+ self.access_token_clients.clone()
+ }
+
+ /// Records the client an access token was issued to. Like a failed
+ /// rebind, a failed write costs only the label on that token's writes, so
+ /// it is logged rather than withholding a token the user approved.
+ async fn bind_access_token(&self, access_token: &str, binding: &RefreshTokenBinding) {
+ self.access_token_clients
+ .bind(access_token, binding)
+ .await
+ .unwrap_or_else(|error| {
+ tracing::error!(
+ error=?error,
+ client_id = %binding.client_id,
+ "failed to record the client an access token was issued to"
+ );
+ });
+ }
+
/// Refreshes an upstream token for the client the refresh token belongs to.
///
/// A public client has no credential to present, so the binding recorded
@@ -253,6 +282,9 @@ where
})
.is_ok();
+ self.bind_access_token(tokens.access_token.as_str(), &binding)
+ .await;
+
if rebound && rotated_digest != presented_digest {
self.refresh_token_bindings
.unbind(&presented_digest)
@@ -325,16 +357,16 @@ where
None => return Err(TokenExchangeError::CodeVerifierRequired),
}
+ let binding = RefreshTokenBinding {
+ client_id: issued.client_id,
+ grant_id: uuid::Uuid::new_v4().to_string(),
+ };
self.refresh_token_bindings
- .bind(
- &refresh_token_digest(&issued.refresh_token),
- &RefreshTokenBinding {
- client_id: issued.client_id,
- grant_id: uuid::Uuid::new_v4().to_string(),
- },
- )
+ .bind(&refresh_token_digest(&issued.refresh_token), &binding)
.await
.map_err(TokenExchangeError::RefreshTokenBindingStore)?;
+ self.bind_access_token(issued.access_token.as_str(), &binding)
+ .await;
Ok(TokenResponse {
access_token: issued.access_token,
diff --git a/services/mcp_auth_proxy/src/domain/service/test.rs b/services/mcp_auth_proxy/src/domain/service/test.rs
index 5c8ca72fc8..e3a418c7ef 100644
--- a/services/mcp_auth_proxy/src/domain/service/test.rs
+++ b/services/mcp_auth_proxy/src/domain/service/test.rs
@@ -878,3 +878,46 @@ fn protected_resource_metadata_does_not_double_the_mcp_path() {
})
);
}
+
+// --- Access token clients ------------------------------------------------
+
+#[tokio::test]
+async fn both_token_exchanges_record_the_client_behind_the_access_token() {
+ let harness = Harness::new();
+ let client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;
+ let refresh_token = obtain_refresh_token(&harness, &client_id).await;
+ harness
+ .service
+ .exchange_token(refresh_request(refresh_token, &client_id))
+ .await
+ .expect("refreshed");
+
+ let clients = harness.service.access_token_clients();
+ for access_token in [UPSTREAM_ACCESS_TOKEN, REFRESHED_ACCESS_TOKEN] {
+ assert_eq!(
+ clients.client_name(access_token).await.unwrap().as_deref(),
+ Some("test-client"),
+ "{access_token}"
+ );
+ }
+}
+
+/// The access token's record shares the refresh binding store, under a digest
+/// no refresh token produces, so it can never be refreshed with.
+#[tokio::test]
+async fn an_access_token_cannot_be_presented_as_a_refresh_token() {
+ let harness = Harness::new();
+ let client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;
+ obtain_refresh_token(&harness, &client_id).await;
+
+ let error = harness
+ .service
+ .exchange_token(refresh_request(
+ RefreshToken::from(UPSTREAM_ACCESS_TOKEN),
+ &client_id,
+ ))
+ .await
+ .expect_err("an access token is not a refresh token");
+
+ assert!(matches!(error, TokenExchangeError::UnboundRefreshToken));
+}
diff --git a/services/mcp_auth_proxy/src/inbound/axum_router.rs b/services/mcp_auth_proxy/src/inbound/axum_router.rs
index 9743b8e31a..f6b8f377be 100644
--- a/services/mcp_auth_proxy/src/inbound/axum_router.rs
+++ b/services/mcp_auth_proxy/src/inbound/axum_router.rs
@@ -388,7 +388,14 @@ where
S::Response: axum::response::IntoResponse,
S::Future: Send + 'static,
{
- mcp_router_with_oauth(oauth_router(auth_proxy), jwt_args, mcp_service)
+ {
+ let clients = auth_proxy.access_token_clients();
+ mcp_router_with_oauth(
+ oauth_router(auth_proxy),
+ super::middleware::BearerAuth { jwt_args, clients },
+ mcp_service,
+ )
+ }
}
/// MCP routes for a shared HTTP listener whose process owns health checks.
@@ -407,10 +414,21 @@ where
S::Response: axum::response::IntoResponse,
S::Future: Send + 'static,
{
- mcp_router_with_oauth(oauth_routes(auth_proxy), jwt_args, mcp_service)
+ {
+ let clients = auth_proxy.access_token_clients();
+ mcp_router_with_oauth(
+ oauth_routes(auth_proxy),
+ super::middleware::BearerAuth { jwt_args, clients },
+ mcp_service,
+ )
+ }
}
-fn mcp_router_with_oauth<S>(oauth: Router, jwt_args: JwtValidationArgs, mcp_service: S) -> Router
+fn mcp_router_with_oauth<S>(
+ oauth: Router,
+ auth: super::middleware::BearerAuth,
+ mcp_service: S,
+) -> Router
where
S: tower::Service<axum::http::Request<axum::body::Body>, Error = std::convert::Infallible>
+ Clone
@@ -424,7 +442,7 @@ where
Router::new()
.nest_service("/mcp", mcp_service)
.layer(axum_mw::from_fn_with_state(
- jwt_args,
+ auth,
super::middleware::validate_bearer,
));
diff --git a/services/mcp_auth_proxy/src/inbound/middleware.rs b/services/mcp_auth_proxy/src/inbound/middleware.rs
index fad6f67314..f07064b90a 100644
--- a/services/mcp_auth_proxy/src/inbound/middleware.rs
+++ b/services/mcp_auth_proxy/src/inbound/middleware.rs
@@ -3,6 +3,7 @@
#[cfg(test)]
mod test;
+use ai_toolset::ToolCaller;
use axum::{
body::Body,
http::{
@@ -10,13 +11,25 @@ use axum::{
header::{HeaderValue, WWW_AUTHENTICATE},
},
};
+use bot_id::BotId;
use macro_auth::middleware::decode_jwt::{JwtToken, JwtValidationArgs, handler};
+
+use crate::domain::access_token_clients::AccessTokenClients;
use macro_user_id::user_id::MacroUserIdStr;
/// Validated Macro JWT from the `Authorization: Bearer` header.
#[derive(Clone)]
pub struct JwtAccessToken(pub String);
+/// What the bearer middleware validates a request with.
+#[derive(Clone)]
+pub struct BearerAuth {
+ /// Signature, audience, and issuer checks for both token kinds.
+ pub jwt_args: JwtValidationArgs,
+ /// Which client each OAuth access token was issued to.
+ pub clients: AccessTokenClients,
+}
+
/// Which kind of credential authenticated an MCP request.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum McpAuthMethod {
@@ -97,9 +110,17 @@ fn unauthorized_response(request: &Request<Body>, error: Option<&str>) -> Respon
}
/// Validates `Authorization: Bearer <token>` and stores the authenticated
-/// [`MacroUserIdStr`] and its [`McpAuthMethod`] in the request extensions.
+/// [`MacroUserIdStr`], its [`McpAuthMethod`], and its [`ToolCaller`] in the
+/// request extensions. Every authenticated request carries a caller:
+/// - a Macro API token signed for an agent (only key holders such as the
+/// agent harness's egress sign the claim, so a client cannot name a bot) is
+/// [`ToolCaller::Agent`];
+/// - an OAuth access token is [`ToolCaller::McpClient`], named after the
+/// client the broker issued it to;
+/// - any other Macro API token is a pasted key, [`ToolCaller::ApiKey`].
+#[tracing::instrument(skip_all, fields(caller = tracing::field::Empty))]
pub async fn validate_bearer(
- axum::extract::State(jwt_args): axum::extract::State<JwtValidationArgs>,
+ axum::extract::State(auth): axum::extract::State<BearerAuth>,
mut request: Request<Body>,
next: axum::middleware::Next,
) -> axum::response::Response {
@@ -115,7 +136,7 @@ pub async fn validate_bearer(
return unauthorized_response(&request, None);
};
- let jwt_token = match handler(&jwt_args, &token) {
+ let jwt_token = match handler(&auth.jwt_args, &token) {
Ok(token) => token,
Err(error) => {
tracing::warn!(error=?error, "MCP bearer token validation failed");
@@ -123,10 +144,33 @@ pub async fn validate_bearer(
}
};
- let (user_id, auth_method) = match jwt_token {
- JwtToken::MacroAccessToken(token) => (token.macro_user_id, McpAuthMethod::OAuth),
- JwtToken::MacroApiToken(token) => (token.macro_user_id, McpAuthMethod::ApiKey),
+ let (user_id, auth_method, caller) = match jwt_token {
+ JwtToken::MacroAccessToken(access) => {
+ let name = match auth.clients.client_name(&token).await {
+ Ok(name) => name,
+ Err(error) => {
+ tracing::error!(error=?error, "could not read the client an access token was issued to");
+ let mut response = Response::new(Body::empty());
+ *response.status_mut() = StatusCode::SERVICE_UNAVAILABLE;
+ return response;
+ }
+ };
+ (
+ access.macro_user_id,
+ McpAuthMethod::OAuth,
+ ToolCaller::McpClient { name },
+ )
+ }
+ JwtToken::MacroApiToken(api) => (
+ api.macro_user_id,
+ McpAuthMethod::ApiKey,
+ match api.agent_id {
+ Some(agent) => ToolCaller::Agent(BotId::new_from_uuid(agent)),
+ None => ToolCaller::ApiKey,
+ },
+ ),
};
+ tracing::Span::current().record("caller", tracing::field::debug(&caller));
let user_id = match MacroUserIdStr::try_from(user_id) {
Ok(user_id) => user_id,
@@ -138,6 +182,7 @@ pub async fn validate_bearer(
request.extensions_mut().insert(user_id);
request.extensions_mut().insert(auth_method);
+ request.extensions_mut().insert(caller);
request.extensions_mut().insert(JwtAccessToken(token));
next.run(request).await