Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(agents): MCP skill and tools for updating agent instructions and settings (#7248)
Wolf Mermelstein392740e8797e
diff --git a/apps/docs/AI/mcp/tools/configure-agent.mdx b/apps/docs/AI/mcp/tools/configure-agent.mdxnew file mode 100644index 0000000000..f04ee03561--- /dev/null+++ b/apps/docs/AI/mcp/tools/configure-agent.mdx@@ -0,0 +1,24 @@+---+title: ConfigureAgent+description: "Update the instructions or settings of an AI agent the current user can manage. Provide only the fields that should change; everything else keeps its current value. Read the agent first with ListAgents: instructions are replaced whole, so to edit them, apply the edit to the current text and pass the complete result. Changes apply to sessions opened afterwards; running sessions keep the instructions they started with. Use ConfigureBot for the display name, handle, description, or picture, and ManageBotChannelAccess for plain webhook bots."+---++# ConfigureAgent++Update the instructions or settings of an AI agent the current user can manage. Provide only the fields that should change; everything else keeps its current value. Read the agent first with ListAgents: instructions are replaced whole, so to edit them, apply the edit to the current text and pass the complete result. Changes apply to sessions opened afterwards; running sessions keep the instructions they started with. Use ConfigureBot for the display name, handle, description, or picture, and ManageBotChannelAccess for plain webhook bots.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `botId` | string | Yes | The agent's bot id: `bot.botId` from ListAgents. |+| `instructions` | string | No | The complete new instructions in markdown. Replaces the current instructions entirely; omit to keep them. |+| `harness` | `"in-memory"` \| `"cursor"` \| `"claude-cloud"` \| `"macrod"` | No | Runtime to move the agent onto. `macrod` also needs harnessId; the other runtimes must not have one. The current model may not exist on the new runtime, so usually pass defaultModel with it. Omit to keep the current runtime. |+| `harnessId` | string | No | Id of the registered self-hosted harness, required when harness is `macrod` and forbidden otherwise. |+| `defaultModel` | string | No | Model id the agent's new sessions should use, as the runtime names it (e.g. `claude-sonnet-4-5`). Valid ids depend on the runtime. Omit to keep the current model. |+| `channelScope` | `"all"` \| `"selected"` | No | `all` makes the agent mentionable in every channel its owner can use; `selected` limits it to channelIds. Omit to keep the current scope, or omit it and pass channelIds alone to switch to `selected`. |+| `channelIds` | string[] | No | The complete list of channel ids the agent is limited to; the user must be a member of each. Required with the `selected` scope and forbidden with `all`. |+| `mcpScope` | `"owner_connections"` \| `"selected"` | No | `owner_connections` hands sessions whatever apps the person running them has connected; `selected` hands exactly mcpServers. Omit to keep the current scope, or omit it and pass mcpServers alone to switch to `selected`. |+| `mcpServers` | AgentMcpServerSummary[] | No | The complete list of connected apps for the `selected` MCP scope, each as its Pipedream app slug (e.g. `linear`) and display name. A slug Pipedream does not list as a connectable app is rejected and nothing is saved. Forbidden with `owner_connections`. |+| `autoAcceptPermissions` | boolean | No | `true` lets sessions approve tool permission requests without asking, where the runtime allows it; `false` makes them ask every time. Omit to leave unchanged. |+| `isCoding` | boolean | No | `true` for a coding agent, which works in a repository and answers a mention with a live session; `false` for a chat agent, which replies in the thread. Omit to leave unchanged. |diff --git a/apps/docs/AI/mcp/tools/index.mdx b/apps/docs/AI/mcp/tools/index.mdxindex 407dcbe033..d5853caacc 100644--- a/apps/docs/AI/mcp/tools/index.mdx+++ b/apps/docs/AI/mcp/tools/index.mdx@@ -14,6 +14,7 @@ These pages are generated from Macro's Rust MCP tool registry.- [BulkSetEntityPropertyOptions](/AI/mcp/tools/bulk-set-entity-property-options)- [CalculateSpreadsheet](/AI/mcp/tools/calculate-spreadsheet)- [CommentOnDocument](/AI/mcp/tools/comment-on-document)+- [ConfigureAgent](/AI/mcp/tools/configure-agent)- [ConfigureBot](/AI/mcp/tools/configure-bot)- [ContentSearch](/AI/mcp/tools/content-search)- [CreateBot](/AI/mcp/tools/create-bot)@@ -42,6 +43,7 @@ These pages are generated from Macro's Rust MCP tool registry.- [GetThread](/AI/mcp/tools/get-thread)- [ImportNotionPage](/AI/mcp/tools/import-notion-page)- [IssueBotCredential](/AI/mcp/tools/issue-bot-credential)+- [ListAgents](/AI/mcp/tools/list-agents)- [ListBots](/AI/mcp/tools/list-bots)- [ListCalendarEvents](/AI/mcp/tools/list-calendar-events)- [ListCalendars](/AI/mcp/tools/list-calendars)diff --git a/apps/docs/AI/mcp/tools/list-agents.mdx b/apps/docs/AI/mcp/tools/list-agents.mdxnew file mode 100644index 0000000000..6267deac9c--- /dev/null+++ b/apps/docs/AI/mcp/tools/list-agents.mdx@@ -0,0 +1,8 @@+---+title: ListAgents+description: "List every AI agent the current user can manage - their own, their teams', and channel agents they can mention - with each agent's current instructions and settings: harness, model, channel availability, connected apps, permission behavior, and whether it is a coding or chat agent. Use this to find an agent's botId and read its current configuration before changing it with ConfigureAgent. ListBots covers plain webhook bots instead."+---++# ListAgents++List every AI agent the current user can manage - their own, their teams', and channel agents they can mention - with each agent's current instructions and settings: harness, model, channel availability, connected apps, permission behavior, and whether it is a coding or chat agent. Use this to find an agent's botId and read its current configuration before changing it with ConfigureAgent. ListBots covers plain webhook bots instead.diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.jsonindex b600539d13..4fe795e264 100644--- a/apps/docs/config/tool-pages.json+++ b/apps/docs/config/tool-pages.json@@ -5,6 +5,7 @@"AI/mcp/tools/bulk-set-entity-property-options","AI/mcp/tools/calculate-spreadsheet","AI/mcp/tools/comment-on-document",+ "AI/mcp/tools/configure-agent","AI/mcp/tools/configure-bot","AI/mcp/tools/content-search","AI/mcp/tools/create-bot",@@ -33,6 +34,7 @@"AI/mcp/tools/get-thread","AI/mcp/tools/import-notion-page","AI/mcp/tools/issue-bot-credential",+ "AI/mcp/tools/list-agents","AI/mcp/tools/list-bots","AI/mcp/tools/list-calendar-events","AI/mcp/tools/list-calendars",diff --git a/apps/docs/docs.json b/apps/docs/docs.jsonindex a839ec06ed..f8214b42a9 100644--- a/apps/docs/docs.json+++ b/apps/docs/docs.json@@ -76,6 +76,7 @@"AI/mcp/tools/bulk-set-entity-property-options","AI/mcp/tools/calculate-spreadsheet","AI/mcp/tools/comment-on-document",+ "AI/mcp/tools/configure-agent","AI/mcp/tools/configure-bot","AI/mcp/tools/content-search","AI/mcp/tools/create-bot",@@ -104,6 +105,7 @@"AI/mcp/tools/get-thread","AI/mcp/tools/import-notion-page","AI/mcp/tools/issue-bot-credential",+ "AI/mcp/tools/list-agents","AI/mcp/tools/list-bots","AI/mcp/tools/list-calendar-events","AI/mcp/tools/list-calendars",diff --git a/apps/web/src/lib/core/component/AI/component/tool/Agents.tsx b/apps/web/src/lib/core/component/AI/component/tool/Agents.tsxnew file mode 100644index 0000000000..c74c7df2e2--- /dev/null+++ b/apps/web/src/lib/core/component/AI/component/tool/Agents.tsx@@ -0,0 +1,186 @@+import HeadCircuit from '@phosphor-icons/core/regular/head-circuit.svg';+import UserGear from '@phosphor-icons/core/regular/user-gear.svg';+import type { NamedTool } from '@service-cognition/generated/tools/tool';+import type { AgentSummary } from '@service-cognition/generated/tools/types';+import { createSignal, For, Show } from 'solid-js';+import { BaseTool } from './BaseTool';+import { type Detail, DetailPanel, ownerLabel } from './Bots';+import { Tool } from './Tool';+import { createToolRenderer } from './ToolRenderer';++const HARNESS_NAMES: Record<string, string> = {+ 'in-memory': 'Macro',+ cursor: 'Cursor',+ 'claude-cloud': 'Claude Cloud',+ macrod: 'Self-hosted harness',+};++function harnessLabel(agent: AgentSummary): string {+ const name = HARNESS_NAMES[agent.harness] ?? agent.harness;+ return agent.harnessId ? `${name} · ${agent.harnessId}` : name;+}++function channelsLabel(agent: AgentSummary): string {+ if (agent.channelScope === 'all') return 'All channels';+ const count = agent.channelIds.length;+ return `${count} selected channel${count === 1 ? '' : 's'}`;+}++function appsLabel(agent: AgentSummary): string {+ if (agent.mcpScope === 'owner_connections') return "Session owner's apps";+ if (agent.mcpServers.length === 0) return 'None';+ return agent.mcpServers.map((server) => server.serverName).join(', ');+}++function permissionsLabel(agent: AgentSummary): string {+ return agent.autoAcceptPermissions ? 'Approve automatically' : 'Ask first';+}++function agentDetails(agent: AgentSummary): Detail[] {+ return [+ { label: 'Agent ID', value: agent.bot.botId, secret: true },+ { label: 'Handle', value: `@${agent.bot.handle}` },+ { label: 'Owner', value: ownerLabel(agent.bot.owner) },+ { label: 'Runtime', value: harnessLabel(agent) },+ { label: 'Model', value: agent.defaultModel },+ { label: 'Channels', value: channelsLabel(agent) },+ { label: 'Connected apps', value: appsLabel(agent) },+ { label: 'Permissions', value: permissionsLabel(agent) },+ { label: 'Mode', value: agent.isCoding ? 'Coding agent' : 'Chat agent' },+ ];+}++function AgentInstructions(props: { instructions: string }) {+ return (+ <div class="rounded-lg border border-edge-muted bg-ink/[0.02] p-3">+ <p class="mb-2 text-xs text-ink-extra-muted">Instructions</p>+ <Show+ when={props.instructions.trim().length > 0}+ fallback={<p class="text-xs text-ink-muted italic">No instructions</p>}+ >+ <pre class="max-h-60 overflow-y-auto whitespace-pre-wrap break-words font-sans text-xs text-ink">+ {props.instructions}+ </pre>+ </Show>+ </div>+ );+}++function AgentPanel(props: { agent: AgentSummary; summary?: string }) {+ return (+ <div class="flex flex-col gap-2">+ <DetailPanel+ details={agentDetails(props.agent)}+ summary={props.summary}+ />+ <AgentInstructions instructions={props.agent.instructions} />+ </div>+ );+}++type ListedAgent = NamedTool<+ 'ListAgents',+ 'response'+>['data']['agents'][number];++function AgentList(props: { agents: ListedAgent[] }) {+ return (+ <Tool.List>+ <div class="max-h-60 overflow-y-auto overscroll-contain">+ <For each={props.agents}>+ {(agent) => (+ <Tool.ListItem icon={<HeadCircuit class="size-4" />}>+ <div class="flex min-w-0 items-center justify-between gap-3">+ <div class="min-w-0">+ <div class="truncate text-ink">{agent.bot.name}</div>+ <div class="truncate text-xxs text-ink-extra-muted">+ @{agent.bot.handle} · {harnessLabel(agent)} ·{' '}+ {agent.defaultModel}+ </div>+ </div>+ <span class="max-w-44 shrink-0 truncate text-ink-extra-muted">+ {agent.isCoding ? 'Coding' : 'Chat'} · {channelsLabel(agent)}+ </span>+ </div>+ </Tool.ListItem>+ )}+ </For>+ </div>+ </Tool.List>+ );+}++const listAgentsHandler = createToolRenderer({+ name: 'ListAgents',+ render: (ctx) => {+ const [expanded, setExpanded] = createSignal(false);+ const agents = () => ctx.response?.data.agents ?? [];+ const status = () => {+ if (!ctx.response) return undefined;+ return `${agents().length} agent${agents().length === 1 ? '' : 's'}`;+ };++ return (+ <BaseTool+ icon={HeadCircuit}+ renderContext={ctx.renderContext}+ type="call"+ response={+ expanded() && agents().length > 0 ? (+ <AgentList agents={agents()} />+ ) : undefined+ }+ >+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">+ <span>List manageable agents</span>+ <Tool.ResultToggle+ expanded={expanded()}+ onToggle={() => setExpanded((value) => !value)}+ showToggle={agents().length > 0}+ status={status()}+ />+ </div>+ </BaseTool>+ );+ },+});++const configureAgentHandler = createToolRenderer({+ name: 'ConfigureAgent',+ render: (ctx) => {+ const [expanded, setExpanded] = createSignal(false);+ const response = () => ctx.response?.data;++ return (+ <BaseTool+ icon={UserGear}+ renderContext={ctx.renderContext}+ type="call"+ response={+ expanded() && response() ? (+ <AgentPanel+ agent={response()!.agent}+ summary={response()!.summary}+ />+ ) : undefined+ }+ >+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">+ <span>{ctx.response ? 'Configured agent' : 'Configure agent'}</span>+ <Tool.ResultToggle+ expanded={expanded()}+ onToggle={() => setExpanded((value) => !value)}+ showToggle={!!response()}+ status={+ ctx.response+ ? `@${ctx.response.data.agent.bot.handle}`+ : undefined+ }+ />+ </div>+ </BaseTool>+ );+ },+});++export { configureAgentHandler, listAgentsHandler };diff --git a/apps/web/src/lib/core/component/AI/component/tool/Bots.tsx b/apps/web/src/lib/core/component/AI/component/tool/Bots.tsxindex 85ea5f17fb..a2761319d9 100644--- a/apps/web/src/lib/core/component/AI/component/tool/Bots.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/Bots.tsx@@ -16,13 +16,13 @@ import { BaseTool } from './BaseTool';import { Tool } from './Tool';import { createToolRenderer } from './ToolRenderer';-type Detail = {+export type Detail = {label: string;value?: string | null;secret?: boolean;};-function DetailPanel(props: { details: Detail[]; summary?: string }) {+export function DetailPanel(props: { details: Detail[]; summary?: string }) {const details = () => props.details.filter((detail) => detail.value != null);return (@@ -49,13 +49,13 @@ function DetailPanel(props: { details: Detail[]; summary?: string }) {);}-function ownerLabel(owner: BotOwnerSummary): string {+export function ownerLabel(owner: BotOwnerSummary): string {return owner.type === 'team'? `Team · ${owner.team_id}`: `User · ${owner.user_id}`;}-function botDetails(bot: BotSummary): Detail[] {+export function botDetails(bot: BotSummary): Detail[] {return [{ label: 'Bot ID', value: bot.botId, secret: true },{ label: 'Handle', value: `@${bot.handle}` },diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsxindex 7a99b85933..31de997917 100644--- a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx@@ -9,6 +9,7 @@ import {} from '@service-cognition/generated/tools/tool';import { createMemo } from 'solid-js';import { Dynamic } from 'solid-js/web';+import { configureAgentHandler, listAgentsHandler } from './Agents';import { bashCodeExecutionHandler } from './BashCodeExecution';import {configureBotHandler,@@ -120,6 +121,8 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {ReadSpreadsheet: readSpreadsheetHandler,CalculateSpreadsheet: calculateSpreadsheetHandler,EditSpreadsheet: editSpreadsheetHandler,+ ConfigureAgent: configureAgentHandler,+ ListAgents: listAgentsHandler,ConfigureBot: configureBotHandler,CreateChannel: createChannelHandler,CreateBot: createBotHandler,diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex e3b68ca97c..f5451c87d2 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts@@ -655,6 +655,177 @@ export const CommentOnDocumentResponse = z.object({markedText: z.union([z.string(), z.null()]).optional(),});+export const ConfigureAgent = z.object({+ botId: z.string().uuid(),+ instructions: z.union([z.string(), z.null()]).optional(),+ harness: z+ .union([+ z.any().superRefine((x, ctx) => {+ const schemas = [+ z.literal('in-memory'),+ z.literal('cursor'),+ z.literal('claude-cloud'),+ z.literal('macrod'),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ z.null(),+ ])+ .optional(),+ harnessId: z.union([z.string().uuid(), z.null()]).optional(),+ defaultModel: z.union([z.string(), z.null()]).optional(),+ channelScope: z+ .union([+ z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('all'), z.literal('selected')];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ z.null(),+ ])+ .optional(),+ channelIds: z.union([z.array(z.string().uuid()), z.null()]).optional(),+ mcpScope: z+ .union([+ z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('owner_connections'), z.literal('selected')];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ z.null(),+ ])+ .optional(),+ mcpServers: z+ .union([+ z.array(z.object({ appSlug: z.string(), serverName: z.string() })),+ z.null(),+ ])+ .optional(),+ autoAcceptPermissions: z.union([z.boolean(), z.null()]).optional(),+ isCoding: z.union([z.boolean(), z.null()]).optional(),+});++export const ConfigureAgentResponse = z.object({+ agent: z.object({+ bot: z.object({+ botId: z.string().uuid(),+ owner: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.object({ user_id: z.string(), type: z.literal('user') }),+ z.object({ team_id: z.string().uuid(), type: z.literal('team') }),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ name: z.string(),+ handle: z.string(),+ description: z.union([z.string(), z.null()]).optional(),+ avatarUrl: z.union([z.string(), z.null()]).optional(),+ hasAgent: z.boolean(),+ }),+ instructions: z.string(),+ harness: z.string(),+ harnessId: z.union([z.string().uuid(), z.null()]).optional(),+ defaultModel: z.string(),+ channelScope: z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('all'), z.literal('selected')];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ channelIds: z.array(z.string().uuid()),+ mcpScope: z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('owner_connections'), z.literal('selected')];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ mcpServers: z.array(+ z.object({ appSlug: z.string(), serverName: z.string() })+ ),+ autoAcceptPermissions: z.union([z.boolean(), z.null()]).optional(),+ isCoding: z.boolean(),+ }),+ summary: z.string(),+});+export const ConfigureBot = z.object({botId: z.string().uuid(),name: z.union([z.string(), z.null()]).optional(),@@ -2848,6 +3019,91 @@ export const IssueBotCredentialResponse = z.object({summary: z.string(),});+export const ListAgents = z.record(z.any());++export const ListAgentsResponse = z.object({+ agents: z.array(+ z.object({+ bot: z.object({+ botId: z.string().uuid(),+ owner: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.object({ user_id: z.string(), type: z.literal('user') }),+ z.object({ team_id: z.string().uuid(), type: z.literal('team') }),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ name: z.string(),+ handle: z.string(),+ description: z.union([z.string(), z.null()]).optional(),+ avatarUrl: z.union([z.string(), z.null()]).optional(),+ hasAgent: z.boolean(),+ }),+ instructions: z.string(),+ harness: z.string(),+ harnessId: z.union([z.string().uuid(), z.null()]).optional(),+ defaultModel: z.string(),+ channelScope: z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('all'), z.literal('selected')];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ channelIds: z.array(z.string().uuid()),+ mcpScope: z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('owner_connections'), z.literal('selected')];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ mcpServers: z.array(+ z.object({ appSlug: z.string(), serverName: z.string() })+ ),+ autoAcceptPermissions: z.union([z.boolean(), z.null()]).optional(),+ isCoding: z.boolean(),+ })+ ),+ summary: z.string(),+});+export const ListBots = z.record(z.any());export const ListBotsResponse = z.object({diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.tsindex b04b46b144..46fa81a740 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts@@ -28,6 +28,10 @@ type ToolParserMap = {call: types.CommentOnDocument;response: types.CommentOnDocumentResponse;};+ ConfigureAgent: {+ call: types.ConfigureAgent;+ response: types.ConfigureAgentResponse;+ };ConfigureBot: {call: types.ConfigureBot;response: types.ConfigureBotResponse;@@ -116,6 +120,7 @@ type ToolParserMap = {call: types.IssueBotCredential;response: types.IssueBotCredentialResponse;};+ ListAgents: { call: types.ListAgents; response: types.ListAgentsResponse };ListBots: { call: types.ListBots; response: types.ListBotsResponse };ListCalendarEvents: {call: types.ListCalendarEvents;@@ -321,6 +326,10 @@ const toolParserMap = {call: schemas.CommentOnDocument,response: schemas.CommentOnDocumentResponse,},+ ConfigureAgent: {+ call: schemas.ConfigureAgent,+ response: schemas.ConfigureAgentResponse,+ },ConfigureBot: {call: schemas.ConfigureBot,response: schemas.ConfigureBotResponse,@@ -415,6 +424,10 @@ const toolParserMap = {call: schemas.IssueBotCredential,response: schemas.IssueBotCredentialResponse,},+ ListAgents: {+ call: schemas.ListAgents,+ response: schemas.ListAgentsResponse,+ },ListBots: { call: schemas.ListBots, response: schemas.ListBotsResponse },ListCalendarEvents: {call: schemas.ListCalendarEvents,@@ -655,6 +668,10 @@ type ToolDataMap = {call: types.CommentOnDocument;response: types.CommentOnDocumentResponse;};+ ConfigureAgent: {+ call: types.ConfigureAgent;+ response: types.ConfigureAgentResponse;+ };ConfigureBot: {call: types.ConfigureBot;response: types.ConfigureBotResponse;@@ -743,6 +760,7 @@ type ToolDataMap = {call: types.IssueBotCredential;response: types.IssueBotCredentialResponse;};+ ListAgents: { call: types.ListAgents; response: types.ListAgentsResponse };ListBots: { call: types.ListBots; response: types.ListBotsResponse };ListCalendarEvents: {call: types.ListCalendarEvents;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex 2db365c05b..c8d40f4a89 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -165,6 +165,22 @@ export type SpreadsheetValueKind =| 'text'| 'boolean'| 'error';+/**+ * The runtimes an agent can be moved onto.+ */+export type AgentHarnessOption =+ | 'in-memory'+ | 'cursor'+ | 'claude-cloud'+ | 'macrod';+/**+ * Where an agent can be mentioned.+ */+export type AgentChannelScopeSummary = 'all' | 'selected';+/**+ * Which connected apps an agent's sessions are handed as MCP servers.+ */+export type AgentMcpScopeSummary = 'owner_connections' | 'selected';/*** Ownership scope of a manageable bot.*/@@ -1806,44 +1822,120 @@ export interface CommentOnDocumentResponse {markedText?: string | null;}/**- * Configure a manageable bot's profile. Provide only fields that should change. Use avatarUrl to set a profile picture from an image already uploaded to Macro static files or another reachable image URL; pass an empty string to clear the current picture. Passing an empty string for description clears it. Confirm handle changes because integrations and mentions may rely on the stable handle.+ * Update the instructions or settings of an AI agent the current user can manage. Provide only the fields that should change; everything else keeps its current value. Read the agent first with ListAgents: instructions are replaced whole, so to edit them, apply the edit to the current text and pass the complete result. Changes apply to sessions opened afterwards; running sessions keep the instructions they started with. Use ConfigureBot for the display name, handle, description, or picture, and ManageBotChannelAccess for plain webhook bots.*/-export interface ConfigureBot {+export interface ConfigureAgent {/**- * Bot id from CreateBot or ListBots.+ * The agent's bot id: `bot.botId` from ListAgents.*/botId: string;/**- * New display name. Omit to keep the current name.+ * The complete new instructions in markdown. Replaces the current instructions entirely; omit to keep them.*/- name?: string | null;+ instructions?: string | null;/**- * New stable handle using lowercase ASCII letters, digits, hyphens, and underscores. Omit to keep the current handle.+ * Runtime to move the agent onto. `macrod` also needs harnessId; the other runtimes must not have one. The current model may not exist on the new runtime, so usually pass defaultModel with it. Omit to keep the current runtime.*/- handle?: string | null;+ harness?: AgentHarnessOption | null;/**- * New bot description. Omit to keep the current value; pass an empty string to clear it.+ * Id of the registered self-hosted harness, required when harness is `macrod` and forbidden otherwise.*/- description?: string | null;+ harnessId?: string | null;/**- * New profile-picture URL. Use a Macro static-file URL or another reachable image URL. Omit to keep the current picture; pass an empty string to clear it.+ * Model id the agent's new sessions should use, as the runtime names it (e.g. `claude-sonnet-4-5`). Valid ids depend on the runtime. Omit to keep the current model.*/- avatarUrl?: string | null;+ defaultModel?: string | null;/**- * Set true if mentioning this bot should open a sandboxed coding-agent session. Omit to leave unchanged.+ * `all` makes the agent mentionable in every channel its owner can use; `selected` limits it to channelIds. Omit to keep the current scope, or omit it and pass channelIds alone to switch to `selected`.*/- hasAgent?: boolean | null;+ channelScope?: AgentChannelScopeSummary | null;+ /**+ * The complete list of channel ids the agent is limited to; the user must be a member of each. Required with the `selected` scope and forbidden with `all`.+ */+ channelIds?: string[] | null;+ /**+ * `owner_connections` hands sessions whatever apps the person running them has connected; `selected` hands exactly mcpServers. Omit to keep the current scope, or omit it and pass mcpServers alone to switch to `selected`.+ */+ mcpScope?: AgentMcpScopeSummary | null;+ /**+ * The complete list of connected apps for the `selected` MCP scope, each as its Pipedream app slug (e.g. `linear`) and display name. A slug Pipedream does not list as a connectable app is rejected and nothing is saved. Forbidden with `owner_connections`.+ */+ mcpServers?: AgentMcpServerSummary[] | null;+ /**+ * `true` lets sessions approve tool permission requests without asking, where the runtime allows it; `false` makes them ask every time. Omit to leave unchanged.+ */+ autoAcceptPermissions?: boolean | null;+ /**+ * `true` for a coding agent, which works in a repository and answers a mention with a live session; `false` for a chat agent, which replies in the thread. Omit to leave unchanged.+ */+ isCoding?: boolean | null;}/**- * Response from [`ConfigureBot`].+ * One Pipedream app an agent lists under the `selected` MCP scope.*/-export interface ConfigureBotResponse {- bot: BotSummary;+export interface AgentMcpServerSummary {/**- * Human-readable result summary.+ * Pipedream app slug, e.g. `linear`.+ */+ appSlug: string;+ /**+ * Display name, e.g. `Linear`.+ */+ serverName: string;+}+/**+ * Response from [`ConfigureAgent`].+ */+export interface ConfigureAgentResponse {+ agent: AgentSummary;+ /**+ * Human-readable result summary naming what changed.*/summary: string;}+/**+ * High-signal agent details returned to AI agents: the bot profile plus the+ * instructions and settings that decide how its sessions run.+ */+export interface AgentSummary {+ bot: BotSummary;+ /**+ * Instructions the agent works under, whole. New sessions snapshot them.+ */+ instructions: string;+ /**+ * Harness slug: `in-memory`, `cursor`, `claude-cloud`, or `macrod`.+ */+ harness: string;+ /**+ * Registered harness the agent runs on when `harness` is `macrod`.+ */+ harnessId?: string | null;+ /**+ * Model id the agent's sessions open with. Valid ids depend on the harness.+ */+ defaultModel: string;+ channelScope: AgentChannelScopeSummary;+ /**+ * Selected channel ids; empty unless `channelScope` is `selected`.+ */+ channelIds: string[];+ mcpScope: AgentMcpScopeSummary;+ /**+ * Selected apps; empty unless `mcpScope` is `selected`.+ */+ mcpServers: AgentMcpServerSummary[];+ /**+ * Whether sessions approve tool permission requests without asking.+ * Absent means the agent always prompts.+ */+ autoAcceptPermissions?: boolean | null;+ /**+ * Whether the agent is a coding agent (works in a repository and answers+ * mentions with a live session) or a chat agent (replies in the thread).+ */+ isCoding: boolean;+}/*** High-signal bot details returned to AI agents.*/@@ -1874,6 +1966,45 @@ export interface BotSummary {*/hasAgent: boolean;}+/**+ * Configure a manageable bot's profile. Provide only fields that should change. Use avatarUrl to set a profile picture from an image already uploaded to Macro static files or another reachable image URL; pass an empty string to clear the current picture. Passing an empty string for description clears it. Confirm handle changes because integrations and mentions may rely on the stable handle.+ */+export interface ConfigureBot {+ /**+ * Bot id from CreateBot or ListBots.+ */+ botId: string;+ /**+ * New display name. Omit to keep the current name.+ */+ name?: string | null;+ /**+ * New stable handle using lowercase ASCII letters, digits, hyphens, and underscores. Omit to keep the current handle.+ */+ handle?: string | null;+ /**+ * New bot description. Omit to keep the current value; pass an empty string to clear it.+ */+ description?: string | null;+ /**+ * New profile-picture URL. Use a Macro static-file URL or another reachable image URL. Omit to keep the current picture; pass an empty string to clear it.+ */+ avatarUrl?: string | null;+ /**+ * Set true if mentioning this bot should open a sandboxed coding-agent session. Omit to leave unchanged.+ */+ hasAgent?: boolean | null;+}+/**+ * Response from [`ConfigureBot`].+ */+export interface ConfigureBotResponse {+ bot: BotSummary;+ /**+ * Human-readable result summary.+ */+ summary: string;+}/*** Search items by their content: document body text; email subject/body/sender/recipient/cc/bcc and the display names on those addresses; chat messages; call transcripts. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed content. Use this for targeted keyword/content lookup, not for activity-summary questions like "what happened today", "what's going on", "catch me up", or "what happened in standup today"; those should start with ListEntities using time/type/channel filters. Whitespace-separated terms are ANDed. For documents and emails, every term must match somewhere in the document — different terms can appear in different chunks/pages or different fields. For documents and emails specifically, each single-word term is matched as a prefix (so `scri` matches `script`); for emails the prefix expansion also runs against the local-part of address fields. For chats, channels, and call transcripts the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the content, not the user's natural-language description; long phrases will not match. Matching defaults to prefix; set matchType to 'exact' to match whole tokens/phrases with no prefix expansion (e.g. an exact word, identifier, or full email address). Wrap a multi-word phrase in double quotes to keep it together as one adjacent phrase. If the user's request combines a person with a topic, run separate searches rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type. Results for documents, emails, AI chats, projects, and call records include the tags visible to the user as {label, scope} pairs; to restrict a search to tagged items, pass the tag labels in the tags argument (ListTags shows which tags exist).*/@@ -4018,6 +4149,23 @@ export interface IssueBotCredentialResponse {*/summary: string;}+/**+ * List every AI agent the current user can manage - their own, their teams', and channel agents they can mention - with each agent's current instructions and settings: harness, model, channel availability, connected apps, permission behavior, and whether it is a coding or chat agent. Use this to find an agent's botId and read its current configuration before changing it with ConfigureAgent. ListBots covers plain webhook bots instead.+ */+export type ListAgents = {};+/**+ * Response from [`ListAgents`].+ */+export interface ListAgentsResponse {+ /**+ * Agents the caller can manage, with their current instructions and settings.+ */+ agents: AgentSummary[];+ /**+ * Human-readable result summary.+ */+ summary: string;+}/*** List every active bot the current user can manage, including user-owned bots and bots owned by teams they belong to. Use this to discover a botId before issuing credentials, reading webhook URLs, changing channel access, configuring, or deleting a bot.*/diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rsindex 6d9036907e..549899cf38 100644--- a/crates/ai_tools/src/build_context.rs+++ b/crates/ai_tools/src/build_context.rs@@ -479,6 +479,7 @@ pub async fn build_tool_service_context_from_env(crate::tool_context::ToolBotEventBroker::Real(macro_event_broker.clone()),entity_access_service.clone(),document_storage_service_url,+ crate::mcp_app_catalog::pipedream_client_from_env()?,),project_tool_context,initiative_tool_context,diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rsindex 0e34831f6e..7a66eeec3d 100644--- a/crates/ai_tools/src/lib.rs+++ b/crates/ai_tools/src/lib.rs@@ -10,6 +10,7 @@ mod test;pub mod ai_operations;mod build_context;mod display_results;+mod mcp_app_catalog;mod schemas;pub mod search;mod search_tools;@@ -51,6 +52,7 @@ pub use build_context::{build_anthropic_tool_context, build_image_generator_from_env,build_tool_service_context_from_env,};+pub use mcp_app_catalog::{PipedreamMcpAppCatalog, pipedream_client_from_env};pub use search::search_toolset;pub use tool_context::{ChannelSideEffectClients, NoOpCallRtcClient, NoOpConnectionService, NoOpNotificationIngress,diff --git a/crates/ai_tools/src/mcp_app_catalog.rs b/crates/ai_tools/src/mcp_app_catalog.rsnew file mode 100644index 0000000000..f0880ae45c--- /dev/null+++ b/crates/ai_tools/src/mcp_app_catalog.rs@@ -0,0 +1,123 @@+//! Pipedream app directory used when an agent pins MCP servers.++use std::sync::Arc;++use anyhow::Context;+use bots::domain::ports::{BotError, McpAppCatalog};+use macro_env::Environment;+use macro_env_var::maybe_env_var;+use pipedream_mcp::domain::ports::ConnectorDirectory;+use pipedream_mcp::outbound::api::{+ DEFAULT_API_URL, DEFAULT_MCP_URL, PipedreamClient, PipedreamConfig,+};++maybe_env_var! {+ struct PipedreamCatalogEnv {+ /// OAuth client ID for the Pipedream API.+ PipedreamClientId,+ /// OAuth client secret for the Pipedream API.+ PipedreamClientSecret,+ /// The Pipedream Connect project ID (`proj_...`).+ PipedreamProjectId,+ /// The Pipedream project environment (`development` or `production`).+ PipedreamEnvironment,+ /// Base URL of the Pipedream API.+ PipedreamApiUrl,+ }+}++/// A Pipedream client when this process has the credentials, otherwise `None`.+///+/// Incomplete credentials are treated as unconfigured: a slug cannot be+/// half-verified.+pub fn pipedream_client_from_env() -> anyhow::Result<Option<Arc<PipedreamClient>>> {+ let env = PipedreamCatalogEnv::new();+ let (Some(client_id), Some(client_secret), Some(project_id)) = (+ env.pipedream_client_id+ .as_ref()+ .and_then(|value| value.value()),+ env.pipedream_client_secret+ .as_ref()+ .and_then(|value| value.value()),+ env.pipedream_project_id+ .as_ref()+ .and_then(|value| value.value()),+ ) else {+ return Ok(None);+ };++ let environment = env+ .pipedream_environment+ .as_ref()+ .and_then(|value| value.value())+ .map(str::to_owned)+ .unwrap_or_else(|| match Environment::new_or_prod() {+ Environment::Production => "production".to_owned(),+ Environment::Develop | Environment::Local => "development".to_owned(),+ });+ let api_url = env+ .pipedream_api_url+ .as_ref()+ .and_then(|value| value.value())+ .unwrap_or(DEFAULT_API_URL)+ .to_owned();++ let client = PipedreamClient::new(PipedreamConfig {+ client_id: client_id.to_owned(),+ client_secret: client_secret.to_owned(),+ project_id: project_id.to_owned(),+ environment,+ allowed_origins: Vec::new(),+ api_url,+ mcp_url: DEFAULT_MCP_URL.to_owned(),+ })+ .context("building Pipedream client for MCP app lookup")?;+ Ok(Some(Arc::new(client)))+}++/// Confirms agent MCP slugs against Pipedream's app directory.+///+/// With no client, every slug is refused: an unverified app is not stored.+#[derive(Clone)]+pub struct PipedreamMcpAppCatalog {+ client: Option<Arc<PipedreamClient>>,+}++impl PipedreamMcpAppCatalog {+ /// Consult `client`, or refuse every slug when Pipedream is not configured.+ pub fn new(client: Option<Arc<PipedreamClient>>) -> Self {+ Self { client }+ }+}++impl std::fmt::Debug for PipedreamMcpAppCatalog {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter+ .debug_struct("PipedreamMcpAppCatalog")+ .field("configured", &self.client.is_some())+ .finish()+ }+}++impl McpAppCatalog for PipedreamMcpAppCatalog {+ async fn is_connectable_app(&self, slug: &str) -> Result<bool, BotError> {+ let Some(client) = &self.client else {+ return Err(BotError::Unavailable(format!(+ "cannot verify MCP app {slug}: Pipedream is not configured"+ )));+ };+ match client.retrieve(slug).await {+ Ok(Some(_)) => Ok(true),+ Ok(None) => Ok(false),+ Err(error) => {+ tracing::warn!(%slug, %error, "MCP app lookup failed");+ Err(BotError::Unavailable(format!(+ "could not verify MCP app {slug}"+ )))+ }+ }+ }+}++#[cfg(test)]+mod test;diff --git a/crates/ai_tools/src/mcp_app_catalog/test.rs b/crates/ai_tools/src/mcp_app_catalog/test.rsnew file mode 100644index 0000000000..82551a26f5--- /dev/null+++ b/crates/ai_tools/src/mcp_app_catalog/test.rs@@ -0,0 +1,11 @@+use super::*;++#[tokio::test]+async fn an_unconfigured_catalog_refuses_every_slug() {+ let catalog = PipedreamMcpAppCatalog::new(None);+ let error = catalog+ .is_connectable_app("linear")+ .await+ .expect_err("no directory");+ assert!(matches!(error, BotError::Unavailable(message) if message.contains("not configured")));+}diff --git a/crates/ai_tools/src/test.rs b/crates/ai_tools/src/test.rsindex faa58a5233..9937ea4608 100644--- a/crates/ai_tools/src/test.rs+++ b/crates/ai_tools/src/test.rs@@ -173,6 +173,26 @@ fn frontend_schemas_distinguish_user_tool_response_types() {);}+/// The configure-agent system skill walks an agent through `ListAgents` and+/// `ConfigureAgent`; a host that reads the skill must be able to follow it.+#[test]+fn every_host_exposes_agent_configuration() {+ for host in [+ AiHost::Chat,+ AiHost::AgentSession,+ AiHost::ChannelBot,+ AiHost::Mcp,+ ] {+ let tools = tools_for(host);+ for name in ["ListAgents", "ConfigureAgent", "ConfigureBot"] {+ assert!(+ tools.toolset.tools.contains_key(name),+ "{host:?} missing {name}"+ );+ }+ }+}+#[test]fn every_host_exposes_skill_discovery_and_reading() {for host in [diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rsindex 3c4da26fcf..9c5ed6c4f9 100644--- a/crates/ai_tools/src/tool_context.rs+++ b/crates/ai_tools/src/tool_context.rs@@ -134,7 +134,8 @@ impl MacroEventBroker for ToolBotEventBroker {}/// Concrete bot domain service used by AI tools.-pub type ToolBotService = BotServiceImpl<PgBotsRepo, ToolBotEventBroker>;+pub type ToolBotService =+ BotServiceImpl<PgBotsRepo, ToolBotEventBroker, crate::mcp_app_catalog::PipedreamMcpAppCatalog>;/// Bot-management AI tool context.pub type ToolBotToolContext = BotToolContext<ToolBotService, ToolEntityAccessService>;@@ -146,9 +147,14 @@ pub fn build_bot_tool_context(event_broker: ToolBotEventBroker,entity_access_service: Arc<ToolEntityAccessService>,document_storage_service_url: String,+ pipedream: Option<Arc<pipedream_mcp::outbound::api::PipedreamClient>>,) -> ToolBotToolContext {BotToolContext {- service: Arc::new(BotServiceImpl::new(PgBotsRepo::new(pool), event_broker)),+ service: Arc::new(+ BotServiceImpl::new(PgBotsRepo::new(pool), event_broker).with_mcp_apps(+ crate::mcp_app_catalog::PipedreamMcpAppCatalog::new(pipedream),+ ),+ ),entity_access_service,document_storage_service_url: document_storage_service_url.trim_end_matches('/')diff --git a/crates/bots/src/domain/models.rs b/crates/bots/src/domain/models.rsindex 332e6878cd..c59b3e8cc2 100644--- a/crates/bots/src/domain/models.rs+++ b/crates/bots/src/domain/models.rs@@ -442,6 +442,100 @@ pub struct UpdateAgentRequest {pub is_coding: bool,}+#[cfg(test)]+mod test;++/// The runtime an agent runs on: a harness slug and, for `macrod`, the+/// registered harness serving it. Travel together because one without the+/// other is never a valid choice.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct AgentHarnessSelection {+ /// Harness slug, e.g. `in-memory`, `cursor`, `claude-cloud`, or `macrod`.+ pub harness: String,+ /// Registered harness to run on. Required when `harness` is `macrod`,+ /// forbidden otherwise.+ pub harness_id: Option<HarnessId>,+}++/// Where an agent can be mentioned: everywhere its owner can use it, or+/// exactly the listed channels.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct AgentChannelSelection {+ /// Whether the agent is global or channel-specific.+ pub channel_scope: AgentChannelScope,+ /// Selected channels. Must be non-empty only for `selected` scope.+ pub channel_ids: Vec<Uuid>,+}++/// Request to change part of a persisted agent's instructions or settings.+///+/// Every field is optional; an absent field keeps the agent's current value.+/// Ownership and the bot profile (name, handle, description, avatar) are not+/// patchable here: the profile has [`PatchBotRequest`], and ownership changes+/// go through [`UpdateAgentRequest`].+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct PatchAgentRequest {+ /// Replacement instructions, whole.+ pub instructions: Option<String>,+ /// Replacement runtime.+ pub harness: Option<AgentHarnessSelection>,+ /// Replacement model.+ pub default_model: Option<String>,+ /// Replacement channel availability.+ pub channels: Option<AgentChannelSelection>,+ /// Replacement MCP server selection.+ pub mcp: Option<AgentMcpServers>,+ /// Replacement permission choice: approve without asking (`true`) or+ /// prompt (`false`). A patch cannot clear the choice back to unset; an+ /// explicit `false` prompts exactly as unset does.+ pub auto_accept_permissions: Option<bool>,+ /// Replacement coding choice.+ pub is_coding: Option<bool>,+}++impl PatchAgentRequest {+ /// The full replacement `current` becomes once this patch is applied.+ ///+ /// Keeps the agent under its current owner and profile; only what the+ /// patch names changes.+ #[must_use]+ pub fn apply_to(self, current: &Agent) -> UpdateAgentRequest {+ let (harness, harness_id) = match self.harness {+ Some(selection) => (selection.harness, selection.harness_id),+ None => (current.harness.clone(), current.harness_id),+ };+ let (channel_scope, channel_ids) = match self.channels {+ Some(selection) => (selection.channel_scope, selection.channel_ids),+ None => (current.channel_scope, current.channel_ids.clone()),+ };+ UpdateAgentRequest {+ team_id: match ¤t.bot.owner {+ Some(BotOwner::Team { team_id }) => Some(*team_id),+ Some(BotOwner::User { .. }) | None => None,+ },+ harness_id,+ name: current.bot.name.clone(),+ handle: current.bot.handle.clone(),+ description: current.bot.description.clone(),+ avatar_url: current.bot.avatar_url.clone(),+ instructions: self+ .instructions+ .unwrap_or_else(|| current.instructions.clone()),+ harness,+ default_model: self+ .default_model+ .unwrap_or_else(|| current.default_model.clone()),+ channel_scope,+ channel_ids,+ mcp: self.mcp.unwrap_or_else(|| current.mcp.clone()),+ auto_accept_permissions: self+ .auto_accept_permissions+ .or(current.auto_accept_permissions),+ is_coding: self.is_coding.unwrap_or(current.is_coding),+ }+ }+}+/// Channel containing a bot.#[derive(Debug, Clone, Serialize, Deserialize)]#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]diff --git a/crates/bots/src/domain/models/test.rs b/crates/bots/src/domain/models/test.rsnew file mode 100644index 0000000000..e3c97e0ec8--- /dev/null+++ b/crates/bots/src/domain/models/test.rs@@ -0,0 +1,114 @@+use super::*;++fn agent(owner: BotOwner) -> Agent {+ let now = Utc::now();+ Agent {+ bot: Bot {+ id: BotId::new_from_uuid(Uuid::new_v4()),+ kind: BotKind::Owned,+ owner: Some(owner),+ name: "Bug fixer".to_string(),+ handle: "bug-fixer".to_string(),+ description: Some("Finds and fixes bugs".to_string()),+ avatar_url: Some("https://static.example/bug-fixer.png".to_string()),+ created_by: Some("macro|[email protected]".to_string()),+ created_at: now,+ updated_at: now,+ deleted_at: None,+ has_agent: true,+ },+ instructions: "Fix the root cause and add tests.".to_string(),+ harness: "macrod".to_string(),+ harness_id: Some(HarnessId::new_from_uuid(Uuid::new_v4())),+ default_model: "claude-sonnet-4-5".to_string(),+ channel_scope: AgentChannelScope::Selected,+ channel_ids: vec![Uuid::new_v4()],+ mcp: AgentMcpServers::Selected {+ servers: vec![AgentMcpServer {+ app_slug: "linear".to_string(),+ server_name: "Linear".to_string(),+ }],+ },+ auto_accept_permissions: Some(true),+ is_coding: true,+ }+}++#[test]+fn empty_patch_reproduces_the_agent_under_its_current_owner() {+ let team_id = Uuid::new_v4();+ let current = agent(BotOwner::Team { team_id });++ let update = PatchAgentRequest::default().apply_to(¤t);++ assert_eq!(update.team_id, Some(team_id));+ assert_eq!(update.harness_id, current.harness_id);+ assert_eq!(update.name, current.bot.name);+ assert_eq!(update.handle, current.bot.handle);+ assert_eq!(update.description, current.bot.description);+ assert_eq!(update.avatar_url, current.bot.avatar_url);+ assert_eq!(update.instructions, current.instructions);+ assert_eq!(update.harness, current.harness);+ assert_eq!(update.default_model, current.default_model);+ assert_eq!(update.channel_scope, current.channel_scope);+ assert_eq!(update.channel_ids, current.channel_ids);+ assert_eq!(update.mcp, current.mcp);+ assert_eq!(+ update.auto_accept_permissions,+ current.auto_accept_permissions+ );+ assert_eq!(update.is_coding, current.is_coding);+}++#[test]+fn user_owned_agent_stays_private() {+ let current = agent(BotOwner::User {+ user_id: "macro|[email protected]".to_string(),+ });++ let update = PatchAgentRequest {+ instructions: Some("Diagnose first.".to_string()),+ ..PatchAgentRequest::default()+ }+ .apply_to(¤t);++ assert_eq!(update.team_id, None);+ assert_eq!(update.instructions, "Diagnose first.");+ assert_eq!(update.harness, "macrod");+}++#[test]+fn named_fields_replace_and_travel_with_their_partners() {+ let current = agent(BotOwner::Team {+ team_id: Uuid::new_v4(),+ });++ let update = PatchAgentRequest {+ harness: Some(AgentHarnessSelection {+ harness: "in-memory".to_string(),+ harness_id: None,+ }),+ default_model: Some("claude-opus-4-5".to_string()),+ channels: Some(AgentChannelSelection {+ channel_scope: AgentChannelScope::All,+ channel_ids: Vec::new(),+ }),+ mcp: Some(AgentMcpServers::OwnerConnections),+ auto_accept_permissions: Some(false),+ is_coding: Some(false),+ ..PatchAgentRequest::default()+ }+ .apply_to(¤t);++ // Moving off macrod drops the registered harness with it, so the+ // request can never name a harness id for a runtime that takes none.+ assert_eq!(update.harness, "in-memory");+ assert_eq!(update.harness_id, None);+ assert_eq!(update.default_model, "claude-opus-4-5");+ assert_eq!(update.channel_scope, AgentChannelScope::All);+ assert!(update.channel_ids.is_empty());+ assert_eq!(update.mcp, AgentMcpServers::OwnerConnections);+ assert_eq!(update.auto_accept_permissions, Some(false));+ assert!(!update.is_coding);+ assert_eq!(update.instructions, current.instructions);+}diff --git a/crates/bots/src/domain/ports.rs b/crates/bots/src/domain/ports.rsindex aaaf484288..1458854474 100644--- a/crates/bots/src/domain/ports.rs+++ b/crates/bots/src/domain/ports.rs@@ -4,7 +4,8 @@ use super::models::{Agent, AuthenticatedBot, Bot, BotChannel, BotChannelListCaller, BotId, BotOwner,BotOwnerProfile, BotProfile, BotToken, BotTokenCandidate, CreateAgentRequest, CreateBotRequest,CreateBotTokenRequest, CreateBotTokenResponse, CreateChannelScopedBotRequest,- CreateChannelScopedBotResponse, HarnessFacts, HarnessId, PatchBotRequest, UpdateAgentRequest,+ CreateChannelScopedBotResponse, HarnessFacts, HarnessId, PatchAgentRequest, PatchBotRequest,+ UpdateAgentRequest,};use bot_token::HashedBotToken;use entity_access::domain::models::{EntityAccessReceipt, MemberParticipantRole};@@ -233,6 +234,15 @@ pub trait BotService: Send + Sync + 'static {req: UpdateAgentRequest,) -> impl Future<Output = Result<Agent, BotError>> + Send;+ /// Change part of a manageable agent's instructions or settings, keeping+ /// everything the patch leaves unnamed - owner and profile included.+ fn patch_agent(+ &self,+ caller: MacroUserIdStr<'static>,+ bot_id: BotId,+ req: PatchAgentRequest,+ ) -> impl Future<Output = Result<Agent, BotError>> + Send;+/// List agents the caller can manage or start a managed session as.fn list_agents(&self,@@ -374,6 +384,16 @@ pub trait BotService: Send + Sync + 'static {) -> impl Future<Output = Result<AuthenticatedBot, BotError>> + Send;}+/// Whether a Pipedream app slug is one an agent may pin.+///+/// The directory is Pipedream's. `Ok(false)` is a definite miss. `Err` means+/// the directory could not be asked, and the slug must not be stored.+pub trait McpAppCatalog: Send + Sync + 'static {+ /// `true` when `slug` is a connectable Pipedream app.+ fn is_connectable_app(&self, slug: &str)+ -> impl Future<Output = Result<bool, BotError>> + Send;+}+/// Bot service error.#[derive(Debug, thiserror::Error)]pub enum BotError {@@ -386,6 +406,9 @@ pub enum BotError {/// Unauthorized.#[error("unauthorized")]Unauthorized,+ /// The MCP app directory could not answer, so a slug was not stored.+ #[error("{0}")]+ Unavailable(String),/// Repository error.#[error(transparent)]Repo(#[from] anyhow::Error),diff --git a/crates/bots/src/domain/service.rs b/crates/bots/src/domain/service.rsindex eda849cd14..aa38723158 100644--- a/crates/bots/src/domain/service.rs+++ b/crates/bots/src/domain/service.rs@@ -3,13 +3,13 @@use super::{events::{BotCreatedMetadata, BotDeletedMetadata, BotMacroEvent, BotUpdatedMetadata},models::{- Agent, AgentChannelScope, AgentMcpServers, AuthenticatedBot, Bot, BotChannel,- BotChannelListCaller, BotId, BotKind, BotOwner, BotOwnerProfile, BotToken,+ Agent, AgentChannelScope, AgentMcpServer, AgentMcpServers, AuthenticatedBot, Bot,+ BotChannel, BotChannelListCaller, BotId, BotKind, BotOwner, BotOwnerProfile, BotToken,BotTokenCandidate, CreateAgentRequest, CreateBotRequest, CreateBotTokenRequest,CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, HarnessId, HarnessOwner,- MAX_BOT_OWNER_PROFILE_IDS, PatchBotRequest, UpdateAgentRequest,+ MAX_BOT_OWNER_PROFILE_IDS, PatchAgentRequest, PatchBotRequest, UpdateAgentRequest,},- ports::{BotError, BotRepo, BotService},+ ports::{BotError, BotRepo, BotService, McpAppCatalog},tokens,};use bot_token::HashedBotToken;@@ -23,16 +23,50 @@ use macro_user_id::user_id::MacroUserIdStr;use uuid::Uuid;/// Bot service implementation.+///+/// `C` answers whether a Pipedream app slug is real. [`UncheckedMcpApps`]+/// accepts every slug; hosts that configure agents from a conversation pass+/// a directory-backed catalog instead.#[derive(Debug, Clone)]-pub struct BotServiceImpl<R, B> {+pub struct BotServiceImpl<R, B, C = UncheckedMcpApps> {repo: R,event_broker: B,+ mcp_apps: C,}-impl<R, B> BotServiceImpl<R, B> {- /// Create a bot service.+/// Accepts every MCP app slug without asking Pipedream.+///+/// For hosts that have no app directory. A host that applies an agent's+/// choice of apps must pass a directory-backed catalog, which refuses a slug+/// it cannot confirm.+#[derive(Debug, Clone, Copy, Default)]+pub struct UncheckedMcpApps;++impl McpAppCatalog for UncheckedMcpApps {+ async fn is_connectable_app(&self, _slug: &str) -> Result<bool, BotError> {+ Ok(true)+ }+}++impl<R, B, C> BotServiceImpl<R, B, C> {+ /// Swap the MCP app directory this service consults.+ pub fn with_mcp_apps<D>(self, mcp_apps: D) -> BotServiceImpl<R, B, D> {+ BotServiceImpl {+ repo: self.repo,+ event_broker: self.event_broker,+ mcp_apps,+ }+ }+}++impl<R, B> BotServiceImpl<R, B, UncheckedMcpApps> {+ /// Create a bot service that does not check MCP app slugs against Pipedream.pub fn new(repo: R, event_broker: B) -> Self {- Self { repo, event_broker }+ Self {+ repo,+ event_broker,+ mcp_apps: UncheckedMcpApps,+ }}}@@ -218,7 +252,7 @@ struct ValidatedBotToken {token_id: Uuid,}-impl<R, B> BotServiceImpl<R, B>+impl<R, B, C> BotServiceImpl<R, B, C>whereR: BotRepo,B: MacroEventBroker,@@ -395,6 +429,64 @@ where}}+ /// Replace a manageable agent's configuration with `req`, `current` being+ /// the bot [`Self::ensure_manageable`] returned for it.+ async fn replace_agent(+ &self,+ caller: MacroUserIdStr<'static>,+ current: &Bot,+ req: UpdateAgentRequest,+ ) -> Result<Agent, BotError> {+ validate_update_agent_request(&req)?;+ if req.channel_scope == AgentChannelScope::Selected+ && !self+ .repo+ .user_has_channels(caller.clone(), &req.channel_ids)+ .await+ .map_err(|err| BotError::Repo(err.into()))?+ {+ return Err(BotError::Unauthorized);+ }++ let owner = self+ .owner_for_agent_update(caller.clone(), current, req.team_id)+ .await?;+ self.ensure_harness_usable(+ caller.clone(),+ &owner,+ req.harness_id,+ req.auto_accept_permissions,+ )+ .await?;+ let requested_name = req.name.clone();+ let requested_handle = req.handle.clone();+ let requested_description = req.description.clone();+ let requested_avatar_url = req.avatar_url.clone();+ let agent = self+ .repo+ .update_agent(current.id, owner, req)+ .await+ .map_err(|err| BotError::Repo(err.into()))?+ .ok_or_else(|| BotError::NotFound("agent not found".to_string()))?;++ self.publish_bot_event(&BotMacroEvent::updated(BotUpdatedMetadata {+ bot_id: agent.bot.id,+ owner: agent+ .bot+ .owner+ .clone()+ .expect("owned agent bot must have an owner"),+ actor_user_id: caller,+ name: Some(requested_name),+ handle: Some(requested_handle),+ description: requested_description,+ avatar_url: requested_avatar_url,+ updated_at: agent.bot.updated_at,+ }));++ Ok(agent)+ }+async fn authenticate_candidate(&self,candidate: Option<BotTokenCandidate>,@@ -420,10 +512,11 @@ where}}-impl<R, B> BotService for BotServiceImpl<R, B>+impl<R, B, C> BotService for BotServiceImpl<R, B, C>whereR: BotRepo,B: MacroEventBroker + Clone,+ C: McpAppCatalog,{async fn create_agent(&self,@@ -431,6 +524,7 @@ wherereq: CreateAgentRequest,) -> Result<Agent, BotError> {validate_agent_request(&req)?;+ reject_unknown_mcp_apps(&self.mcp_apps, &req.mcp, &[]).await?;if req.channel_scope == AgentChannelScope::Selected&& !self.repo@@ -485,55 +579,34 @@ wherereq: UpdateAgentRequest,) -> Result<Agent, BotError> {let current = self.ensure_manageable(caller.clone(), bot_id).await?;-+ let existing = self+ .repo+ .get_agent(bot_id)+ .await+ .map_err(|err| BotError::Repo(err.into()))?+ .ok_or_else(|| BotError::NotFound("agent not found".to_string()))?;validate_update_agent_request(&req)?;- if req.channel_scope == AgentChannelScope::Selected- && !self- .repo- .user_has_channels(caller.clone(), &req.channel_ids)- .await- .map_err(|err| BotError::Repo(err.into()))?- {- return Err(BotError::Unauthorized);- }+ reject_unknown_mcp_apps(&self.mcp_apps, &req.mcp, existing.mcp.servers()).await?;+ self.replace_agent(caller, ¤t, req).await+ }- let owner = self- .owner_for_agent_update(caller.clone(), ¤t, req.team_id)- .await?;- self.ensure_harness_usable(- caller.clone(),- &owner,- req.harness_id,- req.auto_accept_permissions,- )- .await?;- let requested_name = req.name.clone();- let requested_handle = req.handle.clone();- let requested_description = req.description.clone();- let requested_avatar_url = req.avatar_url.clone();+ async fn patch_agent(+ &self,+ caller: MacroUserIdStr<'static>,+ bot_id: BotId,+ req: PatchAgentRequest,+ ) -> Result<Agent, BotError> {+ let current = self.ensure_manageable(caller.clone(), bot_id).await?;let agent = self.repo- .update_agent(bot_id, owner, req)+ .get_agent(bot_id).await.map_err(|err| BotError::Repo(err.into()))?.ok_or_else(|| BotError::NotFound("agent not found".to_string()))?;-- self.publish_bot_event(&BotMacroEvent::updated(BotUpdatedMetadata {- bot_id: agent.bot.id,- owner: agent- .bot- .owner- .clone()- .expect("owned agent bot must have an owner"),- actor_user_id: caller,- name: Some(requested_name),- handle: Some(requested_handle),- description: requested_description,- avatar_url: requested_avatar_url,- updated_at: agent.bot.updated_at,- }));-- Ok(agent)+ let update = req.apply_to(&agent);+ validate_update_agent_request(&update)?;+ reject_unknown_mcp_apps(&self.mcp_apps, &update.mcp, agent.mcp.servers()).await?;+ self.replace_agent(caller, ¤t, update).await}async fn list_agents(&self, caller: MacroUserIdStr<'static>) -> Result<Vec<Agent>, BotError> {@@ -910,6 +983,31 @@ where}}+/// Refuse a selected MCP app Pipedream does not list.+///+/// Slugs already stored on the agent are left alone, so editing instructions+/// does not depend on the directory staying reachable. A newly named slug+/// that the directory rejects is a bad request; a directory that cannot be+/// asked fails the write rather than storing the slug unverified.+async fn reject_unknown_mcp_apps<C: McpAppCatalog>(+ catalog: &C,+ mcp: &AgentMcpServers,+ already: &[AgentMcpServer],+) -> Result<(), BotError> {+ for server in mcp.servers() {+ if already.iter().any(|kept| kept.app_slug == server.app_slug) {+ continue;+ }+ if !catalog.is_connectable_app(&server.app_slug).await? {+ return Err(BotError::BadRequest(format!(+ "MCP server slug {:?} is not a Pipedream app",+ server.app_slug+ )));+ }+ }+ Ok(())+}+/// A persona cannot override its harness operator's permission policy.fn validate_permission_bypass(allowed: bool, requested: Option<bool>) -> Result<(), BotError> {if requested == Some(true) && !allowed {diff --git a/crates/bots/src/domain/service/test.rs b/crates/bots/src/domain/service/test.rsindex 5b746e9a39..d518385963 100644--- a/crates/bots/src/domain/service/test.rs+++ b/crates/bots/src/domain/service/test.rs@@ -1,4 +1,64 @@use super::*;+use crate::domain::models::{AgentMcpServer, AgentMcpServers};+use crate::domain::ports::{BotError, McpAppCatalog};++struct KnownApps(&'static [&'static str]);++impl McpAppCatalog for KnownApps {+ async fn is_connectable_app(&self, slug: &str) -> Result<bool, BotError> {+ Ok(self.0.contains(&slug))+ }+}++struct DirectoryDown;++impl McpAppCatalog for DirectoryDown {+ async fn is_connectable_app(&self, slug: &str) -> Result<bool, BotError> {+ Err(BotError::Unavailable(format!(+ "could not verify MCP app {slug}"+ )))+ }+}++fn selected(slug: &str) -> AgentMcpServers {+ AgentMcpServers::Selected {+ servers: vec![AgentMcpServer {+ app_slug: slug.to_owned(),+ server_name: slug.to_owned(),+ }],+ }+}++#[tokio::test]+async fn an_invented_mcp_slug_is_rejected() {+ let error = reject_unknown_mcp_apps(&KnownApps(&["linear"]), &selected("not-a-real-app"), &[])+ .await+ .expect_err("invented slug");+ assert!(matches!(error, BotError::BadRequest(message) if message.contains("not-a-real-app")));+}++#[tokio::test]+async fn a_listed_mcp_slug_is_accepted() {+ reject_unknown_mcp_apps(&KnownApps(&["linear"]), &selected("linear"), &[])+ .await+ .expect("linear is listed");+}++#[tokio::test]+async fn a_slug_already_on_the_agent_is_not_looked_up_again() {+ let already = selected("made-up").servers().to_vec();+ reject_unknown_mcp_apps(&DirectoryDown, &selected("made-up"), &already)+ .await+ .expect("unchanged slug skips the directory");+}++#[tokio::test]+async fn a_directory_that_cannot_answer_refuses_the_write() {+ let error = reject_unknown_mcp_apps(&DirectoryDown, &selected("linear"), &[])+ .await+ .expect_err("directory down");+ assert!(matches!(error, BotError::Unavailable(_)));+}#[test]fn persona_cannot_bypass_a_harness_that_requires_prompts() {diff --git a/crates/bots/src/inbound/axum_router.rs b/crates/bots/src/inbound/axum_router.rsindex 9a41c3eced..bd393de377 100644--- a/crates/bots/src/inbound/axum_router.rs+++ b/crates/bots/src/inbound/axum_router.rs@@ -650,9 +650,13 @@ impl IntoResponse for BotsHandlerErr {Self::BadRequest(_) | Self::Bot(BotError::BadRequest(_)) => StatusCode::BAD_REQUEST,Self::Bot(BotError::NotFound(_)) => StatusCode::NOT_FOUND,Self::Bot(BotError::Unauthorized) => StatusCode::UNAUTHORIZED,+ Self::Bot(BotError::Unavailable(_)) => StatusCode::SERVICE_UNAVAILABLE,Self::Bot(BotError::Repo(_)) => StatusCode::INTERNAL_SERVER_ERROR,};- if status == StatusCode::INTERNAL_SERVER_ERROR {+ if matches!(+ status,+ StatusCode::INTERNAL_SERVER_ERROR | StatusCode::SERVICE_UNAVAILABLE+ ) {tracing::error!(error=?self, "bots handler error");}(diff --git a/crates/bots/src/inbound/axum_router/tests.rs b/crates/bots/src/inbound/axum_router/tests.rsindex 806592e443..0d850c9f3b 100644--- a/crates/bots/src/inbound/axum_router/tests.rs+++ b/crates/bots/src/inbound/axum_router/tests.rs@@ -2,7 +2,7 @@ use super::*;use crate::domain::models::{Agent, AuthenticatedBot, BotChannel, BotChannelListCaller, BotChannelType, BotKind, BotOwner,BotOwnerProfile, CreateAgentRequest, CreateChannelScopedBotRequest,- CreateChannelScopedBotResponse,+ CreateChannelScopedBotResponse, PatchAgentRequest,};use crate::{domain::service::BotServiceImpl, outbound::pg_bots_repo::PgBotsRepo};use axum::{@@ -126,6 +126,15 @@ impl BotService for TestBotService {unimplemented!()}+ async fn patch_agent(+ &self,+ _caller: MacroUserIdStr<'static>,+ _bot_id: BotId,+ _req: PatchAgentRequest,+ ) -> Result<Agent, BotError> {+ unimplemented!()+ }+async fn list_agents(&self, _caller: MacroUserIdStr<'static>) -> Result<Vec<Agent>, BotError> {unimplemented!()}diff --git a/crates/bots/src/inbound/channel_webhook_router.rs b/crates/bots/src/inbound/channel_webhook_router.rsindex 54f28e76ee..625a484440 100644--- a/crates/bots/src/inbound/channel_webhook_router.rs+++ b/crates/bots/src/inbound/channel_webhook_router.rs@@ -399,12 +399,16 @@ impl IntoResponse for ChannelBotWebhookHandlerErr {Self::Bot(BotError::NotFound(_)) | Self::Message(MessageError::NotFound) => {StatusCode::NOT_FOUND}+ Self::Bot(BotError::Unavailable(_)) => StatusCode::SERVICE_UNAVAILABLE,Self::Bot(BotError::Repo(_)) | Self::Message(MessageError::Repository(_)) => {StatusCode::INTERNAL_SERVER_ERROR}};- if status == StatusCode::INTERNAL_SERVER_ERROR {+ if matches!(+ status,+ StatusCode::INTERNAL_SERVER_ERROR | StatusCode::SERVICE_UNAVAILABLE+ ) {tracing::error!(error=?self, "channel bot webhook handler error");}diff --git a/crates/bots/src/inbound/channel_webhook_router/tests.rs b/crates/bots/src/inbound/channel_webhook_router/tests.rsindex c0a56869af..daab1af27e 100644--- a/crates/bots/src/inbound/channel_webhook_router/tests.rs+++ b/crates/bots/src/inbound/channel_webhook_router/tests.rs@@ -2,7 +2,7 @@ use super::*;use crate::domain::models::{Agent, AuthenticatedBot, Bot, BotChannel, BotChannelListCaller, BotKind, BotOwner,BotOwnerProfile, BotToken, CreateAgentRequest, CreateBotRequest, CreateBotTokenRequest,- CreateBotTokenResponse, PatchBotRequest, UpdateAgentRequest,+ CreateBotTokenResponse, PatchAgentRequest, PatchBotRequest, UpdateAgentRequest,};use axum::{Router,@@ -173,6 +173,15 @@ impl BotService for TestBotService {unimplemented!()}+ async fn patch_agent(+ &self,+ _caller: MacroUserIdStr<'static>,+ _bot_id: BotId,+ _req: PatchAgentRequest,+ ) -> Result<Agent, BotError> {+ unimplemented!()+ }+async fn list_agents(&self, _caller: MacroUserIdStr<'static>) -> Result<Vec<Agent>, BotError> {unimplemented!()}diff --git a/crates/bots/src/inbound/toolset.rs b/crates/bots/src/inbound/toolset.rsindex fa71745bcc..433bcff8e6 100644--- a/crates/bots/src/inbound/toolset.rs+++ b/crates/bots/src/inbound/toolset.rs@@ -1,10 +1,12 @@//! AI tools for bot management.+mod configure_agent;mod configure_bot;mod create_bot;mod delete_bot;mod get_bot_webhooks;mod issue_bot_credential;+mod list_agents;mod list_bots;mod manage_bot_channel_access;mod types;@@ -14,6 +16,7 @@ mod test;use crate::domain::ports::{BotError, BotService};use ai_toolset::{AsyncToolCollection, RequestContext, ToolCallError};+use configure_agent::ConfigureAgent;use configure_bot::ConfigureBot;use create_bot::CreateBot;use delete_bot::DeleteBot;@@ -23,12 +26,16 @@ use entity_access::domain::{};use get_bot_webhooks::GetBotWebhooks;use issue_bot_credential::IssueBotCredential;+use list_agents::ListAgents;use list_bots::ListBots;use manage_bot_channel_access::ManageBotChannelAccess;use std::sync::Arc;use uuid::Uuid;+pub use configure_agent::{AgentHarnessOption, ConfigureAgentResponse};+pub use list_agents::ListAgentsResponse;pub use types::{+ AgentChannelScopeSummary, AgentMcpScopeSummary, AgentMcpServerSummary, AgentSummary,BOT_WEBHOOK_SCOPE, BOT_WEBHOOK_SCOPE_HEADER, BOT_WEBHOOK_TOKEN_HEADER, BotOwnerSummary,BotSummary, BotWebhook, CreatedBotChannelSetup,};@@ -119,7 +126,9 @@ fn channel_access_error(error: AccessError) -> ToolCallError {fn bot_tool_error(action: &'static str, error: BotError) -> ToolCallError {let description = match &error {- BotError::BadRequest(message) | BotError::NotFound(message) => message.clone(),+ BotError::BadRequest(message)+ | BotError::NotFound(message)+ | BotError::Unavailable(message) => message.clone(),BotError::Unauthorized => {"you do not have permission to manage this bot or its owning team".to_string()}@@ -146,4 +155,6 @@ where.add_tool::<ManageBotChannelAccess, BotToolContext<Svc, AccessSvc>>().add_tool::<ConfigureBot, BotToolContext<Svc, AccessSvc>>().add_tool::<DeleteBot, BotToolContext<Svc, AccessSvc>>()+ .add_tool::<ListAgents, BotToolContext<Svc, AccessSvc>>()+ .add_tool::<ConfigureAgent, BotToolContext<Svc, AccessSvc>>()}diff --git a/crates/bots/src/inbound/toolset/configure_agent.rs b/crates/bots/src/inbound/toolset/configure_agent.rsnew file mode 100644index 0000000000..19f627a060--- /dev/null+++ b/crates/bots/src/inbound/toolset/configure_agent.rs@@ -0,0 +1,286 @@+//! ConfigureAgent tool.++use super::{+ AgentChannelScopeSummary, AgentMcpScopeSummary, AgentMcpServerSummary, AgentSummary,+ BotToolContext, bot_tool_error,+};+use crate::domain::{+ models::{+ AgentChannelSelection, AgentHarnessSelection, AgentMcpServer, AgentMcpServers, BotId,+ HarnessId, PatchAgentRequest,+ },+ ports::BotService,+};+use ai_toolset::{+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,+ ToolResult,+};+use async_trait::async_trait;+use entity_access::domain::ports::EntityAccessService;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++/// The runtimes an agent can be moved onto.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]+pub enum AgentHarnessOption {+ /// Macro's built-in chat agent; needs no connected account.+ #[serde(rename = "in-memory")]+ InMemory,+ /// A Cursor cloud agent on the session owner's Cursor account.+ #[serde(rename = "cursor")]+ Cursor,+ /// Claude Code on the session owner's Claude account.+ #[serde(rename = "claude-cloud")]+ ClaudeCloud,+ /// A registered self-hosted harness; requires `harnessId`.+ #[serde(rename = "macrod")]+ Macrod,+}++impl AgentHarnessOption {+ /// The slug the agent row stores.+ fn slug(self) -> &'static str {+ match self {+ Self::InMemory => "in-memory",+ Self::Cursor => "cursor",+ Self::ClaudeCloud => "claude-cloud",+ Self::Macrod => harness_id::MACROD_HARNESS_SLUG,+ }+ }+}++/// Response from [`ConfigureAgent`].+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ConfigureAgentResponse {+ /// The agent as configured now.+ pub agent: AgentSummary,+ /// Human-readable result summary naming what changed.+ pub summary: String,+}++/// Change an agent's instructions or settings.+#[derive(Debug, Clone, Default, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "ConfigureAgent",+ description = "Update the instructions or settings of an AI agent the current user can manage. Provide only the fields that should change; everything else keeps its current value. Read the agent first with ListAgents: instructions are replaced whole, so to edit them, apply the edit to the current text and pass the complete result. Changes apply to sessions opened afterwards; running sessions keep the instructions they started with. Use ConfigureBot for the display name, handle, description, or picture, and ManageBotChannelAccess for plain webhook bots."+)]+pub struct ConfigureAgent {+ /// Agent to configure.+ #[schemars(description = "The agent's bot id: `bot.botId` from ListAgents.")]+ pub bot_id: Uuid,+ /// Replacement instructions.+ #[schemars(+ description = "The complete new instructions in markdown. Replaces the current instructions entirely; omit to keep them."+ )]+ #[serde(default)]+ pub instructions: Option<String>,+ /// Replacement runtime.+ #[schemars(+ description = "Runtime to move the agent onto. `macrod` also needs harnessId; the other runtimes must not have one. The current model may not exist on the new runtime, so usually pass defaultModel with it. Omit to keep the current runtime."+ )]+ #[serde(default)]+ pub harness: Option<AgentHarnessOption>,+ /// Registered harness for the `macrod` runtime.+ #[schemars(+ description = "Id of the registered self-hosted harness, required when harness is `macrod` and forbidden otherwise."+ )]+ #[serde(default)]+ pub harness_id: Option<Uuid>,+ /// Replacement model.+ #[schemars(+ description = "Model id the agent's new sessions should use, as the runtime names it (e.g. `claude-sonnet-4-5`). Valid ids depend on the runtime. Omit to keep the current model."+ )]+ #[serde(default)]+ pub default_model: Option<String>,+ /// Replacement channel scope.+ #[schemars(+ description = "`all` makes the agent mentionable in every channel its owner can use; `selected` limits it to channelIds. Omit to keep the current scope, or omit it and pass channelIds alone to switch to `selected`."+ )]+ #[serde(default)]+ pub channel_scope: Option<AgentChannelScopeSummary>,+ /// Replacement channel list.+ #[schemars(+ description = "The complete list of channel ids the agent is limited to; the user must be a member of each. Required with the `selected` scope and forbidden with `all`."+ )]+ #[serde(default)]+ pub channel_ids: Option<Vec<Uuid>>,+ /// Replacement MCP scope.+ #[schemars(+ description = "`owner_connections` hands sessions whatever apps the person running them has connected; `selected` hands exactly mcpServers. Omit to keep the current scope, or omit it and pass mcpServers alone to switch to `selected`."+ )]+ #[serde(default)]+ pub mcp_scope: Option<AgentMcpScopeSummary>,+ /// Replacement MCP server list.+ #[schemars(+ description = "The complete list of connected apps for the `selected` MCP scope, each as its Pipedream app slug (e.g. `linear`) and display name. A slug Pipedream does not list as a connectable app is rejected and nothing is saved. Forbidden with `owner_connections`."+ )]+ #[serde(default)]+ pub mcp_servers: Option<Vec<AgentMcpServerSummary>>,+ /// Replacement permission choice.+ #[schemars(+ description = "`true` lets sessions approve tool permission requests without asking, where the runtime allows it; `false` makes them ask every time. Omit to leave unchanged."+ )]+ #[serde(default)]+ pub auto_accept_permissions: Option<bool>,+ /// Replacement coding choice.+ #[schemars(+ description = "`true` for a coding agent, which works in a repository and answers a mention with a live session; `false` for a chat agent, which replies in the thread. Omit to leave unchanged."+ )]+ #[serde(default)]+ pub is_coding: Option<bool>,+}++impl ToolAnnotated for ConfigureAgent {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Configure agent");+}++fn invalid_arguments(description: &str) -> ToolCallError {+ ToolCallError {+ description: description.to_string(),+ internal_error: anyhow::anyhow!("invalid ConfigureAgent arguments: {description}"),+ }+}++impl ConfigureAgent {+ /// The names of the settings this call changes, for the summary.+ fn changed_fields(&self) -> Vec<&'static str> {+ [+ ("instructions", self.instructions.is_some()),+ ("runtime", self.harness.is_some()),+ ("model", self.default_model.is_some()),+ (+ "channels",+ self.channel_scope.is_some() || self.channel_ids.is_some(),+ ),+ (+ "connected apps",+ self.mcp_scope.is_some() || self.mcp_servers.is_some(),+ ),+ ("permissions", self.auto_accept_permissions.is_some()),+ ("coding mode", self.is_coding.is_some()),+ ]+ .into_iter()+ .filter_map(|(name, changed)| changed.then_some(name))+ .collect()+ }++ /// Translate the flat tool arguments into the domain patch, refusing+ /// combinations that name no coherent change.+ fn patch(&self) -> Result<PatchAgentRequest, ToolCallError> {+ let harness = match (self.harness, self.harness_id) {+ (Some(harness), harness_id) => Some(AgentHarnessSelection {+ harness: harness.slug().to_string(),+ harness_id: harness_id.map(HarnessId::new_from_uuid),+ }),+ (None, Some(_)) => {+ return Err(invalid_arguments(+ "harnessId only applies together with harness `macrod`; pass harness too",+ ));+ }+ (None, None) => None,+ };++ let channels = match (self.channel_scope, &self.channel_ids) {+ (None, None) => None,+ (Some(AgentChannelScopeSummary::All), Some(ids)) if !ids.is_empty() => {+ return Err(invalid_arguments(+ "channelIds only apply to the `selected` channel scope; omit them for `all`",+ ));+ }+ (Some(AgentChannelScopeSummary::All), _) => Some(AgentChannelSelection {+ channel_scope: AgentChannelScopeSummary::All.into(),+ channel_ids: Vec::new(),+ }),+ (Some(AgentChannelScopeSummary::Selected) | None, ids) => Some(AgentChannelSelection {+ channel_scope: AgentChannelScopeSummary::Selected.into(),+ channel_ids: ids.clone().unwrap_or_default(),+ }),+ };++ let mcp = match (self.mcp_scope, &self.mcp_servers) {+ (None, None) => None,+ (Some(AgentMcpScopeSummary::OwnerConnections), Some(servers))+ if !servers.is_empty() =>+ {+ return Err(invalid_arguments(+ "mcpServers only apply to the `selected` MCP scope; omit them for `owner_connections`",+ ));+ }+ (Some(AgentMcpScopeSummary::OwnerConnections), _) => {+ Some(AgentMcpServers::OwnerConnections)+ }+ (Some(AgentMcpScopeSummary::Selected) | None, servers) => {+ Some(AgentMcpServers::Selected {+ servers: servers+ .clone()+ .unwrap_or_default()+ .into_iter()+ .map(|server| AgentMcpServer {+ app_slug: server.app_slug,+ server_name: server.server_name,+ })+ .collect(),+ })+ }+ };++ let patch = PatchAgentRequest {+ instructions: self.instructions.clone(),+ harness,+ default_model: self.default_model.clone(),+ channels,+ mcp,+ auto_accept_permissions: self.auto_accept_permissions,+ is_coding: self.is_coding,+ };+ if patch == PatchAgentRequest::default() {+ return Err(invalid_arguments(+ "nothing to change: provide at least one field besides botId",+ ));+ }+ Ok(patch)+ }+}++#[async_trait]+impl<Svc, AccessSvc> AsyncTool<BotToolContext<Svc, AccessSvc>> for ConfigureAgent+where+ Svc: BotService,+ AccessSvc: EntityAccessService,+{+ type Output = ConfigureAgentResponse;++ #[tracing::instrument(+ skip_all,+ fields(user_id=?request_context.user_id, bot_id=%self.bot_id),+ err+ )]+ async fn call(+ &self,+ service_context: ServiceContext<BotToolContext<Svc, AccessSvc>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ let patch = self.patch()?;+ let agent = AgentSummary::try_from(+ service_context+ .service+ .patch_agent(+ request_context.user_id,+ BotId::new_from_uuid(self.bot_id),+ patch,+ )+ .await+ .map_err(|error| bot_tool_error("configure agent", error))?,+ )?;+ let summary = format!(+ "Updated @{}: {}. New sessions use the new configuration; running ones keep theirs.",+ agent.bot.handle,+ self.changed_fields().join(", ")+ );++ Ok(ConfigureAgentResponse { agent, summary })+ }+}diff --git a/crates/bots/src/inbound/toolset/list_agents.rs b/crates/bots/src/inbound/toolset/list_agents.rsnew file mode 100644index 0000000000..37effa70d7--- /dev/null+++ b/crates/bots/src/inbound/toolset/list_agents.rs@@ -0,0 +1,65 @@+//! ListAgents tool.++use super::{AgentSummary, BotToolContext, bot_tool_error};+use crate::domain::ports::BotService;+use ai_toolset::{+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,+};+use async_trait::async_trait;+use entity_access::domain::ports::EntityAccessService;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};++/// Response from [`ListAgents`].+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ListAgentsResponse {+ /// Agents the caller can manage, with their current instructions and settings.+ pub agents: Vec<AgentSummary>,+ /// Human-readable result summary.+ pub summary: String,+}++/// List the agents the user can manage, with their full configuration.+#[derive(Debug, Clone, Default, Deserialize, JsonSchema)]+#[schemars(+ title = "ListAgents",+ description = "List every AI agent the current user can manage - their own, their teams', and channel agents they can mention - with each agent's current instructions and settings: harness, model, channel availability, connected apps, permission behavior, and whether it is a coding or chat agent. Use this to find an agent's botId and read its current configuration before changing it with ConfigureAgent. ListBots covers plain webhook bots instead."+)]+pub struct ListAgents {}++impl ToolAnnotated for ListAgents {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("List agents");+}++#[async_trait]+impl<Svc, AccessSvc> AsyncTool<BotToolContext<Svc, AccessSvc>> for ListAgents+where+ Svc: BotService,+ AccessSvc: EntityAccessService,+{+ type Output = ListAgentsResponse;++ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]+ async fn call(+ &self,+ service_context: ServiceContext<BotToolContext<Svc, AccessSvc>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ let agents: Vec<AgentSummary> = service_context+ .service+ .list_agents(request_context.user_id)+ .await+ .map_err(|error| bot_tool_error("list agents", error))?+ .into_iter()+ .map(AgentSummary::try_from)+ .collect::<Result<Vec<_>, _>>()?;+ let summary = match agents.len() {+ 0 => "No manageable agents found.".to_string(),+ 1 => "Found 1 manageable agent.".to_string(),+ count => format!("Found {count} manageable agents."),+ };++ Ok(ListAgentsResponse { agents, summary })+ }+}diff --git a/crates/bots/src/inbound/toolset/test.rs b/crates/bots/src/inbound/toolset/test.rsindex 69b398c8ba..132c7cdf85 100644--- a/crates/bots/src/inbound/toolset/test.rs+++ b/crates/bots/src/inbound/toolset/test.rs@@ -1,15 +1,19 @@use super::{- BotOwnerSummary, BotSummary, BotToolContext, bot_tool_error,+ AgentChannelScopeSummary, AgentMcpScopeSummary, AgentMcpServerSummary, BotOwnerSummary,+ BotSummary, BotToolContext, bot_tool_error,+ configure_agent::{AgentHarnessOption, ConfigureAgent},create_bot::CreateBot,get_bot_webhooks::GetBotWebhooks,issue_bot_credential::IssueBotCredential,+ list_agents::ListAgents,manage_bot_channel_access::{BotChannelAccessAction, ManageBotChannelAccess},};use crate::domain::models::{- Agent, AuthenticatedBot, BotChannel, BotChannelListCaller, BotChannelType, BotOwnerProfile,- BotToken, CreateAgentRequest, CreateBotRequest, CreateBotTokenRequest, CreateBotTokenResponse,- CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, PatchBotRequest,- UpdateAgentRequest,+ Agent, AgentChannelScope, AgentChannelSelection, AgentHarnessSelection, AgentMcpServer,+ AgentMcpServers, AuthenticatedBot, BotChannel, BotChannelListCaller, BotChannelType,+ BotOwnerProfile, BotToken, CreateAgentRequest, CreateBotRequest, CreateBotTokenRequest,+ CreateBotTokenResponse, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse,+ HarnessId, PatchAgentRequest, PatchBotRequest, UpdateAgentRequest,};use crate::domain::{models::{Bot, BotKind, BotOwner},@@ -72,6 +76,21 @@ fn sample_token(bot_id: BotId, label: Option<String>) -> BotToken {}}+fn sample_agent(handle: &str) -> Agent {+ Agent {+ bot: sample_bot(handle),+ instructions: "Fix the root cause and add tests.".to_string(),+ harness: "cursor".to_string(),+ harness_id: None,+ default_model: "cursor-small".to_string(),+ channel_scope: AgentChannelScope::All,+ channel_ids: Vec::new(),+ mcp: AgentMcpServers::OwnerConnections,+ auto_accept_permissions: None,+ is_coding: true,+ }+}+#[derive(Clone, Default)]struct ToolTestBotService {channels: Vec<BotChannel>,@@ -80,7 +99,9 @@ struct ToolTestBotService {scoped: Arc<Mutex<Option<(Uuid, CreateChannelScopedBotRequest)>>>,added: Arc<Mutex<Option<BotId>>>,deleted: Arc<Mutex<Option<BotId>>>,+ patched: Arc<Mutex<Option<(BotId, PatchAgentRequest)>>>,add_error: Option<String>,+ patch_error: Option<String>,}impl BotService for ToolTestBotService {@@ -101,8 +122,33 @@ impl BotService for ToolTestBotService {unimplemented!()}+ async fn patch_agent(+ &self,+ _caller: MacroUserIdStr<'static>,+ bot_id: BotId,+ req: PatchAgentRequest,+ ) -> Result<Agent, BotError> {+ if let Some(message) = &self.patch_error {+ return Err(BotError::BadRequest(message.clone()));+ }+ let mut agent = sample_agent("bug-fixer");+ agent.bot.id = bot_id;+ let update = req.clone().apply_to(&agent);+ *self.patched.lock().expect("patch lock") = Some((bot_id, req));+ agent.instructions = update.instructions;+ agent.harness = update.harness;+ agent.harness_id = update.harness_id;+ agent.default_model = update.default_model;+ agent.channel_scope = update.channel_scope;+ agent.channel_ids = update.channel_ids;+ agent.mcp = update.mcp;+ agent.auto_accept_permissions = update.auto_accept_permissions;+ agent.is_coding = update.is_coding;+ Ok(agent)+ }+async fn list_agents(&self, _caller: MacroUserIdStr<'static>) -> Result<Vec<Agent>, BotError> {- unimplemented!()+ Ok(vec![sample_agent("bug-fixer")])}async fn create_bot(@@ -681,3 +727,233 @@ async fn webhook_response_uses_preferred_bot_authentication_headers() {format!("https://storage.example.com/channels/{channel_id}/webhook"));}++#[tokio::test]+async fn list_agents_returns_instructions_and_settings() {+ let context = BotToolContext::new(+ ToolTestBotService::default(),+ NoOpEntityAccessService,+ "https://storage.example.com".to_string(),+ );++ let response = ListAgents {}+ .call(ServiceContext(context), RequestContext::new(user_id()))+ .await+ .expect("listing needs no entity access");++ assert_eq!(response.summary, "Found 1 manageable agent.");+ let agent = &response.agents[0];+ assert_eq!(agent.bot.handle, "bug-fixer");+ assert_eq!(agent.instructions, "Fix the root cause and add tests.");+ assert_eq!(agent.harness, "cursor");+ assert_eq!(agent.default_model, "cursor-small");+ assert_eq!(agent.channel_scope, AgentChannelScopeSummary::All);+ assert_eq!(agent.mcp_scope, AgentMcpScopeSummary::OwnerConnections);+ assert!(agent.mcp_servers.is_empty());+ assert_eq!(agent.auto_accept_permissions, None);+ assert!(agent.is_coding);+}++#[tokio::test]+async fn configure_agent_patches_only_named_fields() {+ let service = ToolTestBotService::default();+ let patched = service.patched.clone();+ let context = BotToolContext::new(+ service,+ NoOpEntityAccessService,+ "https://storage.example.com".to_string(),+ );+ let bot_id = Uuid::new_v4();++ let response = ConfigureAgent {+ bot_id,+ instructions: Some("Diagnose first, then make the smallest tested fix.".to_string()),+ default_model: Some("claude-sonnet-4-5".to_string()),+ ..ConfigureAgent::default()+ }+ .call(ServiceContext(context), RequestContext::new(user_id()))+ .await+ .expect("instructions and model are a valid patch");++ let (patched_id, patch) = patched+ .lock()+ .expect("patch lock")+ .clone()+ .expect("service should receive the patch");+ assert_eq!(patched_id, BotId::new_from_uuid(bot_id));+ assert_eq!(+ patch,+ PatchAgentRequest {+ instructions: Some("Diagnose first, then make the smallest tested fix.".to_string()),+ default_model: Some("claude-sonnet-4-5".to_string()),+ ..PatchAgentRequest::default()+ }+ );+ assert_eq!(+ response.agent.instructions,+ "Diagnose first, then make the smallest tested fix."+ );+ assert_eq!(response.agent.default_model, "claude-sonnet-4-5");+ assert_eq!(response.agent.harness, "cursor");+ assert!(+ response+ .summary+ .starts_with("Updated @bug-fixer: instructions, model.")+ );+}++#[tokio::test]+async fn configure_agent_translates_scoped_selections() {+ let service = ToolTestBotService::default();+ let patched = service.patched.clone();+ let context = BotToolContext::new(+ service,+ NoOpEntityAccessService,+ "https://storage.example.com".to_string(),+ );+ let channel_id = Uuid::new_v4();+ let harness_id = Uuid::new_v4();++ let response = ConfigureAgent {+ bot_id: Uuid::new_v4(),+ harness: Some(AgentHarnessOption::Macrod),+ harness_id: Some(harness_id),+ channel_ids: Some(vec![channel_id]),+ mcp_servers: Some(vec![AgentMcpServerSummary {+ app_slug: "linear".to_string(),+ server_name: "Linear".to_string(),+ }]),+ auto_accept_permissions: Some(true),+ is_coding: Some(false),+ ..ConfigureAgent::default()+ }+ .call(ServiceContext(context), RequestContext::new(user_id()))+ .await+ .expect("ids alone select the `selected` scopes");++ let (_, patch) = patched+ .lock()+ .expect("patch lock")+ .clone()+ .expect("service should receive the patch");+ assert_eq!(+ patch.harness,+ Some(AgentHarnessSelection {+ harness: "macrod".to_string(),+ harness_id: Some(HarnessId::new_from_uuid(harness_id)),+ })+ );+ assert_eq!(+ patch.channels,+ Some(AgentChannelSelection {+ channel_scope: AgentChannelScope::Selected,+ channel_ids: vec![channel_id],+ })+ );+ assert_eq!(+ patch.mcp,+ Some(AgentMcpServers::Selected {+ servers: vec![AgentMcpServer {+ app_slug: "linear".to_string(),+ server_name: "Linear".to_string(),+ }],+ })+ );+ assert_eq!(patch.auto_accept_permissions, Some(true));+ assert_eq!(patch.is_coding, Some(false));+ assert_eq!(+ response.agent.channel_scope,+ AgentChannelScopeSummary::Selected+ );+ assert_eq!(response.agent.channel_ids, vec![channel_id]);+ assert_eq!(response.agent.mcp_scope, AgentMcpScopeSummary::Selected);+ assert_eq!(response.agent.harness_id, Some(harness_id));+}++#[tokio::test]+async fn configure_agent_rejects_incoherent_arguments() {+ let cases = [+ (+ ConfigureAgent {+ bot_id: Uuid::new_v4(),+ ..ConfigureAgent::default()+ },+ "nothing to change",+ ),+ (+ ConfigureAgent {+ bot_id: Uuid::new_v4(),+ harness_id: Some(Uuid::new_v4()),+ ..ConfigureAgent::default()+ },+ "pass harness too",+ ),+ (+ ConfigureAgent {+ bot_id: Uuid::new_v4(),+ channel_scope: Some(AgentChannelScopeSummary::All),+ channel_ids: Some(vec![Uuid::new_v4()]),+ ..ConfigureAgent::default()+ },+ "omit them for `all`",+ ),+ (+ ConfigureAgent {+ bot_id: Uuid::new_v4(),+ mcp_scope: Some(AgentMcpScopeSummary::OwnerConnections),+ mcp_servers: Some(vec![AgentMcpServerSummary {+ app_slug: "linear".to_string(),+ server_name: "Linear".to_string(),+ }]),+ ..ConfigureAgent::default()+ },+ "omit them for `owner_connections`",+ ),+ ];++ for (call, expected) in cases {+ let service = ToolTestBotService::default();+ let patched = service.patched.clone();+ let context = BotToolContext::new(+ service,+ NoOpEntityAccessService,+ "https://storage.example.com".to_string(),+ );+ let error = call+ .call(ServiceContext(context), RequestContext::new(user_id()))+ .await+ .expect_err("incoherent arguments never reach the service");+ assert!(+ error.description.contains(expected),+ "{expected:?} not in {:?}",+ error.description+ );+ assert!(patched.lock().expect("patch lock").is_none());+ }+}++#[tokio::test]+async fn configure_agent_surfaces_domain_rejections() {+ let context = BotToolContext::new(+ ToolTestBotService {+ patch_error: Some("channel-specific agents require at least one channel".to_string()),+ ..ToolTestBotService::default()+ },+ NoOpEntityAccessService,+ "https://storage.example.com".to_string(),+ );++ let error = ConfigureAgent {+ bot_id: Uuid::new_v4(),+ channel_scope: Some(AgentChannelScopeSummary::Selected),+ ..ConfigureAgent::default()+ }+ .call(ServiceContext(context), RequestContext::new(user_id()))+ .await+ .expect_err("the domain's validation message reaches the model");++ assert_eq!(+ error.description,+ "channel-specific agents require at least one channel"+ );+}diff --git a/crates/bots/src/inbound/toolset/types.rs b/crates/bots/src/inbound/toolset/types.rsindex 818044306e..3e2b4922ea 100644--- a/crates/bots/src/inbound/toolset/types.rs+++ b/crates/bots/src/inbound/toolset/types.rs@@ -1,10 +1,10 @@//! Shared bot tool response types.-use crate::domain::models::{Bot, BotOwner};+use crate::domain::models::{Agent, AgentChannelScope, AgentMcpServers, Bot, BotOwner};use ai_toolset::ToolCallError;use chrono::{DateTime, Utc};use schemars::JsonSchema;-use serde::Serialize;+use serde::{Deserialize, Serialize};use uuid::Uuid;/// Preferred header used to authenticate bot webhook requests.@@ -82,6 +82,120 @@ impl TryFrom<Bot> for BotSummary {}}+/// Where an agent can be mentioned.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]+#[serde(rename_all = "snake_case")]+pub enum AgentChannelScopeSummary {+ /// Every channel its owner can use.+ All,+ /// Only the listed channels.+ Selected,+}++impl From<AgentChannelScope> for AgentChannelScopeSummary {+ fn from(scope: AgentChannelScope) -> Self {+ match scope {+ AgentChannelScope::All => Self::All,+ AgentChannelScope::Selected => Self::Selected,+ }+ }+}++impl From<AgentChannelScopeSummary> for AgentChannelScope {+ fn from(scope: AgentChannelScopeSummary) -> Self {+ match scope {+ AgentChannelScopeSummary::All => Self::All,+ AgentChannelScopeSummary::Selected => Self::Selected,+ }+ }+}++/// Which connected apps an agent's sessions are handed as MCP servers.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]+#[serde(rename_all = "snake_case")]+pub enum AgentMcpScopeSummary {+ /// Whatever apps the person running the session has connected.+ OwnerConnections,+ /// Exactly the listed apps, whether or not the person has connected them.+ Selected,+}++/// One Pipedream app an agent lists under the `selected` MCP scope.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct AgentMcpServerSummary {+ /// Pipedream app slug, e.g. `linear`.+ pub app_slug: String,+ /// Display name, e.g. `Linear`.+ pub server_name: String,+}++/// High-signal agent details returned to AI agents: the bot profile plus the+/// instructions and settings that decide how its sessions run.+#[derive(Debug, Clone, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct AgentSummary {+ /// The bot the agent speaks as; `bot.botId` is the id every agent tool takes.+ pub bot: BotSummary,+ /// Instructions the agent works under, whole. New sessions snapshot them.+ pub instructions: String,+ /// Harness slug: `in-memory`, `cursor`, `claude-cloud`, or `macrod`.+ pub harness: String,+ /// Registered harness the agent runs on when `harness` is `macrod`.+ pub harness_id: Option<Uuid>,+ /// Model id the agent's sessions open with. Valid ids depend on the harness.+ pub default_model: String,+ /// Where the agent can be mentioned.+ pub channel_scope: AgentChannelScopeSummary,+ /// Selected channel ids; empty unless `channelScope` is `selected`.+ pub channel_ids: Vec<Uuid>,+ /// Which connected apps its sessions are handed.+ pub mcp_scope: AgentMcpScopeSummary,+ /// Selected apps; empty unless `mcpScope` is `selected`.+ pub mcp_servers: Vec<AgentMcpServerSummary>,+ /// Whether sessions approve tool permission requests without asking.+ /// Absent means the agent always prompts.+ pub auto_accept_permissions: Option<bool>,+ /// Whether the agent is a coding agent (works in a repository and answers+ /// mentions with a live session) or a chat agent (replies in the thread).+ pub is_coding: bool,+}++impl TryFrom<Agent> for AgentSummary {+ type Error = ToolCallError;++ fn try_from(agent: Agent) -> Result<Self, Self::Error> {+ let (mcp_scope, mcp_servers) = match agent.mcp {+ AgentMcpServers::OwnerConnections => {+ (AgentMcpScopeSummary::OwnerConnections, Vec::new())+ }+ AgentMcpServers::Selected { servers } => (+ AgentMcpScopeSummary::Selected,+ servers+ .into_iter()+ .map(|server| AgentMcpServerSummary {+ app_slug: server.app_slug,+ server_name: server.server_name,+ })+ .collect(),+ ),+ };+ Ok(Self {+ bot: BotSummary::try_from(agent.bot)?,+ instructions: agent.instructions,+ harness: agent.harness,+ harness_id: agent.harness_id.map(|id| id.as_uuid()),+ default_model: agent.default_model,+ channel_scope: agent.channel_scope.into(),+ channel_ids: agent.channel_ids,+ mcp_scope,+ mcp_servers,+ auto_accept_permissions: agent.auto_accept_permissions,+ is_coding: agent.is_coding,+ })+ }+}+/// One channel-specific webhook URL for a bot.#[derive(Debug, Clone, Serialize, JsonSchema)]#[serde(rename_all = "camelCase")]diff --git a/crates/bots/src/outbound/pg_bots_repo/tests.rs b/crates/bots/src/outbound/pg_bots_repo/tests.rsindex 7ce319cabf..c302cad058 100644--- a/crates/bots/src/outbound/pg_bots_repo/tests.rs+++ b/crates/bots/src/outbound/pg_bots_repo/tests.rs@@ -3,9 +3,9 @@ use crate::domain::{models::{AgentChannelScope, AgentMcpServer, AgentMcpServers, BotChannelListCaller, BotChannelType,CreateAgentRequest, CreateBotRequest, CreateBotTokenRequest, CreateChannelScopedBotRequest,- PatchBotRequest, UpdateAgentRequest,+ PatchAgentRequest, PatchBotRequest, UpdateAgentRequest,},- ports::{BotError, BotService},+ ports::{BotError, BotService, McpAppCatalog},service::BotServiceImpl,};use entity_access::domain::models::{@@ -111,6 +111,15 @@ fn service(pool: &PgPool) -> BotServiceImpl<PgBotsRepo, NoopMacroEventBroker> {BotServiceImpl::new(PgBotsRepo::new(pool.clone()), NoopMacroEventBroker)}+/// A directory that knows only the slugs it is given.+struct KnownApps(&'static [&'static str]);++impl McpAppCatalog for KnownApps {+ async fn is_connectable_app(&self, slug: &str) -> Result<bool, BotError> {+ Ok(self.0.contains(&slug))+ }+}+#[derive(Clone, Debug)]struct PublishedEvent {topic: &'static str,@@ -745,6 +754,152 @@ async fn updated_agent_replaces_every_field_and_selected_channel(Ok(())}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn patched_agent_changes_only_what_the_patch_names(pool: PgPool) -> anyhow::Result<()> {+ let channel_id = Uuid::new_v4();+ insert_channel_member(&pool, channel_id, USER_OWNER).await?;+ let service = service(&pool);+ let mut create = create_agent_req("bug-fixer", AgentChannelScope::Selected);+ create.channel_ids = vec![channel_id];+ create.mcp = AgentMcpServers::Selected {+ servers: vec![mcp_server("linear", "Linear")],+ };+ let created = service.create_agent(user_id(USER_OWNER), create).await?;++ let patched = service+ .patch_agent(+ user_id(USER_OWNER),+ created.bot.id,+ PatchAgentRequest {+ instructions: Some(+ "Diagnose first, then make the smallest tested fix.".to_string(),+ ),+ default_model: Some("cursor-large".to_string()),+ ..PatchAgentRequest::default()+ },+ )+ .await?;++ assert_eq!(+ patched.instructions,+ "Diagnose first, then make the smallest tested fix."+ );+ assert_eq!(patched.default_model, "cursor-large");+ // Everything the patch left unnamed survives, the selected channel and+ // apps included - a patch is not a reset to defaults.+ assert_eq!(patched.bot.name, "Bug fixer");+ assert_eq!(patched.bot.handle, "bug-fixer");+ assert_eq!(+ patched.bot.description.as_deref(),+ Some("Finds and fixes bugs")+ );+ assert_eq!(patched.harness, "cursor");+ assert_eq!(patched.channel_scope, AgentChannelScope::Selected);+ assert_eq!(patched.channel_ids, vec![channel_id]);+ assert_eq!(+ patched.mcp,+ AgentMcpServers::Selected {+ servers: vec![mcp_server("linear", "Linear")],+ }+ );+ assert!(patched.is_coding);+ assert_eq!(+ active_channel_participant_count(&pool, channel_id, created.bot.id).await?,+ 1+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn patch_agent_refuses_an_mcp_slug_the_directory_does_not_list(+ pool: PgPool,+) -> anyhow::Result<()> {+ let service = service(&pool).with_mcp_apps(KnownApps(&["linear"]));+ let created = service+ .create_agent(+ user_id(USER_OWNER),+ create_agent_req("bug-fixer", AgentChannelScope::All),+ )+ .await?;++ let error = service+ .patch_agent(+ user_id(USER_OWNER),+ created.bot.id,+ PatchAgentRequest {+ mcp: Some(AgentMcpServers::Selected {+ servers: vec![mcp_server("not-a-real-app", "Not real")],+ }),+ ..PatchAgentRequest::default()+ },+ )+ .await+ .expect_err("an invented Pipedream slug is refused");+ assert!(matches!(error, BotError::BadRequest(_)));++ let stored = PgBotsRepo::new(pool.clone())+ .get_agent(created.bot.id)+ .await?+ .expect("the agent is unchanged");+ assert_eq!(stored.mcp, AgentMcpServers::OwnerConnections);++ let patched = service+ .patch_agent(+ user_id(USER_OWNER),+ created.bot.id,+ PatchAgentRequest {+ mcp: Some(AgentMcpServers::Selected {+ servers: vec![mcp_server("linear", "Linear")],+ }),+ ..PatchAgentRequest::default()+ },+ )+ .await?;+ assert_eq!(+ patched.mcp,+ AgentMcpServers::Selected {+ servers: vec![mcp_server("linear", "Linear")],+ }+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn patch_agent_is_refused_for_strangers_and_plain_bots(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool, USER_OTHER).await?;+ let service = service(&pool);+ let agent = service+ .create_agent(+ user_id(USER_OWNER),+ create_agent_req("bug-fixer", AgentChannelScope::All),+ )+ .await?;+ let plain_bot = service+ .create_bot(user_id(USER_OWNER), create_req("alerts"))+ .await?;+ let patch = PatchAgentRequest {+ instructions: Some("Be terse.".to_string()),+ ..PatchAgentRequest::default()+ };++ let stranger = service+ .patch_agent(user_id(USER_OTHER), agent.bot.id, patch.clone())+ .await;+ assert!(+ matches!(stranger, Err(BotError::Unauthorized)),+ "{stranger:?}"+ );++ let not_an_agent = service+ .patch_agent(user_id(USER_OWNER), plain_bot.id, patch)+ .await;+ assert!(+ matches!(not_an_agent, Err(BotError::NotFound(_))),+ "{not_an_agent:?}"+ );+ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn auto_accept_permissions_persists_each_of_its_three_states(pool: PgPool,diff --git a/crates/pipedream_mcp/src/domain/ports.rs b/crates/pipedream_mcp/src/domain/ports.rsindex 573fd238da..90b703cb6c 100644--- a/crates/pipedream_mcp/src/domain/ports.rs+++ b/crates/pipedream_mcp/src/domain/ports.rs@@ -1,5 +1,6 @@use super::models::{- CatalogPage, ConnectToken, MacroUserIdStr, McpServer, PipedreamAccount, PipedreamConnection,+ CatalogEntry, CatalogPage, ConnectToken, MacroUserIdStr, McpServer, PipedreamAccount,+ PipedreamConnection,};/// Port for persisting Pipedream-connected apps, keyed by user and app slug.@@ -99,4 +100,14 @@ pub trait ConnectorDirectory: Send + Sync + 'static {cursor: Option<&str>,limit: u32,) -> impl Future<Output = anyhow::Result<CatalogPage>> + Send;++ /// Look up one app by its name slug.+ ///+ /// `Ok(None)` when Pipedream has no connectable app under that exact slug:+ /// unknown, or an app with no auth flow (nothing to connect). A lookup+ /// that cannot be completed is an error, not a miss.+ fn retrieve(+ &self,+ app_slug: &str,+ ) -> impl Future<Output = anyhow::Result<Option<CatalogEntry>>> + Send;}diff --git a/crates/pipedream_mcp/src/domain/service/catalog/test.rs b/crates/pipedream_mcp/src/domain/service/catalog/test.rsindex ff91b18e12..4f4daeab7b 100644--- a/crates/pipedream_mcp/src/domain/service/catalog/test.rs+++ b/crates/pipedream_mcp/src/domain/service/catalog/test.rs@@ -34,6 +34,15 @@ impl ConnectorDirectory for FakeDirectory {));Ok(self.page.clone())}++ async fn retrieve(&self, app_slug: &str) -> anyhow::Result<Option<CatalogEntry>> {+ Ok(self+ .page+ .entries+ .iter()+ .find(|entry| entry.app_slug == app_slug)+ .cloned())+ }}fn directory_entry(app_slug: &str) -> CatalogEntry {diff --git a/crates/pipedream_mcp/src/outbound/api.rs b/crates/pipedream_mcp/src/outbound/api.rsindex 57caf04cb3..ae145a05e2 100644--- a/crates/pipedream_mcp/src/outbound/api.rs+++ b/crates/pipedream_mcp/src/outbound/api.rs@@ -239,6 +239,37 @@ impl PipedreamConnect for PipedreamClient {}impl ConnectorDirectory for PipedreamClient {+ #[tracing::instrument(skip(self), err, fields(app = %app_slug))]+ async fn retrieve(&self, app_slug: &str) -> anyhow::Result<Option<CatalogEntry>> {+ // The slug is interpolated into the path. Anything outside Pipedream's+ // app-slug charset is not an app, and is not requested.+ if !is_app_slug(app_slug) {+ return Ok(None);+ }++ let response = self+ .authed(+ self.http+ .get(self.api(&format!("/connect/apps/{app_slug}"))),+ )+ .await?+ .send()+ .await+ .context("retrieving Pipedream app")?;+ if response.status() == reqwest::StatusCode::NOT_FOUND {+ return Ok(None);+ }+ let response = error_for_status(response).await?;++ let body: serde_json::Value = response+ .json()+ .await+ .context("decoding Pipedream app response")?;+ let app = body.get("data").unwrap_or(&body).clone();+ let app: AppResponse = serde_json::from_value(app).context("parsing Pipedream app")?;+ Ok(connectable_catalog_entry(app_slug, app))+ }+#[tracing::instrument(skip(self), err)]async fn search(&self,@@ -390,6 +421,31 @@ impl McpConnection for PipedreamClient {}}+/// The charset a Pipedream app slug may use. A segment outside it could never+/// name an app, and must not be placed in a request path.+fn is_app_slug(slug: &str) -> bool {+ !slug.is_empty()+ && slug+ .chars()+ .all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '-' || ch == '_')+}++/// An app the catalog would offer to connect: the slug we asked for, with an+/// auth flow. Apps with `auth_type: none` have nothing to connect.+fn connectable_catalog_entry(requested_slug: &str, app: AppResponse) -> Option<CatalogEntry> {+ if app.auth_type.as_deref() == Some("none") || app.name_slug != requested_slug {+ return None;+ }+ Some(CatalogEntry {+ app_slug: app.name_slug,+ display_name: app.name,+ description: app+ .description+ .filter(|description| !description.is_empty()),+ icon_url: Some(app.img_src).filter(|url| url.starts_with("https://")),+ })+}+async fn error_for_status(response: reqwest::Response) -> anyhow::Result<reqwest::Response> {let status = response.status();if status.is_success() {@@ -439,6 +495,9 @@ struct PageInfo {end_cursor: Option<String>,}+#[cfg(test)]+mod test;+#[derive(Deserialize)]struct AppResponse {name_slug: String,diff --git a/crates/pipedream_mcp/src/outbound/api/test.rs b/crates/pipedream_mcp/src/outbound/api/test.rsnew file mode 100644index 0000000000..0e8629bd36--- /dev/null+++ b/crates/pipedream_mcp/src/outbound/api/test.rs@@ -0,0 +1,31 @@+use super::{AppResponse, connectable_catalog_entry};++fn app(slug: &str, auth_type: Option<&str>) -> AppResponse {+ AppResponse {+ name_slug: slug.to_owned(),+ name: slug.to_owned(),+ description: None,+ auth_type: auth_type.map(str::to_owned),+ img_src: "https://assets.pipedream.net/linear.png".to_owned(),+ }+}++#[test]+fn a_matching_slug_with_an_auth_flow_is_connectable() {+ let entry = connectable_catalog_entry("linear", app("linear", Some("oauth"))).expect("app");+ assert_eq!(entry.app_slug, "linear");+ assert_eq!(+ entry.icon_url.as_deref(),+ Some("https://assets.pipedream.net/linear.png")+ );+}++#[test]+fn an_app_without_an_auth_flow_is_not_connectable() {+ assert!(connectable_catalog_entry("webhook", app("webhook", Some("none"))).is_none());+}++#[test]+fn a_different_slug_than_the_one_asked_for_is_not_that_app() {+ assert!(connectable_catalog_entry("linear", app("slack", Some("oauth"))).is_none());+}diff --git a/crates/system_skills/src/configure_agent.rs b/crates/system_skills/src/configure_agent.rsnew file mode 100644index 0000000000..f617bd960f--- /dev/null+++ b/crates/system_skills/src/configure_agent.rs@@ -0,0 +1,57 @@+//! System skill for changing an agent's instructions and settings.++use prompt::StaticPrompt;++use crate::SystemSkill;++static TITLE: &str = "Configure Agent";++static INSTRUCTIONS: &str = r##"Follow this skill when the user asks to change how one of their agents behaves - its instructions or system prompt, the model or runtime it runs on, which channels it answers in, which connected apps its sessions get, whether it asks before using tools, or whether it is a coding or chat agent. Agents are the personas people `@` mention in channels and open sessions with; each has a bot profile plus this configuration.++## Find the agent++1. Call `ListAgents`. It returns every agent the user can manage with its current instructions and settings. Match the user's wording against `bot.name` and `bot.handle`; if more than one agent fits or none does, list the candidates and ask rather than guessing.+2. Keep the agent's `bot.botId` - every configuration call takes it.++## Change instructions++Instructions are replaced whole, not merged. To edit them:++1. Start from the current `instructions` text in the `ListAgents` result.+2. Apply exactly what the user asked - add, remove, or reword that part - and leave everything else intact, including formatting and headings.+3. For a substantial rewrite, or when the user's intent is ambiguous, show the proposed new text and confirm before applying. For a small, clearly specified edit, apply it and show what changed afterwards.+4. Call `ConfigureAgent` with `botId` and the complete new `instructions`.++Never send a fragment as the new instructions: it would erase the rest.++## Change settings++Pass only the fields that should change; `ConfigureAgent` keeps the others.++- **Runtime (`harness`)**: `in-memory` is Macro's built-in chat agent; `cursor` and `claude-cloud` run on the user's connected Cursor or Claude account; `macrod` is a self-hosted harness and needs `harnessId`. Model ids are runtime-specific, so when the runtime changes, ask which model to use unless the user named one, and pass `defaultModel` in the same call.+- **Model (`defaultModel`)**: pass the id as the runtime names it. If the user gives a family name ("Sonnet", "Opus"), confirm the exact id before applying.+- **Channels**: `channelScope: "all"` makes the agent mentionable everywhere the owner is; `channelIds` limits it to those channels - the complete list, and the user must belong to each. Resolve channel names to ids first.+- **Connected apps**: `mcpScope: "owner_connections"` gives sessions whatever apps the person running them has connected; `mcpServers` pins an exact list of Pipedream apps by `appSlug` and `serverName`. `appSlug` must be a real Pipedream app slug, such as `linear` or `google_sheets`. An invented slug is rejected and the agent is left unchanged; if you are not sure of the slug, ask rather than guessing.+- **Permissions (`autoAcceptPermissions`)**: `true` lets sessions approve tool permission requests without asking, `false` makes them ask. Self-hosted harnesses only honor `true` when their operator allows bypass; the tool reports the refusal.+- **Coding mode (`isCoding`)**: a coding agent works in a repository and answers a mention with a live session; a chat agent replies in the thread.++Profile changes - display name, handle, description, picture - go through `ConfigureBot` instead.++## Report++State what changed in one or two sentences, quoting the new instruction text or setting values. Mention that sessions already running keep the configuration they opened with; only new sessions pick up the change. If the tool refused the change, relay its reason and what would make it valid.+"##;++static INTENT: &str = "Requests to change an agent's behavior are resolved to one manageable agent, applied as a \+ whole-text instruction replacement or a minimal settings patch through ConfigureAgent, and \+ reported with what changed and that only new sessions see it.";++/// The skill's instructions as a composable prompt section.+pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(TITLE, INSTRUCTIONS, INTENT);++/// The configure-agent system skill.+pub static SKILL: SystemSkill = SystemSkill {+ slug: "configure-agent",+ name: "Configure Agent",+ content: &PROMPT,+};diff --git a/crates/system_skills/src/lib.rs b/crates/system_skills/src/lib.rsindex 27f40cde39..27c4afa3b8 100644--- a/crates/system_skills/src/lib.rs+++ b/crates/system_skills/src/lib.rs@@ -16,6 +16,7 @@ use prompt::Section;use uuid::Uuid;pub mod catch_me_up;+pub mod configure_agent;pub mod what_i_did_yesterday;#[cfg(test)]@@ -51,7 +52,11 @@ impl SystemSkill {}/// Every system skill, in display order.-pub static SYSTEM_SKILLS: &[&SystemSkill] = &[&catch_me_up::SKILL, &what_i_did_yesterday::SKILL];+pub static SYSTEM_SKILLS: &[&SystemSkill] = &[+ &catch_me_up::SKILL,+ &what_i_did_yesterday::SKILL,+ &configure_agent::SKILL,+];/// Look up a system skill by its well-known id.pub fn system_skill(id: Uuid) -> Option<&'static SystemSkill> {diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex 57ed964927..5bc0c6cc3b 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -1094,6 +1094,21 @@ recently updated visible skill documents plus built-ins; `SearchSkills` finds askill by name, including older skills outside that list. A skill mention's id canalso be passed directly to `ReadSkill`.+## Configuring agents from a conversation++The built-in **Configure Agent** skill walks an agent through changing another+agent's instructions or settings on the user's behalf. `ListAgents` returns every+agent the user can manage with its current instructions, runtime, model, channel+scope, connected apps, permission choice, and coding/chat mode; `ConfigureAgent`+patches only the fields it is given. A selected MCP app slug must be a real+Pipedream app; an invented slug is rejected and the agent is left unchanged.+Instructions are replaced whole, so the skill+has the agent edit the current text and send the complete result. Changes reach+sessions opened afterwards; running sessions keep the instructions they started+with. Both tools render as expandable rows in chat, agent sessions, and channel+replies; the profile fields (name, handle, description, picture) stay with+`ConfigureBot`.+The chat's **Read skill** tool row expands to show the full instructions. Whenverifying this flow, invoke a saved skill by name, confirm the agent reads it,and expand the row to inspect the returned content. Document access permissionsdiff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rsindex 03a4f5cef0..00165ecff5 100644--- a/services/document_cognition_service/src/api/context/test.rs+++ b/services/document_cognition_service/src/api/context/test.rs@@ -479,6 +479,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arai_tools::ToolBotEventBroker::Real(macro_event_broker.clone()),entity_access_service.clone(),"http://localhost:8086".to_string(),+ None,),project_tool_context,initiative_tool_context,diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rsindex 887c7b33cc..f6ec037ed8 100644--- a/services/document_cognition_service/src/main.rs+++ b/services/document_cognition_service/src/main.rs@@ -697,6 +697,7 @@ async fn main() -> anyhow::Result<()> {ai_tools::ToolBotEventBroker::Real(macro_event_broker.clone()),entity_access_service.clone(),DocumentStorageServiceUrl::new()?.to_string(),+ pipedream_client.clone(),),project_tool_context,initiative_tool_context,diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rsindex a36008b21f..989ff57559 100644--- a/services/document_storage_service/src/api/context.rs+++ b/services/document_storage_service/src/api/context.rs@@ -386,7 +386,8 @@ pub(crate) type DssChannelsState =ChannelsRouterState<DssChannelService, EntityAccessService, AuthorizationService>;/// Type alias for the bots service wired into DSS.-pub(crate) type DssBotService = BotServiceImpl<PgBotsRepo, DssEventBroker>;+pub(crate) type DssBotService =+ BotServiceImpl<PgBotsRepo, DssEventBroker, ai_tools::PipedreamMcpAppCatalog>;/// Type alias for the bots router state.pub(crate) type DssBotsState =diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rsindex 5d4b58605e..43a297326a 100644--- a/services/document_storage_service/src/main.rs+++ b/services/document_storage_service/src/main.rs@@ -338,7 +338,11 @@ async fn run() -> anyhow::Result<()> {event_broker_tracker.clone(),);let bots_repo = PgBotsRepo::new(db.clone());- let bots_service = BotServiceImpl::new(bots_repo, macro_event_broker.clone());+ // The agent API checks a newly selected MCP app against Pipedream's+ // directory, the same check the ConfigureAgent tool makes.+ let bots_service = BotServiceImpl::new(bots_repo, macro_event_broker.clone()).with_mcp_apps(+ ai_tools::PipedreamMcpAppCatalog::new(ai_tools::pipedream_client_from_env()?),+ );let authorization_service: AuthorizationService = MacroAuthorizationServiceImpl::new(MacroAuthJwtValidator::new(jwt_validation_args.clone()),diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rsindex 390d9242e7..bd4c2e7b84 100644--- a/services/mcp_service/src/context.rs+++ b/services/mcp_service/src/context.rs@@ -432,6 +432,7 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<Toai_tools::ToolBotEventBroker::Real(macro_event_broker.clone()),entity_access_service.clone(),dss_url,+ ai_tools::pipedream_client_from_env()?,),project_tool_context,initiative_tool_context,