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(sdk): connected apps, MCP servers and connector discovery from code mode (#9601)
Wolf Mermelstein4fb369936ac2
diff --git a/Cargo.lock b/Cargo.lockindex dd24ba85d4..b0cfe6c750 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -329,7 +329,9 @@ dependencies = ["macro_db_migrator","macro_user_id","macro_uuid",+ "mcp_client","nutype",+ "pipedream_mcp","rootcause","schemars 1.2.1","serde",diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.tsindex 3597a5ad93..a21f9516ec 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts@@ -22,9 +22,17 @@ import type {AppConnectedRequest,AutoArchiveOverridesBody,AutoArchivePreferencesBody,+ CallConnectedTool,ClassifyInputRequest,ClassifyInputResponse,CodingPreferencesBody,+ ConnectedApp,+ ConnectedAppKind,+ ConnectedTool,+ ConnectedToolResult,+ ConnectedToolSearch,+ ConnectMcpServer,+ ConnectMcpServerResponse,ControlRequest,ControlResponse,CreateAgentSessionRequest,@@ -32,6 +40,8 @@ import type {CreateReview,DiscoverAgentCapabilitiesRequest,DiscoverAgentCapabilitiesResponse,+ DiscoverConnectorsResponse,+ DiscoveryRequest,EditQueuedActionRequest,ExecutionRecord,ExtractInputRequest,@@ -51,6 +61,7 @@ import type {ReviewDecision,ReviewRecord,SandboxSizeBody,+ SearchConnectedAppToolsParams,SessionAutoArchiveResponse,SessionPullRequestsResponse,SetAgentSessionArchivedRequest,@@ -2024,6 +2035,439 @@ export const getCodeExecution = async (} as getCodeExecutionResponse;};+/**+ * @summary List the connected apps and custom MCP servers the session's agent may use.+ */+export type listExecutionConnectedAppsResponse200 = {+ data: ConnectedApp[];+ status: 200;+};++export type listExecutionConnectedAppsResponse403 = {+ data: void;+ status: 403;+};++export type listExecutionConnectedAppsResponse404 = {+ data: void;+ status: 404;+};++export type listExecutionConnectedAppsResponseSuccess =+ listExecutionConnectedAppsResponse200 & {+ headers: Headers;+ };+export type listExecutionConnectedAppsResponseError = (+ | listExecutionConnectedAppsResponse403+ | listExecutionConnectedAppsResponse404+) & {+ headers: Headers;+};++export type listExecutionConnectedAppsResponse =+ | listExecutionConnectedAppsResponseSuccess+ | listExecutionConnectedAppsResponseError;++export const getListExecutionConnectedAppsUrl = (+ sessionId: string,+ executionId: string+) => {+ return `/agent-sessions/${sessionId}/code-executions/${executionId}/connected-apps`;+};++export const listExecutionConnectedApps = async (+ sessionId: string,+ executionId: string,+ options?: RequestInit+): Promise<listExecutionConnectedAppsResponse> => {+ const res = await fetch(+ getListExecutionConnectedAppsUrl(sessionId, executionId),+ {+ ...options,+ method: 'GET',+ }+ );++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: listExecutionConnectedAppsResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as listExecutionConnectedAppsResponse;+};++/**+ * @summary Search the connectable app catalog, or inspect one app's tools and connection status.+ */+export type discoverConnectedAppsResponse200 = {+ data: DiscoverConnectorsResponse;+ status: 200;+};++export type discoverConnectedAppsResponse400 = {+ data: void;+ status: 400;+};++export type discoverConnectedAppsResponse403 = {+ data: void;+ status: 403;+};++export type discoverConnectedAppsResponse404 = {+ data: void;+ status: 404;+};++export type discoverConnectedAppsResponseSuccess =+ discoverConnectedAppsResponse200 & {+ headers: Headers;+ };+export type discoverConnectedAppsResponseError = (+ | discoverConnectedAppsResponse400+ | discoverConnectedAppsResponse403+ | discoverConnectedAppsResponse404+) & {+ headers: Headers;+};++export type discoverConnectedAppsResponse =+ | discoverConnectedAppsResponseSuccess+ | discoverConnectedAppsResponseError;++export const getDiscoverConnectedAppsUrl = (+ sessionId: string,+ executionId: string+) => {+ return `/agent-sessions/${sessionId}/code-executions/${executionId}/connected-apps/discover`;+};++export const discoverConnectedApps = async (+ sessionId: string,+ executionId: string,+ discoveryRequest: DiscoveryRequest,+ options?: RequestInit+): Promise<discoverConnectedAppsResponse> => {+ const res = await fetch(getDiscoverConnectedAppsUrl(sessionId, executionId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(discoveryRequest),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: discoverConnectedAppsResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as discoverConnectedAppsResponse;+};++/**+ * @summary Add a custom MCP server to the execution account's connections.+ */+export type addConnectedMcpServerResponse200 = {+ data: ConnectMcpServerResponse;+ status: 200;+};++export type addConnectedMcpServerResponse400 = {+ data: void;+ status: 400;+};++export type addConnectedMcpServerResponse403 = {+ data: void;+ status: 403;+};++export type addConnectedMcpServerResponse404 = {+ data: void;+ status: 404;+};++export type addConnectedMcpServerResponseSuccess =+ addConnectedMcpServerResponse200 & {+ headers: Headers;+ };+export type addConnectedMcpServerResponseError = (+ | addConnectedMcpServerResponse400+ | addConnectedMcpServerResponse403+ | addConnectedMcpServerResponse404+) & {+ headers: Headers;+};++export type addConnectedMcpServerResponse =+ | addConnectedMcpServerResponseSuccess+ | addConnectedMcpServerResponseError;++export const getAddConnectedMcpServerUrl = (+ sessionId: string,+ executionId: string+) => {+ return `/agent-sessions/${sessionId}/code-executions/${executionId}/connected-apps/servers`;+};++export const addConnectedMcpServer = async (+ sessionId: string,+ executionId: string,+ connectMcpServer: ConnectMcpServer,+ options?: RequestInit+): Promise<addConnectedMcpServerResponse> => {+ const res = await fetch(getAddConnectedMcpServerUrl(sessionId, executionId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(connectMcpServer),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: addConnectedMcpServerResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as addConnectedMcpServerResponse;+};++/**+ * @summary Find tools across the agent's connected apps by keywords.+ */+export type searchConnectedAppToolsResponse200 = {+ data: ConnectedToolSearch;+ status: 200;+};++export type searchConnectedAppToolsResponse403 = {+ data: void;+ status: 403;+};++export type searchConnectedAppToolsResponse404 = {+ data: void;+ status: 404;+};++export type searchConnectedAppToolsResponseSuccess =+ searchConnectedAppToolsResponse200 & {+ headers: Headers;+ };+export type searchConnectedAppToolsResponseError = (+ | searchConnectedAppToolsResponse403+ | searchConnectedAppToolsResponse404+) & {+ headers: Headers;+};++export type searchConnectedAppToolsResponse =+ | searchConnectedAppToolsResponseSuccess+ | searchConnectedAppToolsResponseError;++export const getSearchConnectedAppToolsUrl = (+ sessionId: string,+ executionId: string,+ params: SearchConnectedAppToolsParams+) => {+ const normalizedParams = new URLSearchParams();++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString());+ }+ });++ const stringifiedParams = normalizedParams.toString();++ return stringifiedParams.length > 0+ ? `/agent-sessions/${sessionId}/code-executions/${executionId}/connected-apps/tools?${stringifiedParams}`+ : `/agent-sessions/${sessionId}/code-executions/${executionId}/connected-apps/tools`;+};++export const searchConnectedAppTools = async (+ sessionId: string,+ executionId: string,+ params: SearchConnectedAppToolsParams,+ options?: RequestInit+): Promise<searchConnectedAppToolsResponse> => {+ const res = await fetch(+ getSearchConnectedAppToolsUrl(sessionId, executionId, params),+ {+ ...options,+ method: 'GET',+ }+ );++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: searchConnectedAppToolsResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as searchConnectedAppToolsResponse;+};++/**+ * @summary Call one tool of a connected app as the execution's account.+ */+export type callConnectedAppToolResponse200 = {+ data: ConnectedToolResult;+ status: 200;+};++export type callConnectedAppToolResponse400 = {+ data: void;+ status: 400;+};++export type callConnectedAppToolResponse403 = {+ data: void;+ status: 403;+};++export type callConnectedAppToolResponse404 = {+ data: void;+ status: 404;+};++export type callConnectedAppToolResponseSuccess =+ callConnectedAppToolResponse200 & {+ headers: Headers;+ };+export type callConnectedAppToolResponseError = (+ | callConnectedAppToolResponse400+ | callConnectedAppToolResponse403+ | callConnectedAppToolResponse404+) & {+ headers: Headers;+};++export type callConnectedAppToolResponse =+ | callConnectedAppToolResponseSuccess+ | callConnectedAppToolResponseError;++export const getCallConnectedAppToolUrl = (+ sessionId: string,+ executionId: string,+ kind: ConnectedAppKind,+ key: string+) => {+ return `/agent-sessions/${sessionId}/code-executions/${executionId}/connected-apps/${kind}/${key}/calls`;+};++export const callConnectedAppTool = async (+ sessionId: string,+ executionId: string,+ kind: ConnectedAppKind,+ key: string,+ callConnectedTool: CallConnectedTool,+ options?: RequestInit+): Promise<callConnectedAppToolResponse> => {+ const res = await fetch(+ getCallConnectedAppToolUrl(sessionId, executionId, kind, key),+ {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(callConnectedTool),+ }+ );++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: callConnectedAppToolResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as callConnectedAppToolResponse;+};++/**+ * @summary List the tools one connected app serves.+ */+export type listConnectedAppToolsResponse200 = {+ data: ConnectedTool[];+ status: 200;+};++export type listConnectedAppToolsResponse403 = {+ data: void;+ status: 403;+};++export type listConnectedAppToolsResponse404 = {+ data: void;+ status: 404;+};++export type listConnectedAppToolsResponseSuccess =+ listConnectedAppToolsResponse200 & {+ headers: Headers;+ };+export type listConnectedAppToolsResponseError = (+ | listConnectedAppToolsResponse403+ | listConnectedAppToolsResponse404+) & {+ headers: Headers;+};++export type listConnectedAppToolsResponse =+ | listConnectedAppToolsResponseSuccess+ | listConnectedAppToolsResponseError;++export const getListConnectedAppToolsUrl = (+ sessionId: string,+ executionId: string,+ kind: ConnectedAppKind,+ key: string+) => {+ return `/agent-sessions/${sessionId}/code-executions/${executionId}/connected-apps/${kind}/${key}/tools`;+};++export const listConnectedAppTools = async (+ sessionId: string,+ executionId: string,+ kind: ConnectedAppKind,+ key: string,+ options?: RequestInit+): Promise<listConnectedAppToolsResponse> => {+ const res = await fetch(+ getListConnectedAppToolsUrl(sessionId, executionId, kind, key),+ {+ ...options,+ method: 'GET',+ }+ );++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: listConnectedAppToolsResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as listConnectedAppToolsResponse;+};+/*** @summary List blocks created during an execution, including interrupted executions.*/diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/callConnectedTool.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/callConnectedTool.tsnew file mode 100644index 0000000000..3dff13a884--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/callConnectedTool.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { CallConnectedToolArguments } from './callConnectedToolArguments';++/**+ * Call one tool of a connected app.+ */+export interface CallConnectedTool {+ /** The tool's arguments, matching its input schema. */+ arguments?: CallConnectedToolArguments;+ /** The tool's name on its server. */+ tool: string;+}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/callConnectedToolArguments.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/callConnectedToolArguments.tsnew file mode 100644index 0000000000..9c1c9ce8ab--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/callConnectedToolArguments.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The tool's arguments, matching its input schema.+ */+export type CallConnectedToolArguments = { [key: string]: unknown };diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectMcpServer.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectMcpServer.tsnew file mode 100644index 0000000000..1920153df7--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectMcpServer.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Add a custom MCP server to the user's connections.+ */+export interface ConnectMcpServer {+ /** Display name for the server. */+ serverName: string;+ /** The server's URL. */+ url: string;+}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectMcpServerResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectMcpServerResponse.tsnew file mode 100644index 0000000000..0aa3b4dce1--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectMcpServerResponse.ts@@ -0,0 +1,24 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Response from [`ConnectMcpServer`].+ */+export interface ConnectMcpServerResponse {+ /** Whether the user already had this server before the call. */+ alreadyConnected: boolean;+ /** Whether the server holds the user's sign-in. */+ authenticated: boolean;+ /** Whether the server's tools are turned on. */+ enabled: boolean;+ /** The server's display name. */+ serverName: string;+ /** What happened and what the user still has to do. */+ summary: string;+ /** The server's URL. */+ url: string;+}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedApp.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedApp.tsnew file mode 100644index 0000000000..cf0116d26e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedApp.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { ConnectedAppKind } from './connectedAppKind';++/**+ * A connected app the session's agent may use.+ */+export interface ConnectedApp {+ /** The app's slug, or its custom server key. */+ key: string;+ /** Which store the app comes from. */+ kind: ConnectedAppKind;+ /** Display name, e.g. `Slack` or the owner's name for a custom server. */+ name: string;+}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedAppKind.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedAppKind.tsnew file mode 100644index 0000000000..d2f1033e2d--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedAppKind.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Which store a connected app comes from.+ */+export type ConnectedAppKind =+ (typeof ConnectedAppKind)[keyof typeof ConnectedAppKind];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const ConnectedAppKind = {+ app: 'app',+ custom: 'custom',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedTool.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedTool.tsnew file mode 100644index 0000000000..9ad0ae0852--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedTool.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { ConnectedToolDescription } from './connectedToolDescription';+import type { ConnectedToolInputSchema } from './connectedToolInputSchema';++/**+ * One tool a connected app serves.+ */+export interface ConnectedTool {+ /** What the server says the tool does. */+ description?: ConnectedToolDescription;+ /** JSON Schema for the tool's arguments. */+ inputSchema: ConnectedToolInputSchema;+ /** The tool's name on its server. */+ name: string;+}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolDescription.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolDescription.tsnew file mode 100644index 0000000000..e39bd0d94e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolDescription.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * What the server says the tool does.+ */+export type ConnectedToolDescription = string | null;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolInputSchema.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolInputSchema.tsnew file mode 100644index 0000000000..5950951f13--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolInputSchema.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * JSON Schema for the tool's arguments.+ */+export type ConnectedToolInputSchema = { [key: string]: unknown };diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolMatch.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolMatch.tsnew file mode 100644index 0000000000..bd77255dd1--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolMatch.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { ConnectedApp } from './connectedApp';+import type { ConnectedTool } from './connectedTool';++/**+ * One tool found by a search across the agent's connected apps.+ */+export interface ConnectedToolMatch {+ /** The app serving the tool. */+ app: ConnectedApp;+ /** The tool. */+ tool: ConnectedTool;+}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolResult.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolResult.tsnew file mode 100644index 0000000000..2ae64ad918--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolResult.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { ConnectedToolResultContentItem } from './connectedToolResultContentItem';+import type { ConnectedToolResultStructuredContent } from './connectedToolResultStructuredContent';++/**+ * A connected tool's answer: MCP's `CallToolResult`.+ */+export interface ConnectedToolResult {+ /** MCP content blocks, e.g. `{type: "text", text}`. */+ content: ConnectedToolResultContentItem[];+ /** The tool failed, or could not run; `content` says why. */+ isError: boolean;+ /** Structured output, for tools that declare an output schema. */+ structuredContent?: ConnectedToolResultStructuredContent;+}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolResultContentItem.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolResultContentItem.tsnew file mode 100644index 0000000000..44565df571--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolResultContentItem.ts@@ -0,0 +1,8 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type ConnectedToolResultContentItem = { [key: string]: unknown };diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolResultStructuredContent.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolResultStructuredContent.tsnew file mode 100644index 0000000000..477022cd36--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolResultStructuredContent.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { ConnectedToolResultStructuredContentAnyOf } from './connectedToolResultStructuredContentAnyOf';++/**+ * Structured output, for tools that declare an output schema.+ */+export type ConnectedToolResultStructuredContent =+ ConnectedToolResultStructuredContentAnyOf | null;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolResultStructuredContentAnyOf.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolResultStructuredContentAnyOf.tsnew file mode 100644index 0000000000..4a22287a88--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolResultStructuredContentAnyOf.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Structured output, for tools that declare an output schema.+ */+export type ConnectedToolResultStructuredContentAnyOf = {+ [key: string]: unknown;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolSearch.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolSearch.tsnew file mode 100644index 0000000000..31ac8bf98e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectedToolSearch.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++import type { ConnectedApp } from './connectedApp';+import type { ConnectedToolMatch } from './connectedToolMatch';++/**+ * The best matches across the agent's connected apps, and the apps whose+tools could not be listed, which the search did not cover.+ */+export interface ConnectedToolSearch {+ /** At most [`MAX_TOOL_MATCHES`] tools, best first. */+ matches: ConnectedToolMatch[];+ /** Apps whose tools could not be listed. */+ unsearched: ConnectedApp[];+}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectorTool.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectorTool.tsnew file mode 100644index 0000000000..68ccd66af5--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/connectorTool.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * An advertised action, not a tool loaded into the current turn.+ */+export interface ConnectorTool {+ /** What the action supports. */+ description: string;+ /** Upstream tool name. */+ name: string;+}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoverConnectorsResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoverConnectorsResponse.tsnew file mode 100644index 0000000000..1c0aed7892--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoverConnectorsResponse.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { DiscoverConnectorsResponseConnectMarkup } from './discoverConnectorsResponseConnectMarkup';+import type { DiscoveryResult } from './discoveryResult';++/**+ * Discovery metadata and optional markup for a user-controlled auth flow.+ */+export interface DiscoverConnectorsResponse {+ /** Include verbatim only if an advertised tool supports the requested task. */+ connect_markup?: DiscoverConnectorsResponseConnectMarkup;+ /** Catalog or capability results. */+ result: DiscoveryResult;+}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoverConnectorsResponseConnectMarkup.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoverConnectorsResponseConnectMarkup.tsnew file mode 100644index 0000000000..b4926f31e9--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoverConnectorsResponseConnectMarkup.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Include verbatim only if an advertised tool supports the requested task.+ */+export type DiscoverConnectorsResponseConnectMarkup = string | null;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveredApp.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveredApp.tsnew file mode 100644index 0000000000..dbf8115a47--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveredApp.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { DiscoveredAppDescription } from './discoveredAppDescription';++/**+ * A verified app identity from the directory.+ */+export interface DiscoveredApp {+ /** Exact identity to inspect or connect. */+ app_slug: string;+ /** Directory description; inspect tools to verify specific capabilities. */+ description?: DiscoveredAppDescription;+ /** Human-readable app name. */+ name: string;+}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveredAppDescription.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveredAppDescription.tsnew file mode 100644index 0000000000..d1496e1fa7--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveredAppDescription.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Directory description; inspect tools to verify specific capabilities.+ */+export type DiscoveredAppDescription = string | null;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryRequest.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryRequest.tsnew file mode 100644index 0000000000..9fa32a6ef9--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryRequest.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { DiscoveryRequestOneOf } from './discoveryRequestOneOf';+import type { DiscoveryRequestOneOfThree } from './discoveryRequestOneOfThree';++/**+ * Search by app name, then inspect a returned slug before recommending auth.+ */+export type DiscoveryRequest =+ | DiscoveryRequestOneOf+ | DiscoveryRequestOneOfThree;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryRequestOneOf.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryRequestOneOf.tsnew file mode 100644index 0000000000..b36906459f--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryRequestOneOf.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { DiscoveryRequestOneOfOperation } from './discoveryRequestOneOfOperation';++/**+ * Find connectable apps by name.+ */+export type DiscoveryRequestOneOf = {+ operation: DiscoveryRequestOneOfOperation;+ /** App name, e.g. "Notion" or "Linear", not a task description. */+ query: string;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryRequestOneOfOperation.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryRequestOneOfOperation.tsnew file mode 100644index 0000000000..947386c993--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryRequestOneOfOperation.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type DiscoveryRequestOneOfOperation =+ (typeof DiscoveryRequestOneOfOperation)[keyof typeof DiscoveryRequestOneOfOperation];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const DiscoveryRequestOneOfOperation = {+ search: 'search',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryRequestOneOfThree.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryRequestOneOfThree.tsnew file mode 100644index 0000000000..117fde6b37--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryRequestOneOfThree.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { DiscoveryRequestOneOfThreeOperation } from './discoveryRequestOneOfThreeOperation';++/**+ * Verify capabilities and connection status for one catalog app.+ */+export type DiscoveryRequestOneOfThree = {+ /** Exact app slug from search results. */+ app_slug: string;+ operation: DiscoveryRequestOneOfThreeOperation;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryRequestOneOfThreeOperation.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryRequestOneOfThreeOperation.tsnew file mode 100644index 0000000000..f9c33651fe--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryRequestOneOfThreeOperation.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type DiscoveryRequestOneOfThreeOperation =+ (typeof DiscoveryRequestOneOfThreeOperation)[keyof typeof DiscoveryRequestOneOfThreeOperation];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const DiscoveryRequestOneOfThreeOperation = {+ inspect: 'inspect',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryResult.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryResult.tsnew file mode 100644index 0000000000..a1aef3384f--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryResult.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { DiscoveryResultOneOf } from './discoveryResultOneOf';+import type { DiscoveryResultOneOfThree } from './discoveryResultOneOfThree';++/**+ * Discovery results never execute tools or change connections.+ */+export type DiscoveryResult = DiscoveryResultOneOf | DiscoveryResultOneOfThree;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryResultOneOf.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryResultOneOf.tsnew file mode 100644index 0000000000..231b8de806--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryResultOneOf.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { DiscoveredApp } from './discoveredApp';+import type { DiscoveryResultOneOfOperation } from './discoveryResultOneOfOperation';++/**+ * Candidate apps; none has had its capabilities verified yet.+ */+export type DiscoveryResultOneOf = {+ /** Matching apps. */+ apps: DiscoveredApp[];+ /** Narrow the app name if this is true. */+ more_results: boolean;+ operation: DiscoveryResultOneOfOperation;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryResultOneOfOperation.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryResultOneOfOperation.tsnew file mode 100644index 0000000000..b9e43f9135--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryResultOneOfOperation.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type DiscoveryResultOneOfOperation =+ (typeof DiscoveryResultOneOfOperation)[keyof typeof DiscoveryResultOneOfOperation];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const DiscoveryResultOneOfOperation = {+ search: 'search',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryResultOneOfThree.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryResultOneOfThree.tsnew file mode 100644index 0000000000..2754e14619--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryResultOneOfThree.ts@@ -0,0 +1,27 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++import type { ConnectorTool } from './connectorTool';+import type { DiscoveredApp } from './discoveredApp';+import type { DiscoveryResultOneOfThreeOperation } from './discoveryResultOneOfThreeOperation';++/**+ * Verified identity, capabilities and this caller's connection status.+ */+export type DiscoveryResultOneOfThree = {+ /** App from the directory. */+ app: DiscoveredApp;+ /** Whether this caller has an enabled connection. For an app that+connects through its own MCP server, that connection is checked+there, not in Pipedream. */+ connected: boolean;+ operation: DiscoveryResultOneOfThreeOperation;+ /** Advertised tools. Use SearchTools after connecting to load them. */+ tools: ConnectorTool[];+ /** True when some advertised tools were omitted. */+ tools_truncated: boolean;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryResultOneOfThreeOperation.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryResultOneOfThreeOperation.tsnew file mode 100644index 0000000000..82e7fa0761--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/discoveryResultOneOfThreeOperation.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type DiscoveryResultOneOfThreeOperation =+ (typeof DiscoveryResultOneOfThreeOperation)[keyof typeof DiscoveryResultOneOfThreeOperation];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const DiscoveryResultOneOfThreeOperation = {+ inspect: 'inspect',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.tsindex df17a98710..185071a11c 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts@@ -119,6 +119,8 @@ export * from './calendarSuggestionsRecurrence';export * from './calendarSuggestionsStart';export * from './calendarSuggestionsStartAssumption';export * from './calendarSuggestionsTitle';+export * from './callConnectedTool';+export * from './callConnectedToolArguments';export * from './callSearchSuggestions';export * from './callSearchSuggestionsQuery';export * from './callSearchSuggestionsStatus';@@ -139,6 +141,20 @@ export * from './channelSharePermission';export * from './classifyInputRequest';export * from './classifyInputResponse';export * from './codingPreferencesBody';+export * from './connectedApp';+export * from './connectedAppKind';+export * from './connectedTool';+export * from './connectedToolDescription';+export * from './connectedToolInputSchema';+export * from './connectedToolMatch';+export * from './connectedToolResult';+export * from './connectedToolResultContentItem';+export * from './connectedToolResultStructuredContent';+export * from './connectedToolResultStructuredContentAnyOf';+export * from './connectedToolSearch';+export * from './connectMcpServer';+export * from './connectMcpServerResponse';+export * from './connectorTool';export * from './controlRequest';export * from './controlRequestAllOf';export * from './controlRequestAllOfActionId';@@ -173,6 +189,20 @@ export * from './discoverAgentCapabilitiesRequest';export * from './discoverAgentCapabilitiesRequestHarnessId';export * from './discoverAgentCapabilitiesRequestModel';export * from './discoverAgentCapabilitiesResponse';+export * from './discoverConnectorsResponse';+export * from './discoverConnectorsResponseConnectMarkup';+export * from './discoveredApp';+export * from './discoveredAppDescription';+export * from './discoveryRequest';+export * from './discoveryRequestOneOf';+export * from './discoveryRequestOneOfOperation';+export * from './discoveryRequestOneOfThree';+export * from './discoveryRequestOneOfThreeOperation';+export * from './discoveryResult';+export * from './discoveryResultOneOf';+export * from './discoveryResultOneOfOperation';+export * from './discoveryResultOneOfThree';+export * from './discoveryResultOneOfThreeOperation';export * from './documentId';export * from './editQueuedActionRequest';export * from './elicitationAnswer';@@ -318,6 +348,7 @@ export * from './reviewRecordAllOfTwoExecutionId';export * from './reviewRecordAllOfTwoPresentedAt';export * from './sandboxSize';export * from './sandboxSizeBody';+export * from './searchConnectedAppToolsParams';export * from './searchSuggestions';export * from './searchSuggestionsOneOf';export * from './searchSuggestionsOneOfAllOf';diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/searchConnectedAppToolsParams.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/searchConnectedAppToolsParams.tsnew file mode 100644index 0000000000..68e5adaad0--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/searchConnectedAppToolsParams.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type SearchConnectedAppToolsParams = {+ /**+ * Keywords matched against tool names and descriptions, e.g. `linear issue`.+ */+ query: string;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.jsonindex 3ef8436dce..c707c9a5ff 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json+++ b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json@@ -1626,6 +1626,365 @@}}},+ "/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps": {+ "get": {+ "tags": ["agent-sessions"],+ "summary": "List the connected apps and custom MCP servers the session's agent may use.",+ "operationId": "list_execution_connected_apps",+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "execution_id",+ "in": "path",+ "description": "A running execution of the session's current turn",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ConnectedApp"+ }+ }+ }+ }+ },+ "403": {+ "description": ""+ },+ "404": {+ "description": ""+ }+ }+ }+ },+ "/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/discover": {+ "post": {+ "tags": ["agent-sessions"],+ "summary": "Search the connectable app catalog, or inspect one app's tools and connection status.",+ "operationId": "discover_connected_apps",+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "execution_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/DiscoveryRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/DiscoverConnectorsResponse"+ }+ }+ }+ },+ "400": {+ "description": ""+ },+ "403": {+ "description": ""+ },+ "404": {+ "description": ""+ }+ }+ }+ },+ "/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/servers": {+ "post": {+ "tags": ["agent-sessions"],+ "summary": "Add a custom MCP server to the execution account's connections.",+ "operationId": "add_connected_mcp_server",+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "execution_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ConnectMcpServer"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ConnectMcpServerResponse"+ }+ }+ }+ },+ "400": {+ "description": ""+ },+ "403": {+ "description": ""+ },+ "404": {+ "description": ""+ }+ }+ }+ },+ "/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/tools": {+ "get": {+ "tags": ["agent-sessions"],+ "summary": "Find tools across the agent's connected apps by keywords.",+ "operationId": "search_connected_app_tools",+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "execution_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "query",+ "in": "query",+ "description": "Keywords matched against tool names and descriptions, e.g. `linear issue`.",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ConnectedToolSearch"+ }+ }+ }+ },+ "403": {+ "description": ""+ },+ "404": {+ "description": ""+ }+ }+ }+ },+ "/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/{kind}/{key}/calls": {+ "post": {+ "tags": ["agent-sessions"],+ "summary": "Call one tool of a connected app as the execution's account.",+ "operationId": "call_connected_app_tool",+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "execution_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "kind",+ "in": "path",+ "required": true,+ "schema": {+ "$ref": "#/components/schemas/ConnectedAppKind"+ }+ },+ {+ "name": "key",+ "in": "path",+ "description": "The app's slug or custom server key",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CallConnectedTool"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ConnectedToolResult"+ }+ }+ }+ },+ "400": {+ "description": ""+ },+ "403": {+ "description": ""+ },+ "404": {+ "description": ""+ }+ }+ }+ },+ "/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/{kind}/{key}/tools": {+ "get": {+ "tags": ["agent-sessions"],+ "summary": "List the tools one connected app serves.",+ "operationId": "list_connected_app_tools",+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "execution_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "kind",+ "in": "path",+ "required": true,+ "schema": {+ "$ref": "#/components/schemas/ConnectedAppKind"+ }+ },+ {+ "name": "key",+ "in": "path",+ "description": "The app's slug or custom server key",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ConnectedTool"+ }+ }+ }+ }+ },+ "403": {+ "description": ""+ },+ "404": {+ "description": ""+ }+ }+ }+ },"/agent-sessions/{session_id}/code-executions/{execution_id}/reviews": {"get": {"tags": ["agent-sessions"],@@ -4153,6 +4512,22 @@},"additionalProperties": false},+ "CallConnectedTool": {+ "type": "object",+ "description": "Call one tool of a connected app.",+ "required": ["tool"],+ "properties": {+ "arguments": {+ "type": "object",+ "description": "The tool's arguments, matching its input schema."+ },+ "tool": {+ "type": "string",+ "description": "The tool's name on its server."+ }+ },+ "additionalProperties": false+ },"CallSearchSuggestions": {"type": "object","description": "Call search supports speakers, channels and attendance status.",@@ -4442,6 +4817,175 @@}}},+ "ConnectMcpServer": {+ "type": "object",+ "description": "Add a custom MCP server to the user's connections.",+ "required": ["url", "serverName"],+ "properties": {+ "serverName": {+ "type": "string",+ "description": "Display name for the server."+ },+ "url": {+ "type": "string",+ "description": "The server's URL."+ }+ }+ },+ "ConnectMcpServerResponse": {+ "type": "object",+ "description": "Response from [`ConnectMcpServer`].",+ "required": [+ "url",+ "serverName",+ "alreadyConnected",+ "authenticated",+ "enabled",+ "summary"+ ],+ "properties": {+ "alreadyConnected": {+ "type": "boolean",+ "description": "Whether the user already had this server before the call."+ },+ "authenticated": {+ "type": "boolean",+ "description": "Whether the server holds the user's sign-in."+ },+ "enabled": {+ "type": "boolean",+ "description": "Whether the server's tools are turned on."+ },+ "serverName": {+ "type": "string",+ "description": "The server's display name."+ },+ "summary": {+ "type": "string",+ "description": "What happened and what the user still has to do."+ },+ "url": {+ "type": "string",+ "description": "The server's URL."+ }+ }+ },+ "ConnectedApp": {+ "type": "object",+ "description": "A connected app the session's agent may use.",+ "required": ["kind", "key", "name"],+ "properties": {+ "key": {+ "type": "string",+ "description": "The app's slug, or its custom server key."+ },+ "kind": {+ "$ref": "#/components/schemas/ConnectedAppKind",+ "description": "Which store the app comes from."+ },+ "name": {+ "type": "string",+ "description": "Display name, e.g. `Slack` or the owner's name for a custom server."+ }+ }+ },+ "ConnectedAppKind": {+ "type": "string",+ "description": "Which store a connected app comes from.",+ "enum": ["app", "custom"]+ },+ "ConnectedTool": {+ "type": "object",+ "description": "One tool a connected app serves.",+ "required": ["name", "inputSchema"],+ "properties": {+ "description": {+ "type": ["string", "null"],+ "description": "What the server says the tool does."+ },+ "inputSchema": {+ "type": "object",+ "description": "JSON Schema for the tool's arguments."+ },+ "name": {+ "type": "string",+ "description": "The tool's name on its server."+ }+ }+ },+ "ConnectedToolMatch": {+ "type": "object",+ "description": "One tool found by a search across the agent's connected apps.",+ "required": ["app", "tool"],+ "properties": {+ "app": {+ "$ref": "#/components/schemas/ConnectedApp",+ "description": "The app serving the tool."+ },+ "tool": {+ "$ref": "#/components/schemas/ConnectedTool",+ "description": "The tool."+ }+ }+ },+ "ConnectedToolResult": {+ "type": "object",+ "description": "A connected tool's answer: MCP's `CallToolResult`.",+ "required": ["isError", "content"],+ "properties": {+ "content": {+ "type": "array",+ "items": {+ "type": "object"+ },+ "description": "MCP content blocks, e.g. `{type: \"text\", text}`."+ },+ "isError": {+ "type": "boolean",+ "description": "The tool failed, or could not run; `content` says why."+ },+ "structuredContent": {+ "type": ["object", "null"],+ "description": "Structured output, for tools that declare an output schema."+ }+ }+ },+ "ConnectedToolSearch": {+ "type": "object",+ "description": "The best matches across the agent's connected apps, and the apps whose\ntools could not be listed, which the search did not cover.",+ "required": ["matches", "unsearched"],+ "properties": {+ "matches": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ConnectedToolMatch"+ },+ "description": "At most [`MAX_TOOL_MATCHES`] tools, best first."+ },+ "unsearched": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ConnectedApp"+ },+ "description": "Apps whose tools could not be listed."+ }+ }+ },+ "ConnectorTool": {+ "type": "object",+ "description": "An advertised action, not a tool loaded into the current turn.",+ "required": ["name", "description"],+ "properties": {+ "description": {+ "type": "string",+ "description": "What the action supports."+ },+ "name": {+ "type": "string",+ "description": "Upstream tool name."+ }+ }+ },"ControlRequest": {"allOf": [{@@ -4697,6 +5241,138 @@}}},+ "DiscoverConnectorsResponse": {+ "type": "object",+ "description": "Discovery metadata and optional markup for a user-controlled auth flow.",+ "required": ["result"],+ "properties": {+ "connect_markup": {+ "type": ["string", "null"],+ "description": "Include verbatim only if an advertised tool supports the requested task."+ },+ "result": {+ "$ref": "#/components/schemas/DiscoveryResult",+ "description": "Catalog or capability results."+ }+ }+ },+ "DiscoveredApp": {+ "type": "object",+ "description": "A verified app identity from the directory.",+ "required": ["app_slug", "name"],+ "properties": {+ "app_slug": {+ "type": "string",+ "description": "Exact identity to inspect or connect."+ },+ "description": {+ "type": ["string", "null"],+ "description": "Directory description; inspect tools to verify specific capabilities."+ },+ "name": {+ "type": "string",+ "description": "Human-readable app name."+ }+ }+ },+ "DiscoveryRequest": {+ "oneOf": [+ {+ "type": "object",+ "description": "Find connectable apps by name.",+ "required": ["query", "operation"],+ "properties": {+ "operation": {+ "type": "string",+ "enum": ["search"]+ },+ "query": {+ "type": "string",+ "description": "App name, e.g. \"Notion\" or \"Linear\", not a task description."+ }+ }+ },+ {+ "type": "object",+ "description": "Verify capabilities and connection status for one catalog app.",+ "required": ["app_slug", "operation"],+ "properties": {+ "app_slug": {+ "type": "string",+ "description": "Exact app slug from search results."+ },+ "operation": {+ "type": "string",+ "enum": ["inspect"]+ }+ }+ }+ ],+ "description": "Search by app name, then inspect a returned slug before recommending auth."+ },+ "DiscoveryResult": {+ "oneOf": [+ {+ "type": "object",+ "description": "Candidate apps; none has had its capabilities verified yet.",+ "required": ["apps", "more_results", "operation"],+ "properties": {+ "apps": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/DiscoveredApp"+ },+ "description": "Matching apps."+ },+ "more_results": {+ "type": "boolean",+ "description": "Narrow the app name if this is true."+ },+ "operation": {+ "type": "string",+ "enum": ["search"]+ }+ }+ },+ {+ "type": "object",+ "description": "Verified identity, capabilities and this caller's connection status.",+ "required": [+ "app",+ "connected",+ "tools",+ "tools_truncated",+ "operation"+ ],+ "properties": {+ "app": {+ "$ref": "#/components/schemas/DiscoveredApp",+ "description": "App from the directory."+ },+ "connected": {+ "type": "boolean",+ "description": "Whether this caller has an enabled connection. For an app that\nconnects through its own MCP server, that connection is checked\nthere, not in Pipedream."+ },+ "operation": {+ "type": "string",+ "enum": ["inspect"]+ },+ "tools": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ConnectorTool"+ },+ "description": "Advertised tools. Use SearchTools after connecting to load them."+ },+ "tools_truncated": {+ "type": "boolean",+ "description": "True when some advertised tools were omitted."+ }+ }+ }+ ],+ "description": "Discovery results never execute tools or change connections."+ },"DocumentId": {"type": "string","description": "A validated document identifier. Historical document ids need not be UUIDs."diff --git a/crates/agent_code_mode/AGENTS.md b/crates/agent_code_mode/AGENTS.mdindex 4233974ec6..5022c29118 100644--- a/crates/agent_code_mode/AGENTS.md+++ b/crates/agent_code_mode/AGENTS.md@@ -42,6 +42,18 @@ stacks. Process isolation belongs toand streams it as a completed `PresentView` call (`view_<id>`) through`ReviewActions::present_view`. There is no `PresentView` tool: ExecuteCode'sdescription carries the view schema and when to present one.+- `src/domain/connected_apps.rs`: a running execution's connected apps+ (`macro.connectedApps`). `GET|POST /agent-sessions/{id}/code-executions/{execution}/connected-apps…`+ admits only a running execution of the session's current turn, called by+ the account that execution was approved to act as; the harness adapter+ (`agent_harness_service/src/code_mode/connected_apps.rs`) lists the apps the+ session's agent was given (`EgressProvisioner::advertised_all`) and calls+ them through `agent_egress`'s `SessionMcpExchange`, so credentials never+ reach the sandbox. In a turn someone other than the owner prompted, each+ call spending the owner's access is held for the owner's approval+ (`OwnerApprovals::hold_in_process`), like a direct MCP call. `discover`+ and `servers` serve `DiscoverConnectors` and `ConnectMcpServer` through+ the native tool gate, so both tools are in `covered_by_code_sdk`.- `src/domain/documentation.rs`: the build-time SDK catalog (per entity a`@routing` description, an `@agent` guide and an index; a reference persymbol). Jev ranks entities on their descriptions (32 per call, at most 8diff --git a/crates/agent_code_mode/Cargo.toml b/crates/agent_code_mode/Cargo.tomlindex cf98240a24..6466d9b29f 100644--- a/crates/agent_code_mode/Cargo.toml+++ b/crates/agent_code_mode/Cargo.toml@@ -24,8 +24,10 @@ futures = { workspace = true }import = { path = "../import" }macro_authorization = { path = "../macro_authorization", default-features = false, features = ["axum"] }macro_user_id = { path = "../macro_user_id" }+mcp_client = { path = "../mcp_client" }macro_uuid = { path = "../macro_uuid" }nutype = { workspace = true }+pipedream_mcp = { path = "../pipedream_mcp" }rootcause = { workspace = true }schemars = { workspace = true }serde = { workspace = true }diff --git a/crates/agent_code_mode/src/domain.rs b/crates/agent_code_mode/src/domain.rsindex a5e8a18967..9165dc114b 100644--- a/crates/agent_code_mode/src/domain.rs+++ b/crates/agent_code_mode/src/domain.rs@@ -16,3 +16,5 @@ mod activity;mod user;pub use user::*;++pub mod connected_apps;diff --git a/crates/agent_code_mode/src/domain/connected_apps.rs b/crates/agent_code_mode/src/domain/connected_apps.rsnew file mode 100644index 0000000000..311344b1b8--- /dev/null+++ b/crates/agent_code_mode/src/domain/connected_apps.rs@@ -0,0 +1,351 @@+//! A running execution's route to the session agent's connected apps.+//!+//! A program reaches the same apps and custom MCP servers the session's+//! agent was given, through the harness's credential-stamping egress: the+//! sandbox never sees a token. The program spends the one account its+//! execution was approved for, and only while that execution runs in the+//! turn it was started for.++use agent_session::domain::model::AgentSessionId;+use ai_toolset::actor::ToolActor;+use async_trait::async_trait;+use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt};+use macro_user_id::user_id::MacroUserIdStr;+use mcp_client::inbound::toolset::{ConnectMcpServer, ConnectMcpServerResponse};+use pipedream_mcp::domain::service::discovery::DiscoveryRequest;+use pipedream_mcp::inbound::toolset::DiscoverConnectorsResponse;+use serde::{Deserialize, Serialize};+use std::sync::Arc;+use utoipa::ToSchema;++use super::{CodeModeError, ExecutionId, ExecutionStatus, ExecutionStore, ExecutionTurns};++#[cfg(test)]+mod test;++/// Which store a connected app comes from.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub enum ConnectedAppKind {+ /// An app connected through Macro Connect or Pipedream, keyed by its slug.+ App,+ /// A custom MCP server the owner added by URL, keyed by a digest of the URL.+ Custom,+}++/// Names one connected app: the key is its slug or its URL digest.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct ConnectedAppRef {+ /// Which store the app comes from.+ pub kind: ConnectedAppKind,+ /// The app's slug, or its custom server key.+ pub key: String,+}++/// A connected app the session's agent may use.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct ConnectedApp {+ /// Which store the app comes from.+ pub kind: ConnectedAppKind,+ /// The app's slug, or its custom server key.+ pub key: String,+ /// Display name, e.g. `Slack` or the owner's name for a custom server.+ pub name: String,+}++/// One tool a connected app serves.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct ConnectedTool {+ /// The tool's name on its server.+ pub name: String,+ /// What the server says the tool does.+ pub description: Option<String>,+ /// JSON Schema for the tool's arguments.+ #[schema(value_type = Object)]+ pub input_schema: serde_json::Value,+}++/// One tool found by a search across the agent's connected apps.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct ConnectedToolMatch {+ /// The app serving the tool.+ pub app: ConnectedApp,+ /// The tool.+ pub tool: ConnectedTool,+}++/// The best matches across the agent's connected apps, and the apps whose+/// tools could not be listed, which the search did not cover.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct ConnectedToolSearch {+ /// At most [`MAX_TOOL_MATCHES`] tools, best first.+ pub matches: Vec<ConnectedToolMatch>,+ /// Apps whose tools could not be listed.+ pub unsearched: Vec<ConnectedApp>,+}++/// Most tools one search returns.+pub const MAX_TOOL_MATCHES: usize = 20;++/// Call one tool of a connected app.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct CallConnectedTool {+ /// The tool's name on its server.+ pub tool: String,+ /// The tool's arguments, matching its input schema.+ #[serde(default)]+ #[schema(value_type = Object)]+ pub arguments: serde_json::Map<String, serde_json::Value>,+}++/// A connected tool's answer: MCP's `CallToolResult`.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct ConnectedToolResult {+ /// The tool failed, or could not run; `content` says why.+ pub is_error: bool,+ /// MCP content blocks, e.g. `{type: "text", text}`.+ #[schema(value_type = Vec<Object>)]+ pub content: Vec<serde_json::Value>,+ /// Structured output, for tools that declare an output schema.+ #[schema(value_type = Option<Object>)]+ pub structured_content: Option<serde_json::Value>,+}++/// The accounts a session's turn can act as.+#[derive(Clone, Debug)]+pub struct SessionAccounts {+ /// The session owner.+ pub owner: MacroUserIdStr<'static>,+ /// The person behind the running turn; `None` for a system turn.+ pub requester: Option<MacroUserIdStr<'static>>,+}++/// A running execution's admitted use: the account its calls spend.+#[derive(Clone, Debug)]+pub struct ConnectedAppUse {+ /// The execution's session.+ pub session: AgentSessionId,+ /// The account choice the execution was approved for.+ pub acting_as: ToolActor,+ /// That choice resolved against the current turn.+ pub user: MacroUserIdStr<'static>,+}++/// The session agent's connected apps, reached through the harness egress.+#[async_trait]+pub trait ConnectedAppTools: Send + Sync + 'static {+ /// The accounts the session's current turn can act as.+ async fn accounts(&self, session: AgentSessionId) -> Result<SessionAccounts, CodeModeError>;+ /// The apps the session's agent was given, without contacting any of them.+ async fn apps(&self, usage: &ConnectedAppUse) -> Result<Vec<ConnectedApp>, CodeModeError>;+ /// The tools `app` serves.+ async fn tools(+ &self,+ usage: &ConnectedAppUse,+ app: &ConnectedAppRef,+ ) -> Result<Vec<ConnectedTool>, CodeModeError>;+ /// Call one of `app`'s tools as the execution's account. In a turn+ /// somebody other than the owner prompted, a call spending the owner's+ /// access waits for the owner to approve it.+ async fn call(+ &self,+ usage: &ConnectedAppUse,+ app: &ConnectedAppRef,+ call: CallConnectedTool,+ ) -> Result<ConnectedToolResult, CodeModeError>;+ /// Search the connectable app catalog, or inspect one app's tools and+ /// connection status: what the `DiscoverConnectors` tool does.+ async fn discover(+ &self,+ usage: &ConnectedAppUse,+ request: DiscoveryRequest,+ ) -> Result<DiscoverConnectorsResponse, CodeModeError>;+ /// Add a custom MCP server to the account's connections: what the+ /// `ConnectMcpServer` tool does.+ async fn add_server(+ &self,+ usage: &ConnectedAppUse,+ server: ConnectMcpServer,+ ) -> Result<ConnectMcpServerResponse, CodeModeError>;+}++/// Admits a running execution's connected-app requests.+#[derive(Clone)]+pub struct ConnectedAppService {+ store: Arc<dyn ExecutionStore>,+ turns: Arc<dyn ExecutionTurns>,+ tools: Arc<dyn ConnectedAppTools>,+}++impl ConnectedAppService {+ /// Bind the execution records, shared turn state and the egress adapter.+ pub fn new(+ store: Arc<dyn ExecutionStore>,+ turns: Arc<dyn ExecutionTurns>,+ tools: Arc<dyn ConnectedAppTools>,+ ) -> Self {+ Self {+ store,+ turns,+ tools,+ }+ }++ /// Admit only a running execution of the session's current turn, so a+ /// finished program, a replayed one or another turn cannot spend it, and+ /// only a caller holding the account that execution was approved to act+ /// as: its credential names that account, and nobody else's may spend it.+ async fn admit(+ &self,+ access: &EntityAccessReceipt<EditAccessLevel>,+ caller: &MacroUserIdStr<'static>,+ execution: ExecutionId,+ ) -> Result<ConnectedAppUse, CodeModeError> {+ let session =+ super::reviews::session_id(access.entity().entity_type, &access.entity().entity_id)?;+ if access.acting_user_id() != Some(caller) {+ return Err(CodeModeError::Forbidden);+ }+ let record = self.store.get(session, execution).await?;+ let active = self.turns.active(session).await?;+ let (Some(acting_as), Some(turn)) = (record.acting_as, record.turn_id) else {+ return Err(CodeModeError::Forbidden);+ };+ if record.status != ExecutionStatus::Running || active != Some(turn) {+ return Err(CodeModeError::Forbidden);+ }++ let accounts = self.tools.accounts(session).await?;+ let user = acting_as+ .resolve(&accounts.owner, accounts.requester.as_ref())+ .map_err(|_| CodeModeError::Forbidden)?;+ if user != caller {+ return Err(CodeModeError::Forbidden);+ }+ Ok(ConnectedAppUse {+ session,+ acting_as,+ user: caller.clone(),+ })+ }++ /// The apps the session's agent was given.+ pub async fn apps(+ &self,+ access: &EntityAccessReceipt<EditAccessLevel>,+ caller: &MacroUserIdStr<'static>,+ execution: ExecutionId,+ ) -> Result<Vec<ConnectedApp>, CodeModeError> {+ let usage = self.admit(access, caller, execution).await?;+ self.tools.apps(&usage).await+ }++ /// The tools one of those apps serves.+ pub async fn tools(+ &self,+ access: &EntityAccessReceipt<EditAccessLevel>,+ caller: &MacroUserIdStr<'static>,+ execution: ExecutionId,+ app: ConnectedAppRef,+ ) -> Result<Vec<ConnectedTool>, CodeModeError> {+ let usage = self.admit(access, caller, execution).await?;+ self.tools.tools(&usage, &app).await+ }++ /// Call one of an app's tools.+ pub async fn call(+ &self,+ access: &EntityAccessReceipt<EditAccessLevel>,+ caller: &MacroUserIdStr<'static>,+ execution: ExecutionId,+ app: ConnectedAppRef,+ call: CallConnectedTool,+ ) -> Result<ConnectedToolResult, CodeModeError> {+ let usage = self.admit(access, caller, execution).await?;+ self.tools.call(&usage, &app, call).await+ }++ /// Search or inspect connectable apps.+ pub async fn discover(+ &self,+ access: &EntityAccessReceipt<EditAccessLevel>,+ caller: &MacroUserIdStr<'static>,+ execution: ExecutionId,+ request: DiscoveryRequest,+ ) -> Result<DiscoverConnectorsResponse, CodeModeError> {+ let usage = self.admit(access, caller, execution).await?;+ self.tools.discover(&usage, request).await+ }++ /// Add a custom MCP server to the account's connections.+ pub async fn add_server(+ &self,+ access: &EntityAccessReceipt<EditAccessLevel>,+ caller: &MacroUserIdStr<'static>,+ execution: ExecutionId,+ server: ConnectMcpServer,+ ) -> Result<ConnectMcpServerResponse, CodeModeError> {+ let usage = self.admit(access, caller, execution).await?;+ self.tools.add_server(&usage, server).await+ }++ /// Find tools across every app the agent was given by keywords matched+ /// against tool names and descriptions, ranked the way `SearchTools`+ /// ranks: by how many terms match. An app whose tools cannot be listed+ /// is reported, not fatal.+ pub async fn search_tools(+ &self,+ access: &EntityAccessReceipt<EditAccessLevel>,+ caller: &MacroUserIdStr<'static>,+ execution: ExecutionId,+ query: &str,+ ) -> Result<ConnectedToolSearch, CodeModeError> {+ let usage = self.admit(access, caller, execution).await?;+ let apps = self.tools.apps(&usage).await?;+ let listings = futures::future::join_all(apps.iter().map(|app| {+ let reference = ConnectedAppRef {+ kind: app.kind,+ key: app.key.clone(),+ };+ let usage = &usage;+ async move { self.tools.tools(usage, &reference).await }+ }))+ .await;++ let mut catalog = Vec::new();+ let mut unsearched = Vec::new();+ for (app, listing) in apps.into_iter().zip(listings) {+ match listing {+ Ok(tools) => catalog.extend(tools.into_iter().map(|tool| ConnectedToolMatch {+ app: app.clone(),+ tool,+ })),+ Err(error) => {+ tracing::warn!(?error, app = %app.key, "could not list a connected app's tools");+ unsearched.push(app);+ }+ }+ }+ let matches = ai_toolset::tool_search::rank(&catalog, query, |found| {+ (+ found.tool.name.as_str(),+ found.tool.description.as_deref().unwrap_or_default(),+ )+ })+ .into_iter()+ .take(MAX_TOOL_MATCHES)+ .cloned()+ .collect();+ Ok(ConnectedToolSearch {+ matches,+ unsearched,+ })+ }+}diff --git a/crates/agent_code_mode/src/domain/connected_apps/test.rs b/crates/agent_code_mode/src/domain/connected_apps/test.rsnew file mode 100644index 0000000000..bd4d7874ca--- /dev/null+++ b/crates/agent_code_mode/src/domain/connected_apps/test.rs@@ -0,0 +1,337 @@+use super::*;+use crate::domain::ExecutionRecord;+use ai_toolset::actor::ToolActor;+use entity_access::domain::models::EntityType;+use macro_user_id::cowlike::CowLike;+use std::sync::Mutex;++struct Store(Mutex<Option<ExecutionRecord>>);++#[async_trait]+impl ExecutionStore for Store {+ async fn create(&self, _: AgentSessionId, _: &ExecutionRecord) -> Result<(), CodeModeError> {+ unreachable!("connected apps never create executions")+ }++ async fn save(&self, _: AgentSessionId, _: &ExecutionRecord) -> Result<(), CodeModeError> {+ unreachable!("connected apps never save executions")+ }++ async fn get(+ &self,+ _: AgentSessionId,+ execution: ExecutionId,+ ) -> Result<ExecutionRecord, CodeModeError> {+ self.0+ .lock()+ .unwrap()+ .clone()+ .filter(|record| record.execution_id == execution)+ .ok_or(CodeModeError::NotFound)+ }+}++struct Turns(Option<macro_uuid::Uuid>);++#[async_trait]+impl ExecutionTurns for Turns {+ async fn active(&self, _: AgentSessionId) -> Result<Option<macro_uuid::Uuid>, CodeModeError> {+ Ok(self.0)+ }+}++/// Records every use it is handed and answers one fixed app. Its session is+/// owned by [email protected] and prompted by [email protected].+#[derive(Default)]+struct Apps(Mutex<Vec<(AgentSessionId, String)>>);++#[async_trait]+impl ConnectedAppTools for Apps {+ async fn accounts(&self, _: AgentSessionId) -> Result<SessionAccounts, CodeModeError> {+ Ok(SessionAccounts {+ owner: MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned(),+ requester: Some(+ MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned(),+ ),+ })+ }++ async fn apps(&self, usage: &ConnectedAppUse) -> Result<Vec<ConnectedApp>, CodeModeError> {+ self.0+ .lock()+ .unwrap()+ .push((usage.session, usage.user.to_string()));+ Ok(vec![+ ConnectedApp {+ kind: ConnectedAppKind::App,+ key: "slack".into(),+ name: "Slack".into(),+ },+ ConnectedApp {+ kind: ConnectedAppKind::Custom,+ key: "0123456789abcdef".into(),+ name: "Internal wiki".into(),+ },+ ])+ }++ async fn tools(+ &self,+ _: &ConnectedAppUse,+ app: &ConnectedAppRef,+ ) -> Result<Vec<ConnectedTool>, CodeModeError> {+ if app.key != "slack" {+ return Err(CodeModeError::Unavailable);+ }+ Ok(vec![+ ConnectedTool {+ name: "list_channels".into(),+ description: Some("List Slack channels".into()),+ input_schema: serde_json::json!({"type": "object"}),+ },+ ConnectedTool {+ name: "send_message".into(),+ description: Some("Send a message to a Slack channel".into()),+ input_schema: serde_json::json!({"type": "object"}),+ },+ ])+ }++ async fn call(+ &self,+ usage: &ConnectedAppUse,+ app: &ConnectedAppRef,+ call: CallConnectedTool,+ ) -> Result<ConnectedToolResult, CodeModeError> {+ self.0+ .lock()+ .unwrap()+ .push((usage.session, usage.user.to_string()));+ Ok(ConnectedToolResult {+ is_error: false,+ content: vec![serde_json::json!({+ "type": "text",+ "text": format!("{} {} {}", app.key, call.tool, call.arguments["channel"]),+ })],+ structured_content: None,+ })+ }++ async fn discover(+ &self,+ _: &ConnectedAppUse,+ _: DiscoveryRequest,+ ) -> Result<DiscoverConnectorsResponse, CodeModeError> {+ unreachable!("these tests never discover")+ }++ async fn add_server(+ &self,+ _: &ConnectedAppUse,+ _: ConnectMcpServer,+ ) -> Result<ConnectMcpServerResponse, CodeModeError> {+ unreachable!("these tests never add servers")+ }+}++#[tokio::test]+async fn a_running_execution_of_the_active_turn_calls_as_its_approved_account() {+ let session = AgentSessionId::new_from_uuid(macro_uuid::Uuid::from_u128(7));+ let execution = ExecutionId::mint();+ let caller = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();+ let apps = Arc::new(Apps::default());+ let service = ConnectedAppService::new(+ Arc::new(Store(Mutex::new(Some(ExecutionRecord {+ execution_id: execution,+ acting_as: Some(ToolActor::Owner),+ turn_id: Some(macro_uuid::Uuid::from_u128(1)),+ source: "export async function main() {}".into(),+ status: ExecutionStatus::Running,+ result: None,+ error: None,+ calls: Vec::new(),+ activity: Vec::new(),+ activity_truncated: false,+ })))),+ Arc::new(Turns(Some(macro_uuid::Uuid::from_u128(1)))),+ apps.clone(),+ );+ let access = EntityAccessReceipt::<EditAccessLevel>::dangerously_assert_authenticated_user(+ caller.clone(),+ &session.to_string(),+ EntityType::AgentSession,+ );++ let result = service+ .call(+ &access,+ &caller,+ execution,+ ConnectedAppRef {+ kind: ConnectedAppKind::App,+ key: "slack".into(),+ },+ CallConnectedTool {+ tool: "send_message".into(),+ arguments: serde_json::json!({"channel": "general"})+ .as_object()+ .unwrap()+ .clone(),+ },+ )+ .await+ .unwrap();++ assert_eq!(+ result.content,+ vec![serde_json::json!({"type": "text", "text": "slack send_message \"general\""})]+ );+ assert_eq!(+ *apps.0.lock().unwrap(),+ vec![(session, "macro|[email protected]".to_owned())]+ );+}++#[tokio::test]+async fn a_finished_execution_or_an_ended_turn_reaches_no_app() {+ let session = AgentSessionId::new_from_uuid(macro_uuid::Uuid::from_u128(7));+ let execution = ExecutionId::mint();+ let caller = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();+ let access = EntityAccessReceipt::<EditAccessLevel>::dangerously_assert_authenticated_user(+ caller.clone(),+ &session.to_string(),+ EntityType::AgentSession,+ );+ let record = ExecutionRecord {+ execution_id: execution,+ acting_as: Some(ToolActor::Requester),+ turn_id: Some(macro_uuid::Uuid::from_u128(1)),+ source: "export async function main() {}".into(),+ status: ExecutionStatus::Succeeded,+ result: None,+ error: None,+ calls: Vec::new(),+ activity: Vec::new(),+ activity_truncated: false,+ };+ let apps = Arc::new(Apps::default());++ let finished = ConnectedAppService::new(+ Arc::new(Store(Mutex::new(Some(record.clone())))),+ Arc::new(Turns(Some(macro_uuid::Uuid::from_u128(1)))),+ apps.clone(),+ )+ .apps(&access, &caller, execution)+ .await;+ let ended = ConnectedAppService::new(+ Arc::new(Store(Mutex::new(Some(ExecutionRecord {+ status: ExecutionStatus::Running,+ ..record+ })))),+ Arc::new(Turns(Some(macro_uuid::Uuid::from_u128(2)))),+ apps.clone(),+ )+ .apps(&access, &caller, execution)+ .await;++ assert!(matches!(finished, Err(CodeModeError::Forbidden)));+ assert!(matches!(ended, Err(CodeModeError::Forbidden)));+ assert!(apps.0.lock().unwrap().is_empty());+}++#[tokio::test]+async fn a_caller_holding_another_account_than_the_execution_spends_nothing() {+ let session = AgentSessionId::new_from_uuid(macro_uuid::Uuid::from_u128(7));+ let execution = ExecutionId::mint();+ let owner = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();+ let apps = Arc::new(Apps::default());+ let service = ConnectedAppService::new(+ Arc::new(Store(Mutex::new(Some(ExecutionRecord {+ execution_id: execution,+ acting_as: Some(ToolActor::Requester),+ turn_id: Some(macro_uuid::Uuid::from_u128(1)),+ source: "export async function main() {}".into(),+ status: ExecutionStatus::Running,+ result: None,+ error: None,+ calls: Vec::new(),+ activity: Vec::new(),+ activity_truncated: false,+ })))),+ Arc::new(Turns(Some(macro_uuid::Uuid::from_u128(1)))),+ apps.clone(),+ );+ let access = EntityAccessReceipt::<EditAccessLevel>::dangerously_assert_authenticated_user(+ owner.clone(),+ &session.to_string(),+ EntityType::AgentSession,+ );++ let refused = service.apps(&access, &owner, execution).await;++ assert!(matches!(refused, Err(CodeModeError::Forbidden)));+ assert!(apps.0.lock().unwrap().is_empty());+}++#[tokio::test]+async fn a_search_ranks_tools_across_apps_and_reports_apps_it_could_not_read() {+ let session = AgentSessionId::new_from_uuid(macro_uuid::Uuid::from_u128(7));+ let execution = ExecutionId::mint();+ let caller = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();+ let service = ConnectedAppService::new(+ Arc::new(Store(Mutex::new(Some(ExecutionRecord {+ execution_id: execution,+ acting_as: Some(ToolActor::Owner),+ turn_id: Some(macro_uuid::Uuid::from_u128(1)),+ source: "export async function main() {}".into(),+ status: ExecutionStatus::Running,+ result: None,+ error: None,+ calls: Vec::new(),+ activity: Vec::new(),+ activity_truncated: false,+ })))),+ Arc::new(Turns(Some(macro_uuid::Uuid::from_u128(1)))),+ Arc::new(Apps::default()),+ );+ let access = EntityAccessReceipt::<EditAccessLevel>::dangerously_assert_authenticated_user(+ caller.clone(),+ &session.to_string(),+ EntityType::AgentSession,+ );++ let found = service+ .search_tools(&access, &caller, execution, "send slack message")+ .await+ .unwrap();++ assert_eq!(+ found+ .matches+ .iter()+ .map(|found| found.tool.name.as_str())+ .collect::<Vec<_>>(),+ vec!["send_message", "list_channels"]+ );+ assert_eq!(found.matches[0].app.key, "slack");+ assert_eq!(+ found+ .unsearched+ .iter()+ .map(|app| app.name.as_str())+ .collect::<Vec<_>>(),+ vec!["Internal wiki"]+ );+}diff --git a/crates/agent_code_mode/src/domain/reviews.rs b/crates/agent_code_mode/src/domain/reviews.rsindex 4bd292ad34..f3674f1479 100644--- a/crates/agent_code_mode/src/domain/reviews.rs+++ b/crates/agent_code_mode/src/domain/reviews.rs@@ -771,7 +771,7 @@ impl ReviewService {}}}-fn session_id(kind: EntityType, id: &str) -> Result<AgentSessionId, CodeModeError> {+pub(super) fn session_id(kind: EntityType, id: &str) -> Result<AgentSessionId, CodeModeError> {if kind != EntityType::AgentSession {return Err(CodeModeError::Forbidden);}diff --git a/crates/agent_code_mode/src/domain/service.rs b/crates/agent_code_mode/src/domain/service.rsindex 33c491aa32..6b3464fdb1 100644--- a/crates/agent_code_mode/src/domain/service.rs+++ b/crates/agent_code_mode/src/domain/service.rs@@ -271,6 +271,9 @@ pub fn covered_by_code_sdk(name: &str, user_tool: bool) -> bool {// macro.agents.list() and macro.agentSessions.createManaged.| "ListCodingAgents"| "DispatchCodingAgent"+ // macro.connectedApps.discover and .addServer.+ | "DiscoverConnectors"+ | "ConnectMcpServer")}diff --git a/crates/agent_code_mode/src/inbound/axum_router.rs b/crates/agent_code_mode/src/inbound/axum_router.rsindex c594039523..506825bb6b 100644--- a/crates/agent_code_mode/src/inbound/axum_router.rs+++ b/crates/agent_code_mode/src/inbound/axum_router.rs@@ -1,5 +1,7 @@//! Session-authorized reads for code execution's existing tool components.-use crate::domain::{CodeModeError, ExecutionId, ExecutionRecord, SessionCodeMode, reviews::*};+use crate::domain::{+ CodeModeError, ExecutionId, ExecutionRecord, SessionCodeMode, connected_apps::*, reviews::*,+};use axum::{Json, Router,body::Bytes,@@ -26,6 +28,7 @@ use std::sync::Arc;pub struct CodeExecutionRouterState<Access, Auth> {service: Arc<dyn SessionCodeMode>,reviews: ReviewService,+ connected_apps: ConnectedAppService,entity_access: Arc<Access>,authorization: MacroAuthorizationState<Auth>,}@@ -35,12 +38,14 @@ impl<Access, Auth> CodeExecutionRouterState<Access, Auth> {pub fn new(service: Arc<dyn SessionCodeMode>,reviews: ReviewService,+ connected_apps: ConnectedAppService,entity_access: Arc<Access>,authorization: MacroAuthorizationState<Auth>,) -> Self {Self {service,reviews,+ connected_apps,entity_access,authorization,}@@ -52,6 +57,7 @@ impl<Access, Auth> Clone for CodeExecutionRouterState<Access, Auth> {Self {service: self.service.clone(),reviews: self.reviews.clone(),+ connected_apps: self.connected_apps.clone(),entity_access: self.entity_access.clone(),authorization: self.authorization.clone(),}@@ -93,6 +99,30 @@ where"/{session_id}/code-executions/{execution_id}/reviews",get(list_reviews::<Access, Auth>),)+ .route(+ "/{session_id}/code-executions/{execution_id}/connected-apps",+ get(list_connected_apps::<Access, Auth>),+ )+ .route(+ "/{session_id}/code-executions/{execution_id}/connected-apps/tools",+ get(search_connected_app_tools::<Access, Auth>),+ )+ .route(+ "/{session_id}/code-executions/{execution_id}/connected-apps/discover",+ post(discover_connected_apps::<Access, Auth>),+ )+ .route(+ "/{session_id}/code-executions/{execution_id}/connected-apps/servers",+ post(add_connected_mcp_server::<Access, Auth>),+ )+ .route(+ "/{session_id}/code-executions/{execution_id}/connected-apps/{kind}/{key}/tools",+ get(list_connected_app_tools::<Access, Auth>),+ )+ .route(+ "/{session_id}/code-executions/{execution_id}/connected-apps/{kind}/{key}/calls",+ post(call_connected_app_tool::<Access, Auth>),+ ).with_state(state)}@@ -231,3 +261,174 @@ pub async fn decide_review<Access: EntityAccessService, Auth: MacroAuthorization.map(Json).map_err(CodeExecutionApiError)}++#[utoipa::path(get, path = "/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps", tag = "agent-sessions", operation_id = "list_execution_connected_apps",+ params(("session_id" = Uuid, Path), ("execution_id" = Uuid, Path, description = "A running execution of the session's current turn")),+ responses((status = 200, body = Vec<ConnectedApp>), (status = 403), (status = 404)))]+/// List the connected apps and custom MCP servers the session's agent may use.+pub async fn list_connected_apps<Access: EntityAccessService, Auth: MacroAuthorizationService>(+ access: AgentSessionAccessLevelExtractor<EditAccessLevel, Access, Auth>,+ caller: MacroAuthorizationExtractor<Auth, ActingUser>,+ State(state): State<CodeExecutionRouterState<Access, Auth>>,+ Path((_session, execution)): Path<(Uuid, Uuid)>,+) -> Result<Json<Vec<ConnectedApp>>, CodeExecutionApiError> {+ state+ .connected_apps+ .apps(+ &access.entity_access_receipt,+ &caller.authorization.user.macro_user_id,+ ExecutionId::from_uuid(execution),+ )+ .await+ .map(Json)+ .map_err(CodeExecutionApiError)+}++#[utoipa::path(get, path = "/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/{kind}/{key}/tools", tag = "agent-sessions", operation_id = "list_connected_app_tools",+ params(("session_id" = Uuid, Path), ("execution_id" = Uuid, Path), ("kind" = ConnectedAppKind, Path), ("key" = String, Path, description = "The app's slug or custom server key")),+ responses((status = 200, body = Vec<ConnectedTool>), (status = 403), (status = 404)))]+/// List the tools one connected app serves.+pub async fn list_connected_app_tools<+ Access: EntityAccessService,+ Auth: MacroAuthorizationService,+>(+ access: AgentSessionAccessLevelExtractor<EditAccessLevel, Access, Auth>,+ caller: MacroAuthorizationExtractor<Auth, ActingUser>,+ State(state): State<CodeExecutionRouterState<Access, Auth>>,+ Path((_session, execution, kind, key)): Path<(Uuid, Uuid, ConnectedAppKind, String)>,+) -> Result<Json<Vec<ConnectedTool>>, CodeExecutionApiError> {+ state+ .connected_apps+ .tools(+ &access.entity_access_receipt,+ &caller.authorization.user.macro_user_id,+ ExecutionId::from_uuid(execution),+ ConnectedAppRef { kind, key },+ )+ .await+ .map(Json)+ .map_err(CodeExecutionApiError)+}++#[utoipa::path(post, path = "/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/{kind}/{key}/calls", tag = "agent-sessions", operation_id = "call_connected_app_tool",+ params(("session_id" = Uuid, Path), ("execution_id" = Uuid, Path), ("kind" = ConnectedAppKind, Path), ("key" = String, Path, description = "The app's slug or custom server key")),+ request_body = CallConnectedTool,+ responses((status = 200, body = ConnectedToolResult), (status = 400), (status = 403), (status = 404)))]+/// Call one tool of a connected app as the execution's account.+pub async fn call_connected_app_tool<+ Access: EntityAccessService,+ Auth: MacroAuthorizationService,+>(+ access: AgentSessionAccessLevelExtractor<EditAccessLevel, Access, Auth>,+ caller: MacroAuthorizationExtractor<Auth, ActingUser>,+ State(state): State<CodeExecutionRouterState<Access, Auth>>,+ Path((_session, execution, kind, key)): Path<(Uuid, Uuid, ConnectedAppKind, String)>,+ body: Bytes,+) -> Result<Json<ConnectedToolResult>, CodeExecutionApiError> {+ let call: CallConnectedTool = decode(&body).map_err(CodeExecutionApiError)?;+ state+ .connected_apps+ .call(+ &access.entity_access_receipt,+ &caller.authorization.user.macro_user_id,+ ExecutionId::from_uuid(execution),+ ConnectedAppRef { kind, key },+ call,+ )+ .await+ .map(Json)+ .map_err(CodeExecutionApiError)+}++#[utoipa::path(post, path = "/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/discover", tag = "agent-sessions", operation_id = "discover_connected_apps",+ params(("session_id" = Uuid, Path), ("execution_id" = Uuid, Path)),+ request_body = pipedream_mcp::domain::service::discovery::DiscoveryRequest,+ responses((status = 200, body = pipedream_mcp::inbound::toolset::DiscoverConnectorsResponse), (status = 400), (status = 403), (status = 404)))]+/// Search the connectable app catalog, or inspect one app's tools and connection status.+pub async fn discover_connected_apps<+ Access: EntityAccessService,+ Auth: MacroAuthorizationService,+>(+ access: AgentSessionAccessLevelExtractor<EditAccessLevel, Access, Auth>,+ caller: MacroAuthorizationExtractor<Auth, ActingUser>,+ State(state): State<CodeExecutionRouterState<Access, Auth>>,+ Path((_session, execution)): Path<(Uuid, Uuid)>,+ body: Bytes,+) -> Result<Json<pipedream_mcp::inbound::toolset::DiscoverConnectorsResponse>, CodeExecutionApiError>+{+ let request = decode(&body).map_err(CodeExecutionApiError)?;+ state+ .connected_apps+ .discover(+ &access.entity_access_receipt,+ &caller.authorization.user.macro_user_id,+ ExecutionId::from_uuid(execution),+ request,+ )+ .await+ .map(Json)+ .map_err(CodeExecutionApiError)+}++#[utoipa::path(post, path = "/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/servers", tag = "agent-sessions", operation_id = "add_connected_mcp_server",+ params(("session_id" = Uuid, Path), ("execution_id" = Uuid, Path)),+ request_body = mcp_client::inbound::toolset::ConnectMcpServer,+ responses((status = 200, body = mcp_client::inbound::toolset::ConnectMcpServerResponse), (status = 400), (status = 403), (status = 404)))]+/// Add a custom MCP server to the execution account's connections.+pub async fn add_connected_mcp_server<+ Access: EntityAccessService,+ Auth: MacroAuthorizationService,+>(+ access: AgentSessionAccessLevelExtractor<EditAccessLevel, Access, Auth>,+ caller: MacroAuthorizationExtractor<Auth, ActingUser>,+ State(state): State<CodeExecutionRouterState<Access, Auth>>,+ Path((_session, execution)): Path<(Uuid, Uuid)>,+ body: Bytes,+) -> Result<Json<mcp_client::inbound::toolset::ConnectMcpServerResponse>, CodeExecutionApiError> {+ let server = decode(&body).map_err(CodeExecutionApiError)?;+ state+ .connected_apps+ .add_server(+ &access.entity_access_receipt,+ &caller.authorization.user.macro_user_id,+ ExecutionId::from_uuid(execution),+ server,+ )+ .await+ .map(Json)+ .map_err(CodeExecutionApiError)+}++/// Keywords to find connected-app tools by.+#[derive(Debug, serde::Deserialize, utoipa::IntoParams)]+pub struct ConnectedToolQuery {+ /// Keywords matched against tool names and descriptions, e.g. `linear issue`.+ pub query: String,+}++#[utoipa::path(get, path = "/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/tools", tag = "agent-sessions", operation_id = "search_connected_app_tools",+ params(("session_id" = Uuid, Path), ("execution_id" = Uuid, Path), ConnectedToolQuery),+ responses((status = 200, body = ConnectedToolSearch), (status = 403), (status = 404)))]+/// Find tools across the agent's connected apps by keywords.+pub async fn search_connected_app_tools<+ Access: EntityAccessService,+ Auth: MacroAuthorizationService,+>(+ access: AgentSessionAccessLevelExtractor<EditAccessLevel, Access, Auth>,+ caller: MacroAuthorizationExtractor<Auth, ActingUser>,+ State(state): State<CodeExecutionRouterState<Access, Auth>>,+ Path((_session, execution)): Path<(Uuid, Uuid)>,+ axum::extract::Query(query): axum::extract::Query<ConnectedToolQuery>,+) -> Result<Json<ConnectedToolSearch>, CodeExecutionApiError> {+ state+ .connected_apps+ .search_tools(+ &access.entity_access_receipt,+ &caller.authorization.user.macro_user_id,+ ExecutionId::from_uuid(execution),+ &query.query,+ )+ .await+ .map(Json)+ .map_err(CodeExecutionApiError)+}diff --git a/crates/agent_egress/AGENTS.md b/crates/agent_egress/AGENTS.mdindex 65bce9492c..d497f2d022 100644--- a/crates/agent_egress/AGENTS.md+++ b/crates/agent_egress/AGENTS.md@@ -20,6 +20,15 @@ MCP app, a custom server, or a GitHub installation token) on each request.- `src/outbound/mcp_credentials.rs` / `macro_mcp.rs` / `custom_mcp.rs` /`github_tokens.rs`: the credential resolvers.- `src/inbound/axum_router.rs`: the HTTP entry point the sandbox calls.+- `SessionMcpExchange` (`src/domain/service/actor.rs`): in-process+ `tools/list`/`tools/call` on a connected app or custom server for a caller+ that authorized against the session itself (code executions'+ `macro.connectedApps`). It reads the grant by session id+ (`SessionAuthority::authorize_session`), never reaches Macro's own server or+ previews, and shares the actor path's credential resolution and+ not-connected answers. A call as the owner in a turn someone else prompted+ is held per call through `OwnerApprovals::hold_in_process`, the same+ approval record as the native tool gate.## Scopediff --git a/crates/agent_egress/src/domain/approval.rs b/crates/agent_egress/src/domain/approval.rsindex 7f4a8d4c9c..87ba7980e7 100644--- a/crates/agent_egress/src/domain/approval.rs+++ b/crates/agent_egress/src/domain/approval.rs@@ -120,6 +120,14 @@ pub trait OwnerApprovals: Send + Sync + 'static {session: AgentSessionId,request_id: &serde_json::Value,) -> impl Future<Output = Result<(), EgressError>> + Send;++ /// Hold an in-process `call`, one with no response to stream into,+ /// until it is resolved, and say how. Dropping the future cancels the+ /// hold, which is how a stopped turn gives up on it.+ fn hold_in_process(+ &self,+ call: InProcessCall,+ ) -> impl Future<Output = Result<ToolApprovalStatus, EgressError>> + Send;}impl<Approvals: OwnerApprovals> OwnerApprovals for Arc<Approvals> {@@ -137,6 +145,13 @@ impl<Approvals: OwnerApprovals> OwnerApprovals for Arc<Approvals> {) -> impl Future<Output = Result<(), EgressError>> + Send {(**self).withdraw(session, request_id)}++ fn hold_in_process(+ &self,+ call: InProcessCall,+ ) -> impl Future<Output = Result<ToolApprovalStatus, EgressError>> + Send {+ (**self).hold_in_process(call)+ }}/// For a proxy with no way to ask the owner: every held call is refused, in@@ -165,6 +180,14 @@ impl OwnerApprovals for RefuseHeldCalls {) -> Result<(), EgressError> {Ok(())}++ /// Nobody can be asked, so the call is refused as though it expired.+ async fn hold_in_process(+ &self,+ _call: InProcessCall,+ ) -> Result<ToolApprovalStatus, EgressError> {+ Ok(ToolApprovalStatus::Expired)+ }}/// The approval flow over its store, its wake-ups, and whoever it announces@@ -259,72 +282,6 @@ pub struct InProcessCall {pub arguments: serde_json::Value,}-impl<Store, Signals, Announcer> ToolApprovalService<Store, Signals, Announcer>-where- Store: ToolApprovalStore,- Signals: ToolApprovalSignals,- Announcer: ToolApprovalAnnouncer,-{- /// Hold `call` until it is resolved, and say how. Dropping the future- /// cancels the hold, which is how a stopped turn gives up on it.- pub async fn hold_in_process(- &self,- call: InProcessCall,- ) -> Result<ToolApprovalStatus, EgressError> {- if self- .inner- .is_standing(- call.session,- &call.prompter,- &call.server_slug,- &call.tool_name,- )- .await?- {- return Ok(ToolApprovalStatus::Approved);- }- let prompter = call.prompter.clone();- let approval = ToolApproval {- id: ToolApprovalId::mint(),- session: call.session,- turn_action_id: call.prompter.action_id,- // No JSON-RPC request to name; unique so nothing withdraws it.- request_id: serde_json::Value::String(macro_uuid::generate_uuid_v7().to_string()),- owner: call.owner.clone(),- requested_by: call.prompter.acting_user().cloned(),- server_slug: call.server_slug,- server_name: call.server_name,- tool_name: call.tool_name,- arguments: call.arguments,- status: ToolApprovalStatus::Pending,- resolved_by: None,- remembered: false,- };- self.inner.store.insert(&approval).await?;- if self.inner.settled_by_standing(&approval, &prompter).await? {- return Ok(ToolApprovalStatus::Approved);- }- tracing::info!(- approval = %approval.id,- session = %approval.session,- tool = %approval.tool_name,- "holding an in-process tool call for the owner's approval"- );- self.inner.announcer.requested(&approval, &call.owner).await;-- let guard = CancelOnDrop {- inner: Some(Arc::clone(&self.inner)),- id: approval.id,- };- let resolved = self- .inner- .await_resolution(&approval, None, call.owner.email_str(), None)- .await;- guard.disarm();- Ok(resolved?.status)- }-}-/// Cancels a held call whose waiter went away before it was resolved.struct CancelOnDrop<Store, Signals, Announcer>where@@ -771,6 +728,63 @@ where}Ok(())}++ async fn hold_in_process(+ &self,+ call: InProcessCall,+ ) -> Result<ToolApprovalStatus, EgressError> {+ if self+ .inner+ .is_standing(+ call.session,+ &call.prompter,+ &call.server_slug,+ &call.tool_name,+ )+ .await?+ {+ return Ok(ToolApprovalStatus::Approved);+ }+ let prompter = call.prompter.clone();+ let approval = ToolApproval {+ id: ToolApprovalId::mint(),+ session: call.session,+ turn_action_id: call.prompter.action_id,+ // No JSON-RPC request to name; unique so nothing withdraws it.+ request_id: serde_json::Value::String(macro_uuid::generate_uuid_v7().to_string()),+ owner: call.owner.clone(),+ requested_by: call.prompter.acting_user().cloned(),+ server_slug: call.server_slug,+ server_name: call.server_name,+ tool_name: call.tool_name,+ arguments: call.arguments,+ status: ToolApprovalStatus::Pending,+ resolved_by: None,+ remembered: false,+ };+ self.inner.store.insert(&approval).await?;+ if self.inner.settled_by_standing(&approval, &prompter).await? {+ return Ok(ToolApprovalStatus::Approved);+ }+ tracing::info!(+ approval = %approval.id,+ session = %approval.session,+ tool = %approval.tool_name,+ "holding an in-process tool call for the owner's approval"+ );+ self.inner.announcer.requested(&approval, &call.owner).await;++ let guard = CancelOnDrop {+ inner: Some(Arc::clone(&self.inner)),+ id: approval.id,+ };+ let resolved = self+ .inner+ .await_resolution(&approval, None, call.owner.email_str(), None)+ .await;+ guard.disarm();+ Ok(resolved?.status)+ }}/// What the model is told instead of the tool's answer, for every outcomediff --git a/crates/agent_egress/src/domain/model.rs b/crates/agent_egress/src/domain/model.rsindex 123f761239..b579e28d2d 100644--- a/crates/agent_egress/src/domain/model.rs+++ b/crates/agent_egress/src/domain/model.rs@@ -392,17 +392,22 @@ pub fn not_connected_tool_result(name: &str,id: serde_json::Value,) -> ProxyResponse {+ tool_result_response(id, not_connected_text(slug, name))+}++/// What [`not_connected_tool_result`] tells the model, for callers that+/// answer outside JSON-RPC.+pub fn not_connected_text(slug: &McpServerSlug, name: &str) -> String {let payload = serde_json::json!({"appSlug": slug.as_str(),"name": name,});- let text = format!(+ format!("{name} is not connected for the selected acting_as account, or they have it turned off, so this tool cannot run yet. Tell them so in your reply, and include this exact markup so they get a button that connects it: <{tag}>{payload}</{tag}> Close your reply by asking them to let you know once they have connected {name} so \you can try again - when they do, call this tool again; nothing else needs to change.",name = name,tag = CONNECT_APP_TAG,- );- tool_result_response(id, text)+ )}/// The tool result the proxy answers a `tools/call` with when the session@@ -415,14 +420,27 @@ pub fn not_connected_tool_result(/// The name is the owner's own, off their row, never anything the request/// carried.pub fn disconnected_tool_result(name: &str, id: serde_json::Value) -> ProxyResponse {- let text = format!(+ tool_result_response(id, disconnected_text(name))+}++/// What [`disconnected_tool_result`] tells the model, for callers that answer+/// outside JSON-RPC.+pub fn disconnected_text(name: &str) -> String {+ format!("{name} is a custom MCP server the selected acting_as account added, but its \connection has expired, so this tool cannot run yet. Tell them so in your reply, \and ask them to open Agents → Connections, find {name} under Custom MCP, and use \Reconnect. Close your reply by asking them to let you know once they have done so \- when they do, call this tool again; nothing else needs to change.",- );- tool_result_response(id, text)+ )+}++/// An MCP tool result carrying `text` as its `isError` answer.+pub fn tool_error_result(text: String) -> serde_json::Value {+ serde_json::json!({+ "isError": true,+ "content": [{ "type": "text", "text": text }],+ })}/// A JSON-RPC response carrying `text` as an `isError` tool result for `id`.@@ -430,10 +448,7 @@ pub(crate) fn tool_result_response(id: serde_json::Value, text: String) -> Proxylet body = serde_json::json!({"jsonrpc": "2.0","id": id,- "result": {- "isError": true,- "content": [{ "type": "text", "text": text }],- },+ "result": tool_error_result(text),});let bytes = Bytes::from(serde_json::to_vec(&body).expect("a JSON value serializes"));let mut response = http::Response::new(diff --git a/crates/agent_egress/src/domain/ports.rs b/crates/agent_egress/src/domain/ports.rsindex 9013e2bb1d..58d8d01cdb 100644--- a/crates/agent_egress/src/domain/ports.rs+++ b/crates/agent_egress/src/domain/ports.rs@@ -29,6 +29,14 @@ pub trait SessionAuthority: Send + Sync {&self,token: &SessionToken,) -> impl Future<Output = Result<SessionGrant, EgressError>> + Send;++ /// The same grant, read by session id for an in-process caller that has+ /// already authorized its request against the session itself. Refuses a+ /// closed session exactly as [`Self::authorize`] does.+ fn authorize_session(+ &self,+ session: AgentSessionId,+ ) -> impl Future<Output = Result<SessionGrant, EgressError>> + Send;}/// Resolve an MCP destination to a live upstream call.diff --git a/crates/agent_egress/src/domain/service.rs b/crates/agent_egress/src/domain/service.rsindex 8a9d8a2861..7e4e97f0d9 100644--- a/crates/agent_egress/src/domain/service.rs+++ b/crates/agent_egress/src/domain/service.rs@@ -35,6 +35,28 @@ pub trait EgressService: Send + Sync {) -> impl Future<Output = Result<ProxyResponse, EgressError>> + Send;}+/// MCP exchanges for an in-process caller, such as a code execution's+/// connected-app route, that authorized its request against the session+/// itself rather than presenting the session's token.+pub trait SessionMcpExchange: Send + Sync {+ /// The session's grant, read by id. Refuses a closed session.+ fn session_grant(+ &self,+ session: crate::domain::model::AgentSessionId,+ ) -> impl Future<Output = Result<crate::domain::model::SessionGrant, EgressError>> + Send;++ /// One `tools/list` or `tools/call` on a connected app or custom server+ /// as `user`, an account the caller already settled the call may spend.+ /// Returns the MCP `result` payload.+ fn exchange_as(+ &self,+ grant: &crate::domain::model::SessionGrant,+ user: ¯o_user_id::user_id::MacroUserIdStr<'static>,+ destination: &McpDestination,+ request: serde_json::Value,+ ) -> impl Future<Output = Result<serde_json::Value, EgressError>> + Send;+}+/// The service, over its ports.////// Held tool calls are refused until [`Self::with_owner_approvals`] says howdiff --git a/crates/agent_egress/src/domain/service/actor.rs b/crates/agent_egress/src/domain/service/actor.rsindex c6f8583fb4..677afed485 100644--- a/crates/agent_egress/src/domain/service/actor.rs+++ b/crates/agent_egress/src/domain/service/actor.rs@@ -1,9 +1,14 @@//! Resolve each call's explicit actor before credentials or approvals.use super::*;-use crate::domain::model::{SessionGrant, tool_result_response};+use crate::domain::approval::{InProcessCall, refusal};+use crate::domain::model::{+ AgentSessionId, SessionGrant, disconnected_text, not_connected_text, tool_error_result,+ tool_result_response,+};use agent_session::domain::model::TurnPrompter;use ai_toolset::actor::{ToolActor, add_actor_schema};+use macro_user_id::user_id::MacroUserIdStr;use serde_json::{Value, json};/// Preserve the original MCP session/callback capabilities for owner calls.@@ -68,32 +73,12 @@ where(actor, user)};tracing::info!(session = %grant.session, ?actor, listing, "resolved MCP actor");- let resolution = match self.credentials.resolve(user, grant.agent, destination).await {- Ok(resolution) => resolution,- Err(EgressError::UnknownCustomServer(_)) if !listing => return Ok(tool_result_response(id,- "This custom MCP server is not connected for the selected actor. Ask them to add or reconnect that server in Agents → Connections. Do not switch accounts unless they requested it.".into())),- Err(error) => return Err(error),- };- let upstream = match resolution {- McpResolution::Connected(call) => call,- McpResolution::Unconnected(call) if listing => call,- McpResolution::Unconnected(_) => {- if let McpDestination::Connected(slug) = destination {- return Ok(not_connected_tool_result(- slug,- &grant.display_name(slug),- id,- ));- }- return Ok(tool_result_response(- id,- "The selected actor has no connection for this tool.".into(),- ));- }- McpResolution::Disconnected { call, .. } if listing => call,- McpResolution::Disconnected { name, .. } => {- return Ok(disconnected_tool_result(&name, id));- }+ let upstream = match self+ .resolve_upstream(grant, user, destination, listing)+ .await?+ {+ Ok(upstream) => upstream,+ Err(text) => return Ok(tool_result_response(id, text)),};let transport = self.actor_mcp@@ -121,8 +106,171 @@ where).await}++ /// The upstream `user`'s connection reaches `destination` through, or the+ /// tool result that says why a call cannot run.+ async fn resolve_upstream(+ &self,+ grant: &SessionGrant,+ user: &MacroUserIdStr<'static>,+ destination: &McpDestination,+ listing: bool,+ ) -> Result<Result<UpstreamCall, String>, EgressError> {+ let resolution = match self.credentials.resolve(user, grant.agent, destination).await {+ Ok(resolution) => resolution,+ Err(EgressError::UnknownCustomServer(_)) if !listing => return Ok(Err(+ "This custom MCP server is not connected for the selected actor. Ask them to add or reconnect that server in Agents → Connections. Do not switch accounts unless they requested it.".into())),+ Err(error) => return Err(error),+ };+ Ok(match resolution {+ McpResolution::Connected(call) => Ok(call),+ McpResolution::Unconnected(call) if listing => Ok(call),+ McpResolution::Unconnected(_) => match destination {+ McpDestination::Connected(slug) => {+ Err(not_connected_text(slug, &grant.display_name(slug)))+ }+ _ => Err("The selected actor has no connection for this tool.".into()),+ },+ McpResolution::Disconnected { call, .. } if listing => Ok(call),+ McpResolution::Disconnected { name, .. } => Err(disconnected_text(&name)),+ })+ }}+impl<Sessions, Credentials, Tokens, Forward, Approvals> SessionMcpExchange+ for EgressServiceImpl<Sessions, Credentials, Tokens, Forward, Approvals>+where+ Sessions: SessionAuthority,+ Credentials: McpCredentials,+ Tokens: GithubTokens,+ Forward: Forwarder + 'static,+ Approvals: OwnerApprovals,+{+ /// The session's grant, read by id for an in-process caller that has+ /// authorized its own request against the session.+ async fn session_grant(&self, session: AgentSessionId) -> Result<SessionGrant, EgressError> {+ self.sessions.authorize_session(session).await+ }++ /// One `tools/list` or `tools/call` on a connected app or custom server as+ /// `user`, for an in-process caller that already settled which account+ /// the call spends and that it may spend it.+ ///+ /// The same credential resolution and independently authenticated+ /// transport as a sandbox's requester call, so an app the account has+ /// not connected, or whose grant died, answers with the same tool result.+ /// Returns the MCP `result` payload. Listing reads the owner's catalog,+ /// as every session's discovery does.+ #[tracing::instrument(skip_all, err, fields(session_id = %grant.session, ?destination))]+ async fn exchange_as(+ &self,+ grant: &SessionGrant,+ user: &MacroUserIdStr<'static>,+ destination: &McpDestination,+ request: Value,+ ) -> Result<Value, EgressError> {+ if !matches!(+ destination,+ McpDestination::Connected(_) | McpDestination::Custom(_)+ ) {+ return Err(EgressError::Unroutable(+ "only connected apps and custom servers are exchanged here".into(),+ ));+ }+ let listing = request["method"] == "tools/list";+ let user = if listing { &grant.owner } else { user };+ let upstream = match self+ .resolve_upstream(grant, user, destination, listing)+ .await?+ {+ Ok(upstream) => upstream,+ Err(text) => return Ok(tool_error_result(text)),+ };+ if !listing+ && let Some(text) = self+ .hold_owner_call(grant, user, destination, &request)+ .await?+ {+ return Ok(tool_error_result(text));+ }+ let transport = self+ .actor_mcp+ .clone()+ .ok_or(EgressError::Unauthenticated("actor transport unavailable"))?;+ match transport+ .exchange(grant.session, user.clone(), upstream, request)+ .await+ {+ Ok(result) => Ok(result),+ Err(error) if !listing => {+ tracing::warn!(?error, "actor MCP exchange failed");+ Ok(tool_error_result(UNKNOWN_OUTCOME.into()))+ }+ Err(error) => Err(error),+ }+ }+}++impl<Sessions, Credentials, Tokens, Forward, Approvals>+ EgressServiceImpl<Sessions, Credentials, Tokens, Forward, Approvals>+where+ Sessions: SessionAuthority,+ Approvals: OwnerApprovals,+{+ /// A call spending the owner's access in a turn somebody else prompted+ /// waits for the owner, one call at a time, the same as a sandbox's+ /// held call: the same approval record, announcement and standing+ /// approvals. `Some` with what to tell the model when it may not run.+ async fn hold_owner_call(+ &self,+ grant: &SessionGrant,+ user: &MacroUserIdStr<'static>,+ destination: &McpDestination,+ request: &Value,+ ) -> Result<Option<String>, EgressError> {+ let Some(prompter) = grant.held_prompter().filter(|_| *user == grant.owner) else {+ return Ok(None);+ };+ let (server_slug, server_name) = match destination {+ McpDestination::Connected(slug) => (slug.as_str().to_owned(), grant.display_name(slug)),+ McpDestination::Custom(key) => {+ (format!("custom-{key}"), "custom MCP server".to_owned())+ }+ McpDestination::Macro | McpDestination::Preview => {+ return Err(EgressError::Unroutable(+ "only connected apps and custom servers are exchanged here".into(),+ ));+ }+ };+ let tool = request["params"]["name"]+ .as_str()+ .unwrap_or_default()+ .to_owned();+ let status = self+ .approvals+ .hold_in_process(InProcessCall {+ session: grant.session,+ owner: grant.owner.clone(),+ prompter: prompter.clone(),+ server_slug,+ server_name,+ tool_name: tool.clone(),+ arguments: request["params"]["arguments"].clone(),+ })+ .await?;+ let current = self.sessions.authorize_session(grant.session).await?;+ if current.prompter != grant.prompter {+ return Ok(Some(+ "The original turn ended; this tool did not run.".into(),+ ));+ }+ Ok(refusal(status, grant.owner.email_str(), &tool))+ }+}++/// What a failed call says: it may have run upstream before failing.+const UNKNOWN_OUTCOME: &str = "The selected account's tool could not complete. Its outcome may be unknown; check state before retrying writes.";+async fn exchange_result(transport: &dyn crate::domain::ports::ActorMcpTransport,session: crate::domain::model::AgentSessionId,@@ -137,7 +285,7 @@ async fn exchange_result(Ok(result) => result,Err(error) if !listing => {tracing::warn!(?error, "actor MCP exchange failed");- return Ok(tool_result_response(id, "The selected account's tool could not complete. Its outcome may be unknown; check state before retrying writes.".into()));+ return Ok(tool_result_response(id, UNKNOWN_OUTCOME.into()));}Err(error) => return Err(error),};diff --git a/crates/agent_egress/src/domain/service/test.rs b/crates/agent_egress/src/domain/service/test.rsindex 8635da2014..72b934f2b8 100644--- a/crates/agent_egress/src/domain/service/test.rs+++ b/crates/agent_egress/src/domain/service/test.rs@@ -70,6 +70,15 @@ impl SessionAuthority for StubSessions {.clone().map_err(|()| EgressError::Unauthenticated("unknown session token"))}++ async fn authorize_session(+ &self,+ _session: AgentSessionId,+ ) -> Result<SessionGrant, EgressError> {+ self.0+ .clone()+ .map_err(|()| EgressError::Unauthenticated("unknown session"))+ }}/// How the spy answers a slug it is asked about.@@ -1308,6 +1317,9 @@ struct RecordingApprovals {)>,>,withdrawn: Mutex<Vec<serde_json::Value>>,+ held_in_process: Mutex<Vec<crate::domain::approval::InProcessCall>>,+ /// How an in-process hold is answered; nobody answering expires it.+ answer: Mutex<Option<agent_runtime_protocol::domain::tool_approval::ToolApprovalStatus>>,}impl OwnerApprovals for RecordingApprovals {@@ -1330,6 +1342,19 @@ impl OwnerApprovals for RecordingApprovals {self.withdrawn.lock().unwrap().push(request_id.clone());Ok(())}++ async fn hold_in_process(+ &self,+ call: crate::domain::approval::InProcessCall,+ ) -> Result<agent_runtime_protocol::domain::tool_approval::ToolApprovalStatus, EgressError>+ {+ self.held_in_process.lock().unwrap().push(call);+ Ok(self+ .answer+ .lock()+ .unwrap()+ .unwrap_or(agent_runtime_protocol::domain::tool_approval::ToolApprovalStatus::Expired))+ }}const TOOLS_CALL: &str = r#"{"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"search","arguments":{"q":"x"}}}"#;diff --git a/crates/agent_egress/src/domain/service/test/actor.rs b/crates/agent_egress/src/domain/service/test/actor.rsindex 1283c6aa95..8c9be9ad9a 100644--- a/crates/agent_egress/src/domain/service/test/actor.rs+++ b/crates/agent_egress/src/domain/service/test/actor.rs@@ -189,6 +189,10 @@ impl SessionAuthority for TurnChanges {}Ok(grant)}++ async fn authorize_session(&self, _: AgentSessionId) -> Result<SessionGrant, EgressError> {+ self.authorize(&SessionToken::new("unused")).await+ }}struct Approve;@@ -199,6 +203,13 @@ impl OwnerApprovals for Approve {async fn withdraw(&self, _: AgentSessionId, _: &Value) -> Result<(), EgressError> {Ok(())}+ async fn hold_in_process(+ &self,+ _: crate::domain::approval::InProcessCall,+ ) -> Result<agent_runtime_protocol::domain::tool_approval::ToolApprovalStatus, EgressError>+ {+ Ok(agent_runtime_protocol::domain::tool_approval::ToolApprovalStatus::Approved)+ }}#[tokio::test]@@ -255,3 +266,185 @@ async fn macro_tools_are_attributed_to_the_sessions_agent_not_one_the_caller_namasker().to_string());}++#[tokio::test]+async fn an_in_process_call_spends_the_settled_account_without_holding() {+ let asker = MacroUserIdStr::try_from_email("[email protected]").unwrap();+ let transport = Arc::new(ActorTransport::default());+ let service = gated(prompted_by(Some(asker.clone())), SpyCredentials::knowing())+ .with_actor_mcp(transport.clone());+ let grant = service.session_grant(AgentSessionId::new()).await.unwrap();++ let result = service+ .exchange_as(+ &grant,+ &asker,+ &McpDestination::Connected(McpServerSlug::parse("linear").unwrap()),+ json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"search","arguments":{"q":"x"}}}),+ )+ .await+ .unwrap();++ assert_eq!(result, json!({"content":[{"type":"text","text":"ok"}]}));+ assert_eq!(+ service.credentials.asked.lock().unwrap()[0].0,+ asker.to_string()+ );+ assert_eq!(+ transport.0.lock().unwrap()[0]["params"]["arguments"],+ json!({"q":"x"})+ );+ assert!(service.approvals.held.lock().unwrap().is_empty());+ assert!(!service.forward.was_called());+}++#[tokio::test]+async fn an_in_process_listing_reads_the_owner_catalog_and_an_unconnected_call_offers_connect() {+ let asker = MacroUserIdStr::try_from_email("[email protected]").unwrap();+ let transport = Arc::new(ActorTransport::default());+ let service = gated(+ prompted_by(Some(asker.clone())),+ SpyCredentials::unconnected(),+ )+ .with_actor_mcp(transport.clone());+ let grant = service.session_grant(AgentSessionId::new()).await.unwrap();+ let linear = McpDestination::Connected(McpServerSlug::parse("linear").unwrap());++ let listing = service+ .exchange_as(+ &grant,+ &asker,+ &linear,+ json!({"jsonrpc":"2.0","id":1,"method":"tools/list"}),+ )+ .await+ .unwrap();+ let call = service+ .exchange_as(+ &grant,+ &asker,+ &linear,+ json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"search","arguments":{}}}),+ )+ .await+ .unwrap();++ assert_eq!(listing["tools"][0]["name"], "search");+ assert_eq!(call["isError"], true);+ assert!(+ call["content"][0]["text"]+ .as_str()+ .unwrap()+ .contains("<m-connect-app>")+ );+ let asked = service.credentials.asked.lock().unwrap();+ assert_eq!(asked[0].0, owner().to_string());+ assert_eq!(asked[1].0, asker.to_string());+ assert_eq!(transport.0.lock().unwrap().len(), 1);+}++#[tokio::test]+async fn an_in_process_exchange_never_reaches_macro_or_preview() {+ let transport = Arc::new(ActorTransport::default());+ let service =+ gated(prompted_by(None), SpyCredentials::knowing()).with_actor_mcp(transport.clone());+ let grant = service.session_grant(AgentSessionId::new()).await.unwrap();++ for destination in [McpDestination::Macro, McpDestination::Preview] {+ let refused = service+ .exchange_as(+ &grant,+ &owner(),+ &destination,+ json!({"jsonrpc":"2.0","id":1,"method":"tools/list"}),+ )+ .await;+ assert!(matches!(refused, Err(EgressError::Unroutable(_))));+ }+ assert!(service.credentials.asked.lock().unwrap().is_empty());+ assert!(transport.0.lock().unwrap().is_empty());+}++#[tokio::test]+async fn an_in_process_owner_call_in_the_owners_turn_is_not_held() {+ let transport = Arc::new(ActorTransport::default());+ let service = gated(prompted_by(Some(owner())), SpyCredentials::knowing())+ .with_actor_mcp(transport.clone());+ let grant = service.session_grant(AgentSessionId::new()).await.unwrap();++ let result = service+ .exchange_as(+ &grant,+ &owner(),+ &McpDestination::Connected(McpServerSlug::parse("linear").unwrap()),+ json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"search","arguments":{"q":"x"}}}),+ )+ .await+ .unwrap();++ assert_eq!(result, json!({"content":[{"type":"text","text":"ok"}]}));+ assert!(service.approvals.held_in_process.lock().unwrap().is_empty());+ assert_eq!(transport.0.lock().unwrap().len(), 1);+}++#[tokio::test]+async fn an_in_process_owner_call_in_someone_elses_turn_runs_once_the_owner_approves() {+ let asker = MacroUserIdStr::try_from_email("[email protected]").unwrap();+ let transport = Arc::new(ActorTransport::default());+ let service = gated(prompted_by(Some(asker.clone())), SpyCredentials::knowing())+ .with_actor_mcp(transport.clone());+ *service.approvals.answer.lock().unwrap() =+ Some(agent_runtime_protocol::domain::tool_approval::ToolApprovalStatus::Approved);+ let grant = service.session_grant(AgentSessionId::new()).await.unwrap();++ let result = service+ .exchange_as(+ &grant,+ &owner(),+ &McpDestination::Connected(McpServerSlug::parse("linear").unwrap()),+ json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"search","arguments":{"q":"x"}}}),+ )+ .await+ .unwrap();++ assert_eq!(result, json!({"content":[{"type":"text","text":"ok"}]}));+ let held = service.approvals.held_in_process.lock().unwrap();+ assert_eq!(held.len(), 1);+ assert_eq!(held[0].server_slug, "linear");+ assert_eq!(held[0].tool_name, "search");+ assert_eq!(held[0].arguments, json!({"q":"x"}));+ assert_eq!(held[0].owner, owner());+ assert_eq!(held[0].prompter.acting_user(), Some(&asker));+ assert_eq!(transport.0.lock().unwrap().len(), 1);+}++#[tokio::test]+async fn an_in_process_owner_call_the_owner_declines_never_runs() {+ let asker = MacroUserIdStr::try_from_email("[email protected]").unwrap();+ let transport = Arc::new(ActorTransport::default());+ let service = gated(prompted_by(Some(asker)), SpyCredentials::knowing())+ .with_actor_mcp(transport.clone());+ *service.approvals.answer.lock().unwrap() =+ Some(agent_runtime_protocol::domain::tool_approval::ToolApprovalStatus::Denied);+ let grant = service.session_grant(AgentSessionId::new()).await.unwrap();++ let result = service+ .exchange_as(+ &grant,+ &owner(),+ &McpDestination::Connected(McpServerSlug::parse("linear").unwrap()),+ json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"search","arguments":{"q":"x"}}}),+ )+ .await+ .unwrap();++ assert_eq!(result["isError"], true);+ assert!(+ result["content"][0]["text"]+ .as_str()+ .unwrap()+ .contains("declined this call")+ );+ assert_eq!(service.approvals.held_in_process.lock().unwrap().len(), 1);+ assert!(transport.0.lock().unwrap().is_empty());+}diff --git a/crates/agent_egress/src/outbound/session_authority.rs b/crates/agent_egress/src/outbound/session_authority.rsindex b89ae0e490..8653482a43 100644--- a/crates/agent_egress/src/outbound/session_authority.rs+++ b/crates/agent_egress/src/outbound/session_authority.rs@@ -15,13 +15,19 @@//! digest also keeps the comparison in the index rather than in a Rust `==`//! over secret-derived bytes.+use agent_session::domain::model::AgentSession;use agent_session::domain::ports::AgentSessionRepo;-use agent_session::domain::{credentials::authenticate_session, error::AgentSessionError};+use agent_session::domain::{+ credentials::{authenticate_session, open_session},+ error::AgentSessionError,+};use model_owner::Owner;use tracing::Level;use crate::domain::error::EgressError;-use crate::domain::model::{McpServerListing, McpServerSlug, RepoSlug, SessionGrant, SessionToken};+use crate::domain::model::{+ AgentSessionId, McpServerListing, McpServerSlug, RepoSlug, SessionGrant, SessionToken,+};use crate::domain::ports::SessionAuthority;/// Resolves a presented session token to its session by the digest stored@@ -48,16 +54,41 @@ whereasync fn authorize(&self, token: &SessionToken) -> Result<SessionGrant, EgressError> {let session = authenticate_session(&self.sessions, &token.hash()).await- .map_err(|error| match error {- AgentSessionError::Forbidden => {- EgressError::Unauthenticated("unknown session token")- }- AgentSessionError::Disconnected(_) => EgressError::SessionClosed,- error => EgressError::Internal(rootcause::report!(- "could not authenticate session: {error}"- )),- })?;+ .map_err(authentication_error)?;+ self.grant(session).await+ }++ #[tracing::instrument(skip_all, err(level = Level::DEBUG), fields(%session))]+ async fn authorize_session(+ &self,+ session: AgentSessionId,+ ) -> Result<SessionGrant, EgressError> {+ let session = self+ .sessions+ .get(session)+ .await+ .and_then(open_session)+ .map_err(authentication_error)?;+ self.grant(session).await+ }+}+fn authentication_error(error: AgentSessionError) -> EgressError {+ match error {+ AgentSessionError::Forbidden => EgressError::Unauthenticated("unknown session token"),+ AgentSessionError::NotFound(_) => EgressError::Unauthenticated("unknown session"),+ AgentSessionError::Disconnected(_) => EgressError::SessionClosed,+ error => EgressError::Internal(rootcause::report!(+ "could not authenticate session: {error}"+ )),+ }+}++impl<Sessions> StoredTokenSessionAuthority<Sessions>+where+ Sessions: AgentSessionRepo,+{+ async fn grant(&self, session: AgentSession) -> Result<SessionGrant, EgressError> {// The grant is a person's: everything egress does, it does with the// owner's credentials, and a bot or team has none to spend. Refused// as an admission the token fails, in our own fixed words like everydiff --git a/crates/agent_harness/src/outbound/egress.rs b/crates/agent_harness/src/outbound/egress.rsindex 45e2f561b3..035a1ea01f 100644--- a/crates/agent_harness/src/outbound/egress.rs+++ b/crates/agent_harness/src/outbound/egress.rs@@ -60,9 +60,13 @@ whereself}+ /// The connected apps and custom servers a session with `selection` is+ /// given: the agent author's explicit list, or every app the owner+ /// connected. Code executions read this too, so a program reaches exactly+ /// the apps its agent was given.// Both runtime hosts use mcp_select's provider policy. This adapter only// loads owner-scoped rows and converts the result to proxy addresses.- async fn advertised_all(+ pub async fn advertised_all(&self,owner: &MacroUserIdStr<'static>,selection: &AgentMcpServers,diff --git a/crates/agent_inmem/src/outbound/approval_gate.rs b/crates/agent_inmem/src/outbound/approval_gate.rsindex 4b3ee7e87e..5ff351f81c 100644--- a/crates/agent_inmem/src/outbound/approval_gate.rs+++ b/crates/agent_inmem/src/outbound/approval_gate.rs@@ -8,7 +8,8 @@ use std::pin::Pin;use std::sync::Arc;use agent_egress::domain::approval::{- InProcessCall, MACRO_SERVER_SLUG, ToolApprovalService, refusal, spends_owner_access,+ InProcessCall, MACRO_SERVER_SLUG, OwnerApprovals, ToolApprovalService, refusal,+ spends_owner_access,};use agent_egress::domain::ports::{ToolApprovalAnnouncer, ToolApprovalSignals, ToolApprovalStore};use agent_session::domain::model::AgentSessionId;diff --git a/crates/agent_session/src/domain/credentials.rs b/crates/agent_session/src/domain/credentials.rsindex 17ab300e0c..b8e35bc313 100644--- a/crates/agent_session/src/domain/credentials.rs+++ b/crates/agent_session/src/domain/credentials.rs@@ -17,6 +17,12 @@ pub async fn authenticate_session<R: AgentSessionRepo>(.find_by_egress_token_hash(token_hash).await?.ok_or(AgentSessionError::Forbidden)?;+ open_session(session)+}++/// Refuse a session that has disconnected: its credentials stop working the+/// moment it closes.+pub fn open_session(session: AgentSession) -> Result<AgentSession> {if matches!(session.status,SessionStatus::Disconnected | SessionStatus::Event(SystemEvent::Disconnected)diff --git a/crates/ai_tools/src/search_tools.rs b/crates/ai_tools/src/search_tools.rsindex 2328540af9..9eb1c46268 100644--- a/crates/ai_tools/src/search_tools.rs+++ b/crates/ai_tools/src/search_tools.rs@@ -112,35 +112,10 @@ impl AsyncTool<ToolServiceContext> for LoadTools {// Pure logic (unit-testable without a service context)// ----------------------------------------------------------------------------/// Match `query` against `catalog`, ranked by relevance.-///-/// The query is split into whitespace-separated terms; a tool matches if **any**-/// term is a case-insensitive substring of its name or description, ranked by-/// how many distinct terms match (so "github list commits" surfaces the most-/// relevant tools first). All matches are returned — the caller decides how-/// many to load. An empty query returns the whole catalog.+/// Match `query` against `catalog`, ranked by relevance; see+/// [`ai_toolset::tool_search::rank`].fn search<'c>(catalog: &'c [SearchableTool], query: &str) -> Vec<&'c SearchableTool> {- let query = query.to_lowercase();- let terms: Vec<&str> = query.split_whitespace().collect();-- let mut scored: Vec<(usize, &SearchableTool)> = catalog- .iter()- .filter_map(|t| {- if terms.is_empty() {- return Some((0, t));- }- let haystack = format!("{} {}", t.name.to_lowercase(), t.description.to_lowercase());- let score = terms- .iter()- .filter(|term| haystack.contains(**term))- .count();- (score > 0).then_some((score, t))- })- .collect();- // Highest term-match count first; tie-break by name for stable ordering.- scored.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.name.cmp(&b.1.name)));-- scored.into_iter().map(|(_, t)| t).collect()+ ai_toolset::tool_search::rank(catalog, query, |tool| (&tool.name, &tool.description))}/// Match `query`, auto-load the top [`MAX_AUTO_LOADED_MATCHES`] matches so theydiff --git a/crates/ai_tools/src/test.rs b/crates/ai_tools/src/test.rsindex 2ba04b1b7c..b94d598d0a 100644--- a/crates/ai_tools/src/test.rs+++ b/crates/ai_tools/src/test.rs@@ -705,6 +705,8 @@ fn code_mode_retains_direct_lifecycles_and_hides_sdk_methods_from_lazy_discovery"NameSearch","ListEntities","ContentSearch",+ "DiscoverConnectors",+ "ConnectMcpServer",] {assert!(standard.toolset.tools.contains_key(name), "{name}");assert!(sdk.tools.contains_key(name), "{name}");@@ -727,7 +729,6 @@ fn code_mode_retains_direct_lifecycles_and_hides_sdk_methods_from_lazy_discovery"Subagent","SearchTools","LoadTools",- "DiscoverConnectors","BashCodeExecution","TextEditorCodeExecution",] {diff --git a/crates/ai_toolset/src/tool_search.rs b/crates/ai_toolset/src/tool_search.rsindex e92b430fa6..ddf6383b9c 100644--- a/crates/ai_toolset/src/tool_search.rs+++ b/crates/ai_toolset/src/tool_search.rs@@ -20,6 +20,41 @@ pub const SEARCH_TOOLS: &str = "SearchTools";/// The name of the tool that loads catalog tools by name.pub const LOAD_TOOLS: &str = "LoadTools";+/// Match `query` against `catalog`, ranked by relevance.+///+/// The query is split into whitespace-separated terms; an item matches if+/// **any** term is a case-insensitive substring of its name or description,+/// ranked by how many distinct terms match (so "github list commits" surfaces+/// the most relevant tools first), ties by name. An empty query matches+/// everything. `text` reads an item's name and description.+pub fn rank<'c, Item>(+ catalog: &'c [Item],+ query: &str,+ text: impl Fn(&Item) -> (&str, &str),+) -> Vec<&'c Item> {+ let query = query.to_lowercase();+ let terms: Vec<&str> = query.split_whitespace().collect();++ let mut scored: Vec<(usize, &str, &Item)> = catalog+ .iter()+ .filter_map(|item| {+ let (name, description) = text(item);+ if terms.is_empty() {+ return Some((0, name, item));+ }+ let haystack = format!("{} {}", name.to_lowercase(), description.to_lowercase());+ let score = terms+ .iter()+ .filter(|term| haystack.contains(**term))+ .count();+ (score > 0).then_some((score, name, item))+ })+ .collect();+ scored.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(b.1)));++ scored.into_iter().map(|(_, _, item)| item).collect()+}+/// A tool that is loaded on demand via tool search rather than sent on every/// request. The catalog of these is returned by/// [`ToolSet::searchable_catalog`](crate::ToolSet::searchable_catalog) and readdiff --git a/crates/mcp_client/src/inbound/toolset.rs b/crates/mcp_client/src/inbound/toolset.rsindex 83c9bd78aa..f9093e12e6 100644--- a/crates/mcp_client/src/inbound/toolset.rs+++ b/crates/mcp_client/src/inbound/toolset.rs@@ -56,7 +56,7 @@ where}/// Add a custom MCP server to the user's connections.-#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[derive(Debug, Clone, Deserialize, JsonSchema, utoipa::ToSchema)]#[serde(rename_all = "camelCase")]#[schemars(title = "ConnectMcpServer",@@ -80,7 +80,7 @@ impl ToolAnnotated for ConnectMcpServer {}/// Response from [`ConnectMcpServer`].-#[derive(Debug, Serialize, JsonSchema)]+#[derive(Debug, Serialize, JsonSchema, utoipa::ToSchema)]#[serde(rename_all = "camelCase")]pub struct ConnectMcpServerResponse {/// The server's URL.diff --git a/crates/pipedream_mcp/src/domain/service/discovery.rs b/crates/pipedream_mcp/src/domain/service/discovery.rsindex 6b41ddc741..27ab150507 100644--- a/crates/pipedream_mcp/src/domain/service/discovery.rs+++ b/crates/pipedream_mcp/src/domain/service/discovery.rs@@ -17,7 +17,7 @@ mod test;const MAX_TOOLS: usize = 100;/// Search by app name, then inspect a returned slug before recommending auth.-#[derive(Debug, Deserialize, JsonSchema)]+#[derive(Debug, Serialize, Deserialize, JsonSchema, utoipa::ToSchema)]#[serde(tag = "operation", rename_all = "snake_case")]pub enum DiscoveryRequest {/// Find connectable apps by name.@@ -33,7 +33,7 @@ pub enum DiscoveryRequest {}/// An advertised action, not a tool loaded into the current turn.-#[derive(Debug, Serialize, JsonSchema)]+#[derive(Debug, Serialize, JsonSchema, utoipa::ToSchema)]pub struct ConnectorTool {/// Upstream tool name.pub name: String,@@ -42,7 +42,7 @@ pub struct ConnectorTool {}/// A verified app identity from the directory.-#[derive(Debug, Serialize, JsonSchema)]+#[derive(Debug, Serialize, JsonSchema, utoipa::ToSchema)]pub struct DiscoveredApp {/// Exact identity to inspect or connect.pub app_slug: String,@@ -53,7 +53,7 @@ pub struct DiscoveredApp {}/// Discovery results never execute tools or change connections.-#[derive(Debug, Serialize, JsonSchema)]+#[derive(Debug, Serialize, JsonSchema, utoipa::ToSchema)]#[serde(tag = "operation", rename_all = "snake_case")]pub enum DiscoveryResult {/// Candidate apps; none has had its capabilities verified yet.diff --git a/crates/pipedream_mcp/src/inbound/toolset.rs b/crates/pipedream_mcp/src/inbound/toolset.rsindex 663c000fe9..382eb25389 100644--- a/crates/pipedream_mcp/src/inbound/toolset.rs+++ b/crates/pipedream_mcp/src/inbound/toolset.rs@@ -42,7 +42,7 @@ pub struct DiscoverConnectors {}/// Discovery metadata and optional markup for a user-controlled auth flow.-#[derive(Debug, Serialize, JsonSchema)]+#[derive(Debug, Serialize, JsonSchema, utoipa::ToSchema)]pub struct DiscoverConnectorsResponse {/// Catalog or capability results.pub result: DiscoveryResult,@@ -77,6 +77,14 @@ wheredescription: error.to_string(),internal_error: error,})?;+ Ok(DiscoverConnectorsResponse::from(result))+ }+}++impl From<DiscoveryResult> for DiscoverConnectorsResponse {+ /// Offer connect markup only for an unconnected app whose inspected tools+ /// could do something.+ fn from(result: DiscoveryResult) -> Self {let connect_markup = match &result {DiscoveryResult::Inspect {app,@@ -89,9 +97,9 @@ where}_ => None,};- Ok(DiscoverConnectorsResponse {+ Self {result,connect_markup,- })+ }}}diff --git a/crates/prompt/src/agent_session.rs b/crates/prompt/src/agent_session.rsindex 4f38c95b78..8bff043386 100644--- a/crates/prompt/src/agent_session.rs+++ b/crates/prompt/src/agent_session.rs@@ -11,7 +11,7 @@ You are Macro's agent. Your replies render in the session; when the session was- Answer user messages directly; use your tools to look things up or act in the workspace when that is what the request needs. Be correctness-obsessed, precise, and confident.- Always use Markdown for formatting.- When you reference a Macro document, channel, chat, project, task, email thread, calendar event, person, date/time, agent session, or other mentionable chip, emit the matching XML mention tag (see the mentioning rules). Those tags render as clickable chips in the session and in the channel thread. Do not use plain Markdown links or bare names for Macro items.-- When a request needs an external app (for example, "import my Datadog logs"), use SearchTools for its actions. If the app is missing or a workflow needs an unconnected account, use DiscoverConnectors to search for the app and inspect its actual capabilities and connection status. This also applies when a native import tool exists but requires that app's connection. For a suitable unconnected app, include the returned connect_markup and tell the owner to connect to continue; do not substitute instructions to find Settings or ask for document URLs before resolving the missing connection. After authorization the session resumes automatically, and SearchTools can load the refreshed tools. Never claim an app supports an action merely because its name matches.+- When a request needs an external app (for example, "import my Datadog logs"), use SearchTools for its actions. If the app is missing or a workflow needs an unconnected account, search for the app and inspect its actual capabilities and connection status with DiscoverConnectors, or `macro.connectedApps.discover` in code mode. This also applies when a native import tool exists but requires that app's connection. For a suitable unconnected app, include the returned connect_markup and tell the owner to connect to continue; do not substitute instructions to find Settings or ask for document URLs before resolving the missing connection. After authorization the session resumes automatically, and SearchTools can load the refreshed tools. Never claim an app supports an action merely because its name matches.- Work autonomously: nobody can approve intermediate questions mid-turn, so make reasonable assumptions, state them briefly, and proceed.## Tone and Stylediff --git a/packages/code-mode-sdk/scripts/catalog.ts b/packages/code-mode-sdk/scripts/catalog.tsindex ec2277ebd1..be6527b4f3 100644--- a/packages/code-mode-sdk/scripts/catalog.ts+++ b/packages/code-mode-sdk/scripts/catalog.ts@@ -18,6 +18,7 @@ export const entityDirectories: readonly string[] = ['calendar','calls','channels',+ 'connected-apps','crm','databases','documents',@@ -26,7 +27,6 @@ export const entityDirectories: readonly string[] = ['foreign','forms','notifications',- 'pins','projects','properties','referrals',diff --git a/packages/code-mode-sdk/scripts/typedoc.ts b/packages/code-mode-sdk/scripts/typedoc.tsindex 99e23207e6..4349940b4b 100644--- a/packages/code-mode-sdk/scripts/typedoc.ts+++ b/packages/code-mode-sdk/scripts/typedoc.ts@@ -87,9 +87,9 @@ export function packageEntityDocs(letter.toUpperCase()),// Agent and host setup share one discovery topic, as do AI calls and- // image generation, searching, browsing and AI chats, and the web and- // URL previews, keeping the classifier request within its 32-question- // contract as the public API grows.+ // image generation, searching, browsing and AI chats, the web and URL+ // previews, and favorites and pins, keeping the classifier request+ // within its 32-question contract as the public API grows.prefixes: (directory === 'agents'? ['agents', 'harnesses']: directory === 'channels'@@ -102,7 +102,9 @@ export function packageEntityDocs(? ['search', 'workspace', 'chats']: directory === 'web'? ['web', 'unfurls']- : [directory]+ : directory === 'favorites'+ ? ['favorites', 'pins']+ : [directory]).map((value) => `src/entities/${value}/`),})),{ name: 'core', prefixes: core },diff --git a/packages/sdk/AGENTS.md b/packages/sdk/AGENTS.mdindex cc46aa9c23..1f1e11e33a 100644--- a/packages/sdk/AGENTS.md+++ b/packages/sdk/AGENTS.md@@ -31,6 +31,13 @@ enforced by the ordinary backend APIs.`PipelineTable.views()` returns views whose `positions()` reads saved board order.- `src/entities/external-chat/`: added provider chats (`macro.externalChats`, entity type`external_chat`) and their message/send/upload/participant handles.+- `src/entities/connected-apps/`: `macro.connectedApps.list(execution)` returns the+ connected apps and custom MCP servers a running code execution's session+ agent was given; `app.tools()` and `tool.call(args)` go through the harness,+ which stamps the credential and holds each owner-account call in a turn+ someone else prompted for the owner's approval. `discover(execution, name)`+ and `Connector.inspect()` mirror `DiscoverConnectors`; `addServer` mirrors+ `ConnectMcpServer`. Only works inside a running execution.- `src/entities/whatsapp/`: the owner's WhatsApp account and chat list; `WhatsAppChat.add()`returns an `ExternalChat`.- `src/entities/me/`: `macro.me.update()` sets the caller's name and profilediff --git a/packages/sdk/generated/agent-harness/index.ts b/packages/sdk/generated/agent-harness/index.tsindex b6bfe18c4a..b1e4e4244a 100644--- a/packages/sdk/generated/agent-harness/index.ts+++ b/packages/sdk/generated/agent-harness/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessLevel, AgentAction, AgentActionId, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentConversationDto, AgentConversationsDto, AgentConversationSessionDto, AgentConversationTurnDto, AgentMode, AgentModeChoiceRequest, AgentModeChoiceResponse, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionFoldedLogResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSessionsForPullRequestData, AgentSessionsForPullRequestError, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponse, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsError, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponse, AgentSessionsForPullRequestsResponses, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, AiSuggestions, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalError, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponse, AnswerAgentSessionToolApprovalResponses, AnswerToolApprovalRequest, AnswerToolApprovalResponse, AppConnectedRequest, ArchiveCause, AutoArchiveOverridesBody, AutoArchivePreferencesBody, BotId, CalendarSuggestions, CallSearchSuggestions, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSearchSuggestions, ChannelSharePermission, ChooseAgentModeData, ChooseAgentModeErrors, ChooseAgentModeResponse, ChooseAgentModeResponses, ClassifyData, ClassifyErrors, ClassifyInputRequest, ClassifyInputResponse, ClassifyResponse, ClassifyResponses, ClientOptions, CodingPreferencesBody, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, ConversationTurnState, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateReview, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponse, CreateSessionReviewResponses, CreateSessionThread, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponse, DecideSessionReviewResponses, DecisionVia, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmailSearchSuggestions, EmailSuggestions, ExecutionActivity, ExecutionId, ExecutionRecord, ExecutionStatus, ExternalSessionResponse, ExtractData, ExtractErrors, ExtractInputRequest, ExtractInputResponse, ExtractResponse, ExtractResponses, FileChangeKindDto, GetAgentAutoArchivePreferencesData, GetAgentAutoArchivePreferencesError, GetAgentAutoArchivePreferencesErrors, GetAgentAutoArchivePreferencesResponse, GetAgentAutoArchivePreferencesResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesError, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponse, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionAutoArchiveData, GetAgentSessionAutoArchiveError, GetAgentSessionAutoArchiveErrors, GetAgentSessionAutoArchiveResponse, GetAgentSessionAutoArchiveResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionFoldedLogData, GetAgentSessionFoldedLogError, GetAgentSessionFoldedLogErrors, GetAgentSessionFoldedLogResponse, GetAgentSessionFoldedLogResponses, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponse, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponse, GetSessionReviewResponses, GitRefDto, InputIntent, InputPropertyDefinition, InputPropertySuggestion, InputSuggestions, IntentScore, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestError, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponse, LinkAgentSessionPullRequestResponses, LinkShare, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponse, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsError, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponse, ListAgentSessionPullRequestsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponse, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, MessageSuggestions, ModelHarnessDto, MonthlyWeekday, NoteSuggestions, PermissionAnswer, PresentSessionViewData, PresentSessionViewErrors, PresentSessionViewResponse, PresentSessionViewResponses, PresentView, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PullRequestLinkedSession, PullRequestLinkSource, PullRequestSessions, PullRequestSessionsResponse, PullRequestsSessionsResponse, PullRequestUrl, PullRequestUrls, PutAgentAutoArchivePreferencesData, PutAgentAutoArchivePreferencesError, PutAgentAutoArchivePreferencesErrors, PutAgentAutoArchivePreferencesResponse, PutAgentAutoArchivePreferencesResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesError, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponse, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionAutoArchiveData, PutAgentSessionAutoArchiveError, PutAgentSessionAutoArchiveErrors, PutAgentSessionAutoArchiveResponse, PutAgentSessionAutoArchiveResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QuerySearchSuggestions, QueuedActionDto, RecordedCallStatus, RecordedToolCall, RecurrenceEnd, RecurrenceFrequency, RecurrenceSuggestion, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, ReportAgentSessionAppConnectedData, ReportAgentSessionAppConnectedError, ReportAgentSessionAppConnectedErrors, ReportAgentSessionAppConnectedResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnRequest, RetryAgentConversationTurnResponse, RetryAgentConversationTurnResponses, ReviewDecision, ReviewDecisionContext, ReviewId, ReviewRecord, SandboxSize, SandboxSizeBody, SearchSuggestions, SearchType, SessionAutoArchiveResponse, SessionBot, SessionPullRequestLink, SessionPullRequestsResponse, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationRequest, StartFreshAgentConversationResponse, StartFreshAgentConversationResponses, SteerQueuedActionData, SteerQueuedActionError, SteerQueuedActionErrors, SteerQueuedActionResponse, SteerQueuedActionResponses, TaskSearchSuggestions, TaskSuggestions, ToolActor, ToolApprovalAnswerDto, ToolApprovalStatusDto, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestError, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponse, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponse, WarmAgentSessionHandlerResponses, WarmAgentSessionRequest, WarmAgentSessionResponse, WeekdayCode, WithAgentSessionId } from './types.gen';+export type { AccessLevel, AddConnectedMcpServerData, AddConnectedMcpServerErrors, AddConnectedMcpServerResponse, AddConnectedMcpServerResponses, AgentAction, AgentActionId, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentConversationDto, AgentConversationsDto, AgentConversationSessionDto, AgentConversationTurnDto, AgentMode, AgentModeChoiceRequest, AgentModeChoiceResponse, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionFoldedLogResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSessionsForPullRequestData, AgentSessionsForPullRequestError, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponse, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsError, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponse, AgentSessionsForPullRequestsResponses, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, AiSuggestions, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalError, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponse, AnswerAgentSessionToolApprovalResponses, AnswerToolApprovalRequest, AnswerToolApprovalResponse, AppConnectedRequest, ArchiveCause, AutoArchiveOverridesBody, AutoArchivePreferencesBody, BotId, CalendarSuggestions, CallConnectedAppToolData, CallConnectedAppToolErrors, CallConnectedAppToolResponse, CallConnectedAppToolResponses, CallConnectedTool, CallSearchSuggestions, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSearchSuggestions, ChannelSharePermission, ChooseAgentModeData, ChooseAgentModeErrors, ChooseAgentModeResponse, ChooseAgentModeResponses, ClassifyData, ClassifyErrors, ClassifyInputRequest, ClassifyInputResponse, ClassifyResponse, ClassifyResponses, ClientOptions, CodingPreferencesBody, ConnectedApp, ConnectedAppKind, ConnectedTool, ConnectedToolMatch, ConnectedToolResult, ConnectedToolSearch, ConnectMcpServer, ConnectMcpServerResponse, ConnectorTool, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, ConversationTurnState, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateReview, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponse, CreateSessionReviewResponses, CreateSessionThread, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponse, DecideSessionReviewResponses, DecisionVia, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, DiscoverConnectedAppsData, DiscoverConnectedAppsErrors, DiscoverConnectedAppsResponse, DiscoverConnectedAppsResponses, DiscoverConnectorsResponse, DiscoveredApp, DiscoveryRequest, DiscoveryResult, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmailSearchSuggestions, EmailSuggestions, ExecutionActivity, ExecutionId, ExecutionRecord, ExecutionStatus, ExternalSessionResponse, ExtractData, ExtractErrors, ExtractInputRequest, ExtractInputResponse, ExtractResponse, ExtractResponses, FileChangeKindDto, GetAgentAutoArchivePreferencesData, GetAgentAutoArchivePreferencesError, GetAgentAutoArchivePreferencesErrors, GetAgentAutoArchivePreferencesResponse, GetAgentAutoArchivePreferencesResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesError, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponse, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionAutoArchiveData, GetAgentSessionAutoArchiveError, GetAgentSessionAutoArchiveErrors, GetAgentSessionAutoArchiveResponse, GetAgentSessionAutoArchiveResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionFoldedLogData, GetAgentSessionFoldedLogError, GetAgentSessionFoldedLogErrors, GetAgentSessionFoldedLogResponse, GetAgentSessionFoldedLogResponses, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponse, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponse, GetSessionReviewResponses, GitRefDto, InputIntent, InputPropertyDefinition, InputPropertySuggestion, InputSuggestions, IntentScore, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestError, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponse, LinkAgentSessionPullRequestResponses, LinkShare, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponse, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsError, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponse, ListAgentSessionPullRequestsResponses, ListConnectedAppToolsData, ListConnectedAppToolsErrors, ListConnectedAppToolsResponse, ListConnectedAppToolsResponses, ListExecutionConnectedAppsData, ListExecutionConnectedAppsErrors, ListExecutionConnectedAppsResponse, ListExecutionConnectedAppsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponse, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, MessageSuggestions, ModelHarnessDto, MonthlyWeekday, NoteSuggestions, PermissionAnswer, PresentSessionViewData, PresentSessionViewErrors, PresentSessionViewResponse, PresentSessionViewResponses, PresentView, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PullRequestLinkedSession, PullRequestLinkSource, PullRequestSessions, PullRequestSessionsResponse, PullRequestsSessionsResponse, PullRequestUrl, PullRequestUrls, PutAgentAutoArchivePreferencesData, PutAgentAutoArchivePreferencesError, PutAgentAutoArchivePreferencesErrors, PutAgentAutoArchivePreferencesResponse, PutAgentAutoArchivePreferencesResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesError, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponse, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionAutoArchiveData, PutAgentSessionAutoArchiveError, PutAgentSessionAutoArchiveErrors, PutAgentSessionAutoArchiveResponse, PutAgentSessionAutoArchiveResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QuerySearchSuggestions, QueuedActionDto, RecordedCallStatus, RecordedToolCall, RecurrenceEnd, RecurrenceFrequency, RecurrenceSuggestion, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, ReportAgentSessionAppConnectedData, ReportAgentSessionAppConnectedError, ReportAgentSessionAppConnectedErrors, ReportAgentSessionAppConnectedResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnRequest, RetryAgentConversationTurnResponse, RetryAgentConversationTurnResponses, ReviewDecision, ReviewDecisionContext, ReviewId, ReviewRecord, SandboxSize, SandboxSizeBody, SearchConnectedAppToolsData, SearchConnectedAppToolsErrors, SearchConnectedAppToolsResponse, SearchConnectedAppToolsResponses, SearchSuggestions, SearchType, SessionAutoArchiveResponse, SessionBot, SessionPullRequestLink, SessionPullRequestsResponse, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationRequest, StartFreshAgentConversationResponse, StartFreshAgentConversationResponses, SteerQueuedActionData, SteerQueuedActionError, SteerQueuedActionErrors, SteerQueuedActionResponse, SteerQueuedActionResponses, TaskSearchSuggestions, TaskSuggestions, ToolActor, ToolApprovalAnswerDto, ToolApprovalStatusDto, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestError, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponse, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponse, WarmAgentSessionHandlerResponses, WarmAgentSessionRequest, WarmAgentSessionResponse, WeekdayCode, WithAgentSessionId } from './types.gen';diff --git a/packages/sdk/generated/agent-harness/sdk.gen.ts b/packages/sdk/generated/agent-harness/sdk.gen.tsindex 020fa89e35..e2e122e7ae 100644--- a/packages/sdk/generated/agent-harness/sdk.gen.ts+++ b/packages/sdk/generated/agent-harness/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { AgentSessionsForPullRequestData, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponses, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponses, ChooseAgentModeData, ChooseAgentModeErrors, ChooseAgentModeResponses, ClassifyData, ClassifyErrors, ClassifyResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponses, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, ExtractData, ExtractErrors, ExtractResponses, GetAgentAutoArchivePreferencesData, GetAgentAutoArchivePreferencesErrors, GetAgentAutoArchivePreferencesResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionAutoArchiveData, GetAgentSessionAutoArchiveErrors, GetAgentSessionAutoArchiveResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionFoldedLogData, GetAgentSessionFoldedLogErrors, GetAgentSessionFoldedLogResponses, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponses, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponses, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PresentSessionViewData, PresentSessionViewErrors, PresentSessionViewResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentAutoArchivePreferencesData, PutAgentAutoArchivePreferencesErrors, PutAgentAutoArchivePreferencesResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionAutoArchiveData, PutAgentSessionAutoArchiveErrors, PutAgentSessionAutoArchiveResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, ReportAgentSessionAppConnectedData, ReportAgentSessionAppConnectedErrors, ReportAgentSessionAppConnectedResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnResponses, SetAgentSessionArchivedData, SetAgentSessionArchivedErrors, SetAgentSessionArchivedResponses, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationResponses, SteerQueuedActionData, SteerQueuedActionErrors, SteerQueuedActionResponses, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponses, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponses } from './types.gen';+import type { AddConnectedMcpServerData, AddConnectedMcpServerErrors, AddConnectedMcpServerResponses, AgentSessionsForPullRequestData, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponses, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponses, CallConnectedAppToolData, CallConnectedAppToolErrors, CallConnectedAppToolResponses, ChooseAgentModeData, ChooseAgentModeErrors, ChooseAgentModeResponses, ClassifyData, ClassifyErrors, ClassifyResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponses, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponses, DiscoverConnectedAppsData, DiscoverConnectedAppsErrors, DiscoverConnectedAppsResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, ExtractData, ExtractErrors, ExtractResponses, GetAgentAutoArchivePreferencesData, GetAgentAutoArchivePreferencesErrors, GetAgentAutoArchivePreferencesResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionAutoArchiveData, GetAgentSessionAutoArchiveErrors, GetAgentSessionAutoArchiveResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionFoldedLogData, GetAgentSessionFoldedLogErrors, GetAgentSessionFoldedLogResponses, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponses, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponses, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponses, ListConnectedAppToolsData, ListConnectedAppToolsErrors, ListConnectedAppToolsResponses, ListExecutionConnectedAppsData, ListExecutionConnectedAppsErrors, ListExecutionConnectedAppsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PresentSessionViewData, PresentSessionViewErrors, PresentSessionViewResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentAutoArchivePreferencesData, PutAgentAutoArchivePreferencesErrors, PutAgentAutoArchivePreferencesResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionAutoArchiveData, PutAgentSessionAutoArchiveErrors, PutAgentSessionAutoArchiveResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, ReportAgentSessionAppConnectedData, ReportAgentSessionAppConnectedErrors, ReportAgentSessionAppConnectedResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnResponses, SearchConnectedAppToolsData, SearchConnectedAppToolsErrors, SearchConnectedAppToolsResponses, SetAgentSessionArchivedData, SetAgentSessionArchivedErrors, SetAgentSessionArchivedResponses, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationResponses, SteerQueuedActionData, SteerQueuedActionErrors, SteerQueuedActionResponses, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponses, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -412,6 +412,69 @@ export class Sdk extends HeyApiClient {return (options.client ?? this.client).get<GetCodeExecutionResponses, GetCodeExecutionErrors, ThrowOnError>({ url: '/agent-sessions/{session_id}/code-executions/{execution_id}', ...options });}+ /**+ * List the connected apps and custom MCP servers the session's agent may use.+ */+ public listExecutionConnectedApps<ThrowOnError extends boolean = false>(options: Options<ListExecutionConnectedAppsData, ThrowOnError>): RequestResult<ListExecutionConnectedAppsResponses, ListExecutionConnectedAppsErrors, ThrowOnError> {+ return (options.client ?? this.client).get<ListExecutionConnectedAppsResponses, ListExecutionConnectedAppsErrors, ThrowOnError>({ url: '/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps', ...options });+ }++ /**+ * Search the connectable app catalog, or inspect one app's tools and connection status.+ */+ public discoverConnectedApps<ThrowOnError extends boolean = false>(options: Options<DiscoverConnectedAppsData, ThrowOnError>): RequestResult<DiscoverConnectedAppsResponses, DiscoverConnectedAppsErrors, ThrowOnError> {+ return (options.client ?? this.client).post<DiscoverConnectedAppsResponses, DiscoverConnectedAppsErrors, ThrowOnError>({+ url: '/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/discover',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }++ /**+ * Add a custom MCP server to the execution account's connections.+ */+ public addConnectedMcpServer<ThrowOnError extends boolean = false>(options: Options<AddConnectedMcpServerData, ThrowOnError>): RequestResult<AddConnectedMcpServerResponses, AddConnectedMcpServerErrors, ThrowOnError> {+ return (options.client ?? this.client).post<AddConnectedMcpServerResponses, AddConnectedMcpServerErrors, ThrowOnError>({+ url: '/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/servers',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }++ /**+ * Find tools across the agent's connected apps by keywords.+ */+ public searchConnectedAppTools<ThrowOnError extends boolean = false>(options: Options<SearchConnectedAppToolsData, ThrowOnError>): RequestResult<SearchConnectedAppToolsResponses, SearchConnectedAppToolsErrors, ThrowOnError> {+ return (options.client ?? this.client).get<SearchConnectedAppToolsResponses, SearchConnectedAppToolsErrors, ThrowOnError>({ url: '/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/tools', ...options });+ }++ /**+ * Call one tool of a connected app as the execution's account.+ */+ public callConnectedAppTool<ThrowOnError extends boolean = false>(options: Options<CallConnectedAppToolData, ThrowOnError>): RequestResult<CallConnectedAppToolResponses, CallConnectedAppToolErrors, ThrowOnError> {+ return (options.client ?? this.client).post<CallConnectedAppToolResponses, CallConnectedAppToolErrors, ThrowOnError>({+ url: '/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/{kind}/{key}/calls',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }++ /**+ * List the tools one connected app serves.+ */+ public listConnectedAppTools<ThrowOnError extends boolean = false>(options: Options<ListConnectedAppToolsData, ThrowOnError>): RequestResult<ListConnectedAppToolsResponses, ListConnectedAppToolsErrors, ThrowOnError> {+ return (options.client ?? this.client).get<ListConnectedAppToolsResponses, ListConnectedAppToolsErrors, ThrowOnError>({ url: '/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/{kind}/{key}/tools', ...options });+ }+/*** List blocks created during an execution, including interrupted executions.*/diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.tsindex 8ffdc9e9ca..705365920f 100644--- a/packages/sdk/generated/agent-harness/types.gen.ts+++ b/packages/sdk/generated/agent-harness/types.gen.ts@@ -775,6 +775,22 @@ export type CalendarSuggestions = {title?: string | null;};+/**+ * Call one tool of a connected app.+ */+export type CallConnectedTool = {+ /**+ * The tool's arguments, matching its input schema.+ */+ arguments?: {+ [key: string]: unknown;+ };+ /**+ * The tool's name on its server.+ */+ tool: string;+};+/*** Call search supports speakers, channels and attendance status.*/@@ -996,6 +1012,158 @@ export type CodingPreferencesBody = {openPullRequests: boolean;};+/**+ * Add a custom MCP server to the user's connections.+ */+export type ConnectMcpServer = {+ /**+ * Display name for the server.+ */+ serverName: string;+ /**+ * The server's URL.+ */+ url: string;+};++/**+ * Response from [`ConnectMcpServer`].+ */+export type ConnectMcpServerResponse = {+ /**+ * Whether the user already had this server before the call.+ */+ alreadyConnected: boolean;+ /**+ * Whether the server holds the user's sign-in.+ */+ authenticated: boolean;+ /**+ * Whether the server's tools are turned on.+ */+ enabled: boolean;+ /**+ * The server's display name.+ */+ serverName: string;+ /**+ * What happened and what the user still has to do.+ */+ summary: string;+ /**+ * The server's URL.+ */+ url: string;+};++/**+ * A connected app the session's agent may use.+ */+export type ConnectedApp = {+ /**+ * The app's slug, or its custom server key.+ */+ key: string;+ /**+ * Which store the app comes from.+ */+ kind: ConnectedAppKind;+ /**+ * Display name, e.g. `Slack` or the owner's name for a custom server.+ */+ name: string;+};++/**+ * Which store a connected app comes from.+ */+export type ConnectedAppKind = 'app' | 'custom';++/**+ * One tool a connected app serves.+ */+export type ConnectedTool = {+ /**+ * What the server says the tool does.+ */+ description?: string | null;+ /**+ * JSON Schema for the tool's arguments.+ */+ inputSchema: {+ [key: string]: unknown;+ };+ /**+ * The tool's name on its server.+ */+ name: string;+};++/**+ * One tool found by a search across the agent's connected apps.+ */+export type ConnectedToolMatch = {+ /**+ * The app serving the tool.+ */+ app: ConnectedApp;+ /**+ * The tool.+ */+ tool: ConnectedTool;+};++/**+ * A connected tool's answer: MCP's `CallToolResult`.+ */+export type ConnectedToolResult = {+ /**+ * MCP content blocks, e.g. `{type: "text", text}`.+ */+ content: Array<{+ [key: string]: unknown;+ }>;+ /**+ * The tool failed, or could not run; `content` says why.+ */+ isError: boolean;+ /**+ * Structured output, for tools that declare an output schema.+ */+ structuredContent?: {+ [key: string]: unknown;+ } | null;+};++/**+ * The best matches across the agent's connected apps, and the apps whose+ * tools could not be listed, which the search did not cover.+ */+export type ConnectedToolSearch = {+ /**+ * At most [`MAX_TOOL_MATCHES`] tools, best first.+ */+ matches: Array<ConnectedToolMatch>;+ /**+ * Apps whose tools could not be listed.+ */+ unsearched: Array<ConnectedApp>;+};++/**+ * An advertised action, not a tool loaded into the current turn.+ */+export type ConnectorTool = {+ /**+ * What the action supports.+ */+ description: string;+ /**+ * Upstream tool name.+ */+ name: string;+};+/*** Request body for a control operation on a live session.*@@ -1233,6 +1401,90 @@ export type DiscoverAgentCapabilitiesResponse = {configOptions: Array<AgentConfigOptionDto>;};+/**+ * Discovery metadata and optional markup for a user-controlled auth flow.+ */+export type DiscoverConnectorsResponse = {+ /**+ * Include verbatim only if an advertised tool supports the requested task.+ */+ connect_markup?: string | null;+ /**+ * Catalog or capability results.+ */+ result: DiscoveryResult;+};++/**+ * A verified app identity from the directory.+ */+export type DiscoveredApp = {+ /**+ * Exact identity to inspect or connect.+ */+ app_slug: string;+ /**+ * Directory description; inspect tools to verify specific capabilities.+ */+ description?: string | null;+ /**+ * Human-readable app name.+ */+ name: string;+};++/**+ * Search by app name, then inspect a returned slug before recommending auth.+ */+export type DiscoveryRequest = {+ operation: 'search';+ /**+ * App name, e.g. "Notion" or "Linear", not a task description.+ */+ query: string;+} | {+ /**+ * Exact app slug from search results.+ */+ app_slug: string;+ operation: 'inspect';+};++/**+ * Discovery results never execute tools or change connections.+ */+export type DiscoveryResult = {+ /**+ * Matching apps.+ */+ apps: Array<DiscoveredApp>;+ /**+ * Narrow the app name if this is true.+ */+ more_results: boolean;+ operation: 'search';+} | {+ /**+ * App from the directory.+ */+ app: DiscoveredApp;+ /**+ * Whether this caller has an enabled connection. For an app that+ * connects through its own MCP server, that connection is checked+ * there, not in Pipedream.+ */+ connected: boolean;+ operation: 'inspect';+ /**+ * Advertised tools. Use SearchTools after connecting to load them.+ */+ tools: Array<ConnectorTool>;+ /**+ * True when some advertised tools were omitted.+ */+ tools_truncated: boolean;+};+/*** A validated document identifier. Historical document ids need not be UUIDs.*/@@ -3263,6 +3515,153 @@ export type GetCodeExecutionResponses = {export type GetCodeExecutionResponse = GetCodeExecutionResponses[keyof GetCodeExecutionResponses];+export type ListExecutionConnectedAppsData = {+ body?: never;+ path: {+ session_id: string;+ /**+ * A running execution of the session's current turn+ */+ execution_id: string;+ };+ query?: never;+ url: '/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps';+};++export type ListExecutionConnectedAppsErrors = {+ 403: unknown;+ 404: unknown;+};++export type ListExecutionConnectedAppsResponses = {+ 200: Array<ConnectedApp>;+};++export type ListExecutionConnectedAppsResponse = ListExecutionConnectedAppsResponses[keyof ListExecutionConnectedAppsResponses];++export type DiscoverConnectedAppsData = {+ body: DiscoveryRequest;+ path: {+ session_id: string;+ execution_id: string;+ };+ query?: never;+ url: '/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/discover';+};++export type DiscoverConnectedAppsErrors = {+ 400: unknown;+ 403: unknown;+ 404: unknown;+};++export type DiscoverConnectedAppsResponses = {+ 200: DiscoverConnectorsResponse;+};++export type DiscoverConnectedAppsResponse = DiscoverConnectedAppsResponses[keyof DiscoverConnectedAppsResponses];++export type AddConnectedMcpServerData = {+ body: ConnectMcpServer;+ path: {+ session_id: string;+ execution_id: string;+ };+ query?: never;+ url: '/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/servers';+};++export type AddConnectedMcpServerErrors = {+ 400: unknown;+ 403: unknown;+ 404: unknown;+};++export type AddConnectedMcpServerResponses = {+ 200: ConnectMcpServerResponse;+};++export type AddConnectedMcpServerResponse = AddConnectedMcpServerResponses[keyof AddConnectedMcpServerResponses];++export type SearchConnectedAppToolsData = {+ body?: never;+ path: {+ session_id: string;+ execution_id: string;+ };+ query: {+ /**+ * Keywords matched against tool names and descriptions, e.g. `linear issue`.+ */+ query: string;+ };+ url: '/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/tools';+};++export type SearchConnectedAppToolsErrors = {+ 403: unknown;+ 404: unknown;+};++export type SearchConnectedAppToolsResponses = {+ 200: ConnectedToolSearch;+};++export type SearchConnectedAppToolsResponse = SearchConnectedAppToolsResponses[keyof SearchConnectedAppToolsResponses];++export type CallConnectedAppToolData = {+ body: CallConnectedTool;+ path: {+ session_id: string;+ execution_id: string;+ kind: ConnectedAppKind;+ /**+ * The app's slug or custom server key+ */+ key: string;+ };+ query?: never;+ url: '/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/{kind}/{key}/calls';+};++export type CallConnectedAppToolErrors = {+ 400: unknown;+ 403: unknown;+ 404: unknown;+};++export type CallConnectedAppToolResponses = {+ 200: ConnectedToolResult;+};++export type CallConnectedAppToolResponse = CallConnectedAppToolResponses[keyof CallConnectedAppToolResponses];++export type ListConnectedAppToolsData = {+ body?: never;+ path: {+ session_id: string;+ execution_id: string;+ kind: ConnectedAppKind;+ /**+ * The app's slug or custom server key+ */+ key: string;+ };+ query?: never;+ url: '/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/{kind}/{key}/tools';+};++export type ListConnectedAppToolsErrors = {+ 403: unknown;+ 404: unknown;+};++export type ListConnectedAppToolsResponses = {+ 200: Array<ConnectedTool>;+};++export type ListConnectedAppToolsResponse = ListConnectedAppToolsResponses[keyof ListConnectedAppToolsResponses];+export type ListExecutionReviewsData = {body?: never;path: {diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.jsonindex 3ef8436dce..c707c9a5ff 100644--- a/packages/sdk/specs/agent-harness.json+++ b/packages/sdk/specs/agent-harness.json@@ -1626,6 +1626,365 @@}}},+ "/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps": {+ "get": {+ "tags": ["agent-sessions"],+ "summary": "List the connected apps and custom MCP servers the session's agent may use.",+ "operationId": "list_execution_connected_apps",+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "execution_id",+ "in": "path",+ "description": "A running execution of the session's current turn",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ConnectedApp"+ }+ }+ }+ }+ },+ "403": {+ "description": ""+ },+ "404": {+ "description": ""+ }+ }+ }+ },+ "/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/discover": {+ "post": {+ "tags": ["agent-sessions"],+ "summary": "Search the connectable app catalog, or inspect one app's tools and connection status.",+ "operationId": "discover_connected_apps",+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "execution_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/DiscoveryRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/DiscoverConnectorsResponse"+ }+ }+ }+ },+ "400": {+ "description": ""+ },+ "403": {+ "description": ""+ },+ "404": {+ "description": ""+ }+ }+ }+ },+ "/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/servers": {+ "post": {+ "tags": ["agent-sessions"],+ "summary": "Add a custom MCP server to the execution account's connections.",+ "operationId": "add_connected_mcp_server",+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "execution_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ConnectMcpServer"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ConnectMcpServerResponse"+ }+ }+ }+ },+ "400": {+ "description": ""+ },+ "403": {+ "description": ""+ },+ "404": {+ "description": ""+ }+ }+ }+ },+ "/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/tools": {+ "get": {+ "tags": ["agent-sessions"],+ "summary": "Find tools across the agent's connected apps by keywords.",+ "operationId": "search_connected_app_tools",+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "execution_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "query",+ "in": "query",+ "description": "Keywords matched against tool names and descriptions, e.g. `linear issue`.",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ConnectedToolSearch"+ }+ }+ }+ },+ "403": {+ "description": ""+ },+ "404": {+ "description": ""+ }+ }+ }+ },+ "/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/{kind}/{key}/calls": {+ "post": {+ "tags": ["agent-sessions"],+ "summary": "Call one tool of a connected app as the execution's account.",+ "operationId": "call_connected_app_tool",+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "execution_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "kind",+ "in": "path",+ "required": true,+ "schema": {+ "$ref": "#/components/schemas/ConnectedAppKind"+ }+ },+ {+ "name": "key",+ "in": "path",+ "description": "The app's slug or custom server key",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CallConnectedTool"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ConnectedToolResult"+ }+ }+ }+ },+ "400": {+ "description": ""+ },+ "403": {+ "description": ""+ },+ "404": {+ "description": ""+ }+ }+ }+ },+ "/agent-sessions/{session_id}/code-executions/{execution_id}/connected-apps/{kind}/{key}/tools": {+ "get": {+ "tags": ["agent-sessions"],+ "summary": "List the tools one connected app serves.",+ "operationId": "list_connected_app_tools",+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "execution_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "kind",+ "in": "path",+ "required": true,+ "schema": {+ "$ref": "#/components/schemas/ConnectedAppKind"+ }+ },+ {+ "name": "key",+ "in": "path",+ "description": "The app's slug or custom server key",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ConnectedTool"+ }+ }+ }+ }+ },+ "403": {+ "description": ""+ },+ "404": {+ "description": ""+ }+ }+ }+ },"/agent-sessions/{session_id}/code-executions/{execution_id}/reviews": {"get": {"tags": ["agent-sessions"],@@ -4153,6 +4512,22 @@},"additionalProperties": false},+ "CallConnectedTool": {+ "type": "object",+ "description": "Call one tool of a connected app.",+ "required": ["tool"],+ "properties": {+ "arguments": {+ "type": "object",+ "description": "The tool's arguments, matching its input schema."+ },+ "tool": {+ "type": "string",+ "description": "The tool's name on its server."+ }+ },+ "additionalProperties": false+ },"CallSearchSuggestions": {"type": "object","description": "Call search supports speakers, channels and attendance status.",@@ -4442,6 +4817,175 @@}}},+ "ConnectMcpServer": {+ "type": "object",+ "description": "Add a custom MCP server to the user's connections.",+ "required": ["url", "serverName"],+ "properties": {+ "serverName": {+ "type": "string",+ "description": "Display name for the server."+ },+ "url": {+ "type": "string",+ "description": "The server's URL."+ }+ }+ },+ "ConnectMcpServerResponse": {+ "type": "object",+ "description": "Response from [`ConnectMcpServer`].",+ "required": [+ "url",+ "serverName",+ "alreadyConnected",+ "authenticated",+ "enabled",+ "summary"+ ],+ "properties": {+ "alreadyConnected": {+ "type": "boolean",+ "description": "Whether the user already had this server before the call."+ },+ "authenticated": {+ "type": "boolean",+ "description": "Whether the server holds the user's sign-in."+ },+ "enabled": {+ "type": "boolean",+ "description": "Whether the server's tools are turned on."+ },+ "serverName": {+ "type": "string",+ "description": "The server's display name."+ },+ "summary": {+ "type": "string",+ "description": "What happened and what the user still has to do."+ },+ "url": {+ "type": "string",+ "description": "The server's URL."+ }+ }+ },+ "ConnectedApp": {+ "type": "object",+ "description": "A connected app the session's agent may use.",+ "required": ["kind", "key", "name"],+ "properties": {+ "key": {+ "type": "string",+ "description": "The app's slug, or its custom server key."+ },+ "kind": {+ "$ref": "#/components/schemas/ConnectedAppKind",+ "description": "Which store the app comes from."+ },+ "name": {+ "type": "string",+ "description": "Display name, e.g. `Slack` or the owner's name for a custom server."+ }+ }+ },+ "ConnectedAppKind": {+ "type": "string",+ "description": "Which store a connected app comes from.",+ "enum": ["app", "custom"]+ },+ "ConnectedTool": {+ "type": "object",+ "description": "One tool a connected app serves.",+ "required": ["name", "inputSchema"],+ "properties": {+ "description": {+ "type": ["string", "null"],+ "description": "What the server says the tool does."+ },+ "inputSchema": {+ "type": "object",+ "description": "JSON Schema for the tool's arguments."+ },+ "name": {+ "type": "string",+ "description": "The tool's name on its server."+ }+ }+ },+ "ConnectedToolMatch": {+ "type": "object",+ "description": "One tool found by a search across the agent's connected apps.",+ "required": ["app", "tool"],+ "properties": {+ "app": {+ "$ref": "#/components/schemas/ConnectedApp",+ "description": "The app serving the tool."+ },+ "tool": {+ "$ref": "#/components/schemas/ConnectedTool",+ "description": "The tool."+ }+ }+ },+ "ConnectedToolResult": {+ "type": "object",+ "description": "A connected tool's answer: MCP's `CallToolResult`.",+ "required": ["isError", "content"],+ "properties": {+ "content": {+ "type": "array",+ "items": {+ "type": "object"+ },+ "description": "MCP content blocks, e.g. `{type: \"text\", text}`."+ },+ "isError": {+ "type": "boolean",+ "description": "The tool failed, or could not run; `content` says why."+ },+ "structuredContent": {+ "type": ["object", "null"],+ "description": "Structured output, for tools that declare an output schema."+ }+ }+ },+ "ConnectedToolSearch": {+ "type": "object",+ "description": "The best matches across the agent's connected apps, and the apps whose\ntools could not be listed, which the search did not cover.",+ "required": ["matches", "unsearched"],+ "properties": {+ "matches": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ConnectedToolMatch"+ },+ "description": "At most [`MAX_TOOL_MATCHES`] tools, best first."+ },+ "unsearched": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ConnectedApp"+ },+ "description": "Apps whose tools could not be listed."+ }+ }+ },+ "ConnectorTool": {+ "type": "object",+ "description": "An advertised action, not a tool loaded into the current turn.",+ "required": ["name", "description"],+ "properties": {+ "description": {+ "type": "string",+ "description": "What the action supports."+ },+ "name": {+ "type": "string",+ "description": "Upstream tool name."+ }+ }+ },"ControlRequest": {"allOf": [{@@ -4697,6 +5241,138 @@}}},+ "DiscoverConnectorsResponse": {+ "type": "object",+ "description": "Discovery metadata and optional markup for a user-controlled auth flow.",+ "required": ["result"],+ "properties": {+ "connect_markup": {+ "type": ["string", "null"],+ "description": "Include verbatim only if an advertised tool supports the requested task."+ },+ "result": {+ "$ref": "#/components/schemas/DiscoveryResult",+ "description": "Catalog or capability results."+ }+ }+ },+ "DiscoveredApp": {+ "type": "object",+ "description": "A verified app identity from the directory.",+ "required": ["app_slug", "name"],+ "properties": {+ "app_slug": {+ "type": "string",+ "description": "Exact identity to inspect or connect."+ },+ "description": {+ "type": ["string", "null"],+ "description": "Directory description; inspect tools to verify specific capabilities."+ },+ "name": {+ "type": "string",+ "description": "Human-readable app name."+ }+ }+ },+ "DiscoveryRequest": {+ "oneOf": [+ {+ "type": "object",+ "description": "Find connectable apps by name.",+ "required": ["query", "operation"],+ "properties": {+ "operation": {+ "type": "string",+ "enum": ["search"]+ },+ "query": {+ "type": "string",+ "description": "App name, e.g. \"Notion\" or \"Linear\", not a task description."+ }+ }+ },+ {+ "type": "object",+ "description": "Verify capabilities and connection status for one catalog app.",+ "required": ["app_slug", "operation"],+ "properties": {+ "app_slug": {+ "type": "string",+ "description": "Exact app slug from search results."+ },+ "operation": {+ "type": "string",+ "enum": ["inspect"]+ }+ }+ }+ ],+ "description": "Search by app name, then inspect a returned slug before recommending auth."+ },+ "DiscoveryResult": {+ "oneOf": [+ {+ "type": "object",+ "description": "Candidate apps; none has had its capabilities verified yet.",+ "required": ["apps", "more_results", "operation"],+ "properties": {+ "apps": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/DiscoveredApp"+ },+ "description": "Matching apps."+ },+ "more_results": {+ "type": "boolean",+ "description": "Narrow the app name if this is true."+ },+ "operation": {+ "type": "string",+ "enum": ["search"]+ }+ }+ },+ {+ "type": "object",+ "description": "Verified identity, capabilities and this caller's connection status.",+ "required": [+ "app",+ "connected",+ "tools",+ "tools_truncated",+ "operation"+ ],+ "properties": {+ "app": {+ "$ref": "#/components/schemas/DiscoveredApp",+ "description": "App from the directory."+ },+ "connected": {+ "type": "boolean",+ "description": "Whether this caller has an enabled connection. For an app that\nconnects through its own MCP server, that connection is checked\nthere, not in Pipedream."+ },+ "operation": {+ "type": "string",+ "enum": ["inspect"]+ },+ "tools": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ConnectorTool"+ },+ "description": "Advertised tools. Use SearchTools after connecting to load them."+ },+ "tools_truncated": {+ "type": "boolean",+ "description": "True when some advertised tools were omitted."+ }+ }+ }+ ],+ "description": "Discovery results never execute tools or change connections."+ },"DocumentId": {"type": "string","description": "A validated document identifier. Historical document ids need not be UUIDs."diff --git a/packages/sdk/src/entities/connected-apps/connected-app.ts b/packages/sdk/src/entities/connected-apps/connected-app.tsnew file mode 100644index 0000000000..04d6b90e5f--- /dev/null+++ b/packages/sdk/src/entities/connected-apps/connected-app.ts@@ -0,0 +1,201 @@+import type {+ ConnectedAppKind,+ ConnectedApp as ConnectedAppRecord,+ ConnectedTool as ConnectedToolRecord,+ ConnectedToolResult as ConnectedToolResultRecord,+} from '../../../generated/agent-harness/types.gen';+import { unwrap } from '../../utils';+import type { MacroClient } from '../../utils/client';+import type { CodeExecution } from '../agent-sessions/code-execution';++export type { ConnectedAppKind };++/** A connected tool's answer, MCP's `CallToolResult`. */+export type ConnectedToolResult = {+ /** The tool failed or could not run; `content` says why. */+ isError: boolean;+ /** MCP content blocks, e.g. `{type: 'text', text}`. */+ content: Array<Record<string, unknown>>;+ /** Structured output, for tools that declare an output schema. */+ structuredContent?: Record<string, unknown>;+};++/**+ * An app the session's agent was given: one the user connected through+ * Macro Connect (Slack, Linear, GitHub, Notion, Gmail, ...) or a custom MCP+ * server they added. Read its tools, then call one.+ */+export class ConnectedApp {+ private constructor(+ private readonly client: MacroClient,+ /** The running execution this app is reached through. */+ readonly execution: CodeExecution,+ /** `app` for a connected app, `custom` for a custom MCP server. */+ readonly kind: ConnectedAppKind,+ /** The app's slug, e.g. `slack`, or the custom server's key. */+ readonly key: string,+ /** Display name, e.g. `Slack`. */+ readonly name: string,+ ) {}++ /** The apps `execution`'s session agent was given. */+ static async list(+ client: MacroClient,+ execution: CodeExecution,+ ): Promise<ConnectedApp[]> {+ const records = unwrap(+ await client.agentHarness.listExecutionConnectedApps({+ path: {+ session_id: execution.session().id,+ execution_id: execution.id,+ },+ }),+ );+ return records.map((record: ConnectedAppRecord) =>+ ConnectedApp.fromRecord(client, execution, record),+ );+ }++ /** @internal A handle for an app record the harness answered. */+ static fromRecord(+ client: MacroClient,+ execution: CodeExecution,+ record: ConnectedAppRecord,+ ): ConnectedApp {+ return new ConnectedApp(+ client,+ execution,+ record.kind,+ record.key,+ record.name,+ );+ }++ /**+ * Find tools across every app the execution's agent was given, by+ * keywords matched against tool names and descriptions, best first (at+ * most 20). `unsearched` lists apps whose tools could not be read.+ */+ static async searchTools(+ client: MacroClient,+ execution: CodeExecution,+ query: string,+ ): Promise<{ matches: ConnectedTool[]; unsearched: ConnectedApp[] }> {+ const found = unwrap(+ await client.agentHarness.searchConnectedAppTools({+ path: {+ session_id: execution.session().id,+ execution_id: execution.id,+ },+ query: { query },+ }),+ );+ return {+ matches: found.matches.map((match) =>+ ConnectedTool.fromRecord(+ client,+ ConnectedApp.fromRecord(client, execution, match.app),+ match.tool,+ ),+ ),+ unsearched: found.unsearched.map((record) =>+ ConnectedApp.fromRecord(client, execution, record),+ ),+ };+ }++ /**+ * The tools this app serves, with each one's description and argument+ * schema. Read a tool's `inputSchema` before calling it.+ */+ async tools(): Promise<ConnectedTool[]> {+ const records = unwrap(+ await this.client.agentHarness.listConnectedAppTools({+ path: this.path(),+ }),+ );+ return records.map((record: ConnectedToolRecord) =>+ ConnectedTool.fromRecord(this.client, this, record),+ );+ }++ /** @internal The harness route that names this app. */+ path() {+ return {+ session_id: this.execution.session().id,+ execution_id: this.execution.id,+ kind: this.kind,+ key: this.key,+ };+ }++ /** Serialize identity only. */+ toJSON() {+ return { kind: this.kind, key: this.key, name: this.name };+ }+}++/** One tool a connected app serves. */+export class ConnectedTool {+ /** @internal */+ constructor(+ private readonly client: MacroClient,+ /** The app serving this tool. */+ readonly app: ConnectedApp,+ /** The tool's name on its server. */+ readonly name: string,+ /** What the server says the tool does. */+ readonly description: string | undefined,+ /** JSON Schema for the tool's arguments. */+ readonly inputSchema: Record<string, unknown>,+ ) {}++ /** @internal A handle for a tool record the harness answered. */+ static fromRecord(+ client: MacroClient,+ app: ConnectedApp,+ record: ConnectedToolRecord,+ ): ConnectedTool {+ return new ConnectedTool(+ client,+ app,+ record.name,+ record.description ?? undefined,+ record.inputSchema,+ );+ }++ /**+ * Call the tool as the execution's account, with arguments matching+ * `inputSchema`. Writes take effect immediately, in the user's real+ * account. In a turn someone other than the session's owner prompted, a+ * call as the owner waits for the owner to approve it, and a declined or+ * unanswered call comes back with `isError`. Check `isError` on the result: an app that is not connected,+ * or whose connection expired, answers with `isError` and text telling you+ * what to say to the user, including any connect markup to put in your+ * reply verbatim.+ */+ async call(args: Record<string, unknown> = {}): Promise<ConnectedToolResult> {+ const result: ConnectedToolResultRecord = unwrap(+ await this.client.agentHarness.callConnectedAppTool({+ path: this.app.path(),+ body: { tool: this.name, arguments: args },+ }),+ );+ return {+ isError: result.isError,+ content: result.content,+ structuredContent: result.structuredContent ?? undefined,+ };+ }++ /** Serialize the tool's description, not its client. */+ toJSON() {+ return {+ app: this.app.toJSON(),+ name: this.name,+ description: this.description,+ inputSchema: this.inputSchema,+ };+ }+}diff --git a/packages/sdk/src/entities/connected-apps/connector.ts b/packages/sdk/src/entities/connected-apps/connector.tsnew file mode 100644index 0000000000..b0a53f2f3e--- /dev/null+++ b/packages/sdk/src/entities/connected-apps/connector.ts@@ -0,0 +1,121 @@+import type { DiscoverConnectorsResponse } from '../../../generated/agent-harness/types.gen';+import { unwrap } from '../../utils';+import type { MacroClient } from '../../utils/client';+import type { CodeExecution } from '../agent-sessions/code-execution';++/** One action a connectable app advertises; not callable until connected. */+export type ConnectorAction = {+ /** The upstream tool name. */+ name: string;+ /** What the action supports. */+ description: string;+};++/** A connector's verified capabilities and the account's connection status. */+export type ConnectorInspection = {+ /** Whether the execution's account has the app connected and enabled. */+ connected: boolean;+ /** The actions the app advertises. */+ actions: ConnectorAction[];+ /** True when some advertised actions were left out. */+ actionsTruncated: boolean;+ /**+ * Markup that gives the user a button to connect the app, present only for+ * an unconnected app with advertised actions. Put it in your reply+ * verbatim, and only when one of `actions` supports the user's task.+ */+ connectMarkup: string | undefined;+};++/**+ * An app the user could connect, found in the connector catalog. Its+ * description is the catalog's; inspect it to see what it can actually do.+ */+export class Connector {+ private constructor(+ private readonly client: MacroClient,+ /** The running execution the catalog is read through. */+ readonly execution: CodeExecution,+ /** The app's catalog slug, e.g. `linear`. */+ readonly slug: string,+ /** Display name, e.g. `Linear`. */+ readonly name: string,+ /** The catalog's description. */+ readonly description: string | undefined,+ ) {}++ /** Search the connector catalog by app name. */+ static async search(+ client: MacroClient,+ execution: CodeExecution,+ appName: string,+ ): Promise<{ connectors: Connector[]; moreResults: boolean }> {+ const response = await discover(client, execution, {+ operation: 'search',+ query: appName,+ });+ if (response.result.operation !== 'search') {+ throw new Error('connector search answered with an inspection');+ }+ return {+ connectors: response.result.apps.map(+ (app) =>+ new Connector(+ client,+ execution,+ app.app_slug,+ app.name,+ app.description ?? undefined,+ ),+ ),+ moreResults: response.result.more_results,+ };+ }++ /**+ * Read the actions this app advertises and whether the execution's account+ * has it connected. Inspection never calls the app or changes a connection.+ */+ async inspect(): Promise<ConnectorInspection> {+ const response = await discover(this.client, this.execution, {+ operation: 'inspect',+ app_slug: this.slug,+ });+ if (response.result.operation !== 'inspect') {+ throw new Error('connector inspection answered with a search');+ }+ return {+ connected: response.result.connected,+ actions: response.result.tools,+ actionsTruncated: response.result.tools_truncated,+ connectMarkup: response.connect_markup ?? undefined,+ };+ }++ /** Serialize the catalog entry, not its client. */+ toJSON() {+ return {+ slug: this.slug,+ name: this.name,+ description: this.description,+ };+ }+}++async function discover(+ client: MacroClient,+ execution: CodeExecution,+ request:+ | { operation: 'search'; query: string }+ | { operation: 'inspect'; app_slug: string },+): Promise<DiscoverConnectorsResponse> {+ return unwrap(+ await client.agentHarness.discoverConnectedApps({+ path: {+ session_id: execution.session().id,+ execution_id: execution.id,+ },+ body: request,+ }),+ );+}diff --git a/packages/sdk/src/entities/connected-apps/namespace.ts b/packages/sdk/src/entities/connected-apps/namespace.tsnew file mode 100644index 0000000000..22857b0511--- /dev/null+++ b/packages/sdk/src/entities/connected-apps/namespace.ts@@ -0,0 +1,96 @@+import type { ConnectMcpServerResponse } from '../../../generated/agent-harness/types.gen';+import { unwrap } from '../../utils';+import type { MacroClient } from '../../utils/client';+import type { CodeExecution } from '../agent-sessions/code-execution';+import { ConnectedApp, type ConnectedTool } from './connected-app';+import { Connector } from './connector';++export type { ConnectMcpServerResponse };++/**+ * The apps the user connected for their agents (Slack, Linear, GitHub,+ * Notion, Gmail and others through Macro Connect) and the custom MCP servers+ * they added, reached from a session's code execution.+ *+ * @routing Use when the work needs a connected third-party app or MCP server (Slack, Linear, GitHub, Notion, Jira, Google Sheets, a custom MCP server): reading or changing data in it, or calling one of its tools; not Macro's own documents, email, channels or calendar.+ *+ * @agent+ * ## Connected apps+ *+ * Connected apps are reached only from an agent session's ExecuteCode program: pass the `execution` that `main` receives. `macro.connectedApps.list(execution)` returns the apps this agent was given (every app the user connected, or the agent's own selection); an app missing from it is not connected for this agent. Find a tool across every app with `macro.connectedApps.searchTools(execution, 'linear issue')`, or read one app's tools with `app.tools()`; pick one by name and description, read its `inputSchema`, then `tool.call(args)`.+ *+ * Calls run in the user's real account through Macro's server, as the account this execution acts as, and take effect at once; the program never sees a credential. In a turn someone other than the session's owner prompted, each call that uses the owner's account waits for the owner to approve it, so make few such calls and expect a long wait or a refusal. Read before writing, and never repeat a write whose outcome is unknown: check the app's state first. A result with `isError` explains itself: when it says an app is not connected, tell the user and include the connect markup it gives you in your reply verbatim, then stop.+ *+ * When an app the work needs is missing, find it with `macro.connectedApps.discover(execution, appName)` and `connector.inspect()` its advertised actions and connection status. Recommend connecting only when an advertised action supports the task; an app's name is not evidence. For a suitable unconnected app, put the inspection's `connectMarkup` in your reply verbatim and say what connecting enables. To add a remote MCP server the user gives you the URL of, use `macro.connectedApps.addServer(execution, {url, serverName})`; never guess a URL, and tell the user to sign in under Settings → Connections when its summary says so.+ *+ * ```javascript+ * export async function main({macro, execution}) {+ * const apps = await macro.connectedApps.list(execution);+ * const linear = apps.find((app) => app.key === 'linear');+ * if (!linear) return {data: {error: 'Linear is not connected', available: apps.map((app) => app.name)}};+ * const tools = await linear.tools();+ * const search = tools.find((tool) => tool.name === 'list_issues');+ * const result = await search.call({query: 'login bug', limit: 5});+ * return {data: result.isError ? {error: result.content} : result.structuredContent ?? result.content};+ * }+ * ```+ */+export class ConnectedAppNamespace {+ constructor(private readonly client: MacroClient) {}++ /**+ * List the apps a running code execution's session agent may use; pass the+ * `execution` given to `main`. Fails outside a running execution of the+ * session's current turn.+ */+ list(execution: CodeExecution): Promise<ConnectedApp[]> {+ return ConnectedApp.list(this.client, execution);+ }++ /**+ * Find tools across every connected app the execution's agent was given,+ * by keywords matched against tool names and descriptions (e.g. `linear+ * issue`), best first, at most 20. Apps whose tools could not be read come+ * back in `unsearched`, not as an error.+ */+ searchTools(+ execution: CodeExecution,+ query: string,+ ): Promise<{ matches: ConnectedTool[]; unsearched: ConnectedApp[] }> {+ return ConnectedApp.searchTools(this.client, execution, query);+ }++ /**+ * Search the catalog of apps the user could connect, by app name (e.g.+ * `Linear`, not a task description). Inspect a result before recommending+ * it: its description alone does not show what it can do.+ */+ discover(+ execution: CodeExecution,+ appName: string,+ ): Promise<{ connectors: Connector[]; moreResults: boolean }> {+ return Connector.search(this.client, execution, appName);+ }++ /**+ * Add a remote MCP server to the execution account's connections by its+ * URL: only one the user gave you, or an official URL you are sure of;+ * never guess. Most servers then need the user to sign in under+ * Settings → Connections, which the result's `summary` says. A URL the+ * user already has is left as it is.+ */+ async addServer(+ execution: CodeExecution,+ server: { url: string; serverName: string },+ ): Promise<ConnectMcpServerResponse> {+ return unwrap(+ await this.client.agentHarness.addConnectedMcpServer({+ path: {+ session_id: execution.session().id,+ execution_id: execution.id,+ },+ body: server,+ }),+ );+ }+}diff --git a/packages/sdk/src/entities/favorites/namespace.ts b/packages/sdk/src/entities/favorites/namespace.tsindex a422979813..19b2e39315 100644--- a/packages/sdk/src/entities/favorites/namespace.ts+++ b/packages/sdk/src/entities/favorites/namespace.ts@@ -24,7 +24,7 @@ export type FavoritesFilter = {/*** The user's favorites: a manually ordered collection of entity references.*- * @routing Use when adding or removing the user's favorites; not pins.+ * @routing Use when adding or removing the user's favorites or pinned home-view slots (`macro.pins`); not tags or properties.*/export class FavoritesNamespace {constructor(private readonly client: MacroClient) {}diff --git a/packages/sdk/src/entities/pins/namespace.ts b/packages/sdk/src/entities/pins/namespace.tsindex 1e8c61d52e..f3341beaf7 100644--- a/packages/sdk/src/entities/pins/namespace.ts+++ b/packages/sdk/src/entities/pins/namespace.ts@@ -10,8 +10,6 @@ export type { PinnedItem, ReorderPinRequest };/*** The user's pins: items pinned to fixed slots in the home view.- *- * @routing Use when pinning or unpinning items; not favorites.*/export class PinsNamespace {constructor(private readonly client: MacroClient) {}diff --git a/packages/sdk/src/macro.ts b/packages/sdk/src/macro.tsindex 6cc08ea7f6..8f2e9aad6a 100644--- a/packages/sdk/src/macro.ts+++ b/packages/sdk/src/macro.ts@@ -8,6 +8,7 @@ import { CalendarNamespace } from './entities/calendar/namespace';import { CallRecordNamespace } from './entities/calls/namespace';import { ChannelNamespace } from './entities/channels/namespace';import { ChatNamespace } from './entities/chats/namespace';+import { ConnectedAppNamespace } from './entities/connected-apps/namespace';import { CrmNamespace } from './entities/crm/namespace';import { DatabaseNamespace } from './entities/databases/namespace';import { DocumentNamespace } from './entities/documents/namespace';@@ -51,6 +52,12 @@ export type {StructuredCompletionResponse,} from './entities/ai/namespace';export type { CallMessage } from './entities/calls/message';+export {+ ConnectedApp,+ ConnectedTool,+} from './entities/connected-apps/connected-app';+export { Connector } from './entities/connected-apps/connector';+export { ConnectedAppNamespace } from './entities/connected-apps/namespace';export {type AddColumnOptions,type ApplyOpsOptions,@@ -156,6 +163,9 @@ export class Macro<T extends MacroOpts = MacroOpts> {readonly email: EmailNamespace;+ /** Call the user's connected apps and MCP servers from a code execution. */+ readonly connectedApps: ConnectedAppNamespace;+readonly favorites: FavoritesNamespace;readonly foreignEntities: ForeignEntityNamespace;@@ -232,6 +242,7 @@ export class Macro<T extends MacroOpts = MacroOpts> {this.databases = new DatabaseNamespace(client);this.documents = new DocumentNamespace(client);this.email = new EmailNamespace(client);+ this.connectedApps = new ConnectedAppNamespace(client);this.favorites = new FavoritesNamespace(client);this.foreignEntities = new ForeignEntityNamespace(client);this.forms = new FormNamespace(client);@@ -294,6 +305,15 @@ export { ChannelAccessRequest } from './entities/channels/access-request';export { ChannelActivity } from './entities/channels/activity';export { ChannelPicture } from './entities/channels/picture';export { ChatGeneration, ChatMessage } from './entities/chats/generation';+export type {+ ConnectedAppKind,+ ConnectedToolResult,+} from './entities/connected-apps/connected-app';+export type {+ ConnectorAction,+ ConnectorInspection,+} from './entities/connected-apps/connector';+export type { ConnectMcpServerResponse } from './entities/connected-apps/namespace';export {CrmPipeline,PipelineColumn,diff --git a/packages/sdk/tests/connected-apps.test.ts b/packages/sdk/tests/connected-apps.test.tsnew file mode 100644index 0000000000..ab175d76e5--- /dev/null+++ b/packages/sdk/tests/connected-apps.test.ts@@ -0,0 +1,220 @@+import { afterEach, describe, expect, test } from 'bun:test';+import { Macro } from '../src/macro';++const originalFetch = globalThis.fetch;+afterEach(() => {+ globalThis.fetch = originalFetch;+});++describe('connected apps', () => {+ test('lists an execution’s apps, their tools, and calls one through the harness', async () => {+ const requests: Array<{ method: string; url: string; body: unknown }> = [];+ globalThis.fetch = (async (input) => {+ const request = input instanceof Request ? input : new Request(input);+ const body: unknown =+ request.method === 'POST' ? await request.clone().json() : undefined;+ requests.push({ method: request.method, url: request.url, body });+ if (request.url.endsWith('/connected-apps')) {+ return Response.json([+ { kind: 'app', key: 'slack', name: 'Slack' },+ { kind: 'custom', key: '0123456789abcdef', name: 'Internal wiki' },+ ]);+ }+ if (request.url.endsWith('/connected-apps/app/slack/tools')) {+ return Response.json([+ {+ name: 'send_message',+ description: 'Send a message to a channel',+ inputSchema: {+ type: 'object',+ properties: { channel: { type: 'string' } },+ },+ },+ ]);+ }+ return Response.json({+ isError: false,+ content: [{ type: 'text', text: 'sent' }],+ structuredContent: null,+ });+ }) as typeof fetch;+ const macro = new Macro({+ token: 'test-token',+ hosts: { 'agent-harness': 'https://agent.example.test' },+ });+ const execution = macro.agentSessions+ .byId('0198a4cc-e138-7670-a308-a6b766602700')+ .codeExecutions.byId('0198a4cc-e138-7670-a308-a6b766602788');++ const apps = await macro.connectedApps.list(execution);+ const slack = apps.find((app) => app.name === 'Slack');+ const tools = (await slack?.tools()) ?? [];+ const result = await tools[0]?.call({ channel: 'general', text: 'hi' });++ expect(apps.map((app) => app.toJSON())).toEqual([+ { kind: 'app', key: 'slack', name: 'Slack' },+ { kind: 'custom', key: '0123456789abcdef', name: 'Internal wiki' },+ ]);+ expect(tools.map((tool) => tool.toJSON())).toEqual([+ {+ app: { kind: 'app', key: 'slack', name: 'Slack' },+ name: 'send_message',+ description: 'Send a message to a channel',+ inputSchema: {+ type: 'object',+ properties: { channel: { type: 'string' } },+ },+ },+ ]);+ expect(result).toEqual({+ isError: false,+ content: [{ type: 'text', text: 'sent' }],+ structuredContent: undefined,+ });+ const base =+ 'https://agent.example.test/agent-sessions/0198a4cc-e138-7670-a308-a6b766602700/code-executions/0198a4cc-e138-7670-a308-a6b766602788/connected-apps';+ expect(requests).toEqual([+ { method: 'GET', url: base, body: undefined },+ { method: 'GET', url: `${base}/app/slack/tools`, body: undefined },+ {+ method: 'POST',+ url: `${base}/app/slack/calls`,+ body: {+ tool: 'send_message',+ arguments: { channel: 'general', text: 'hi' },+ },+ },+ ]);+ });++ test('discovers a connector, inspects it, and adds an MCP server through the harness', async () => {+ const requests: Array<{ url: string; body: unknown }> = [];+ globalThis.fetch = (async (input) => {+ const request = input instanceof Request ? input : new Request(input);+ const body: unknown = await request.clone().json();+ requests.push({ url: request.url, body });+ if (request.url.endsWith('/connected-apps/servers')) {+ return Response.json({+ url: 'https://mcp.linear.app/mcp',+ serverName: 'Linear',+ alreadyConnected: false,+ authenticated: false,+ enabled: true,+ summary: 'Added Linear.',+ });+ }+ if ((body as { operation: string }).operation === 'search') {+ return Response.json({+ result: {+ operation: 'search',+ apps: [+ { app_slug: 'linear', name: 'Linear', description: 'Issues' },+ ],+ more_results: false,+ },+ connect_markup: null,+ });+ }+ return Response.json({+ result: {+ operation: 'inspect',+ app: { app_slug: 'linear', name: 'Linear', description: 'Issues' },+ connected: false,+ tools: [{ name: 'create_issue', description: 'Create an issue' }],+ tools_truncated: false,+ },+ connect_markup:+ '<m-connect-app>{"appSlug":"linear","name":"Linear"}</m-connect-app>',+ });+ }) as typeof fetch;+ const macro = new Macro({+ token: 'test-token',+ hosts: { 'agent-harness': 'https://agent.example.test' },+ });+ const execution = macro.agentSessions+ .byId('0198a4cc-e138-7670-a308-a6b766602700')+ .codeExecutions.byId('0198a4cc-e138-7670-a308-a6b766602788');++ const found = await macro.connectedApps.discover(execution, 'Linear');+ const inspection = await found.connectors[0]?.inspect();+ const added = await macro.connectedApps.addServer(execution, {+ url: 'https://mcp.linear.app/mcp',+ serverName: 'Linear',+ });++ expect(found.connectors.map((connector) => connector.toJSON())).toEqual([+ { slug: 'linear', name: 'Linear', description: 'Issues' },+ ]);+ expect(found.moreResults).toBe(false);+ expect(inspection).toEqual({+ connected: false,+ actions: [{ name: 'create_issue', description: 'Create an issue' }],+ actionsTruncated: false,+ connectMarkup:+ '<m-connect-app>{"appSlug":"linear","name":"Linear"}</m-connect-app>',+ });+ expect(added.summary).toBe('Added Linear.');+ const base =+ 'https://agent.example.test/agent-sessions/0198a4cc-e138-7670-a308-a6b766602700/code-executions/0198a4cc-e138-7670-a308-a6b766602788/connected-apps';+ expect(requests).toEqual([+ {+ url: `${base}/discover`,+ body: { operation: 'search', query: 'Linear' },+ },+ {+ url: `${base}/discover`,+ body: { operation: 'inspect', app_slug: 'linear' },+ },+ {+ url: `${base}/servers`,+ body: { url: 'https://mcp.linear.app/mcp', serverName: 'Linear' },+ },+ ]);+ });++ test('searches tools across connected apps through the harness', async () => {+ const urls: string[] = [];+ globalThis.fetch = (async (input) => {+ const request = input instanceof Request ? input : new Request(input);+ urls.push(request.url);+ return Response.json({+ matches: [+ {+ app: { kind: 'app', key: 'linear', name: 'Linear' },+ tool: {+ name: 'create_issue',+ description: 'Create a Linear issue',+ inputSchema: { type: 'object' },+ },+ },+ ],+ unsearched: [{ kind: 'custom', key: '0123456789abcdef', name: 'Wiki' }],+ });+ }) as typeof fetch;+ const macro = new Macro({+ token: 'test-token',+ hosts: { 'agent-harness': 'https://agent.example.test' },+ });+ const execution = macro.agentSessions+ .byId('0198a4cc-e138-7670-a308-a6b766602700')+ .codeExecutions.byId('0198a4cc-e138-7670-a308-a6b766602788');++ const found = await macro.connectedApps.searchTools(+ execution,+ 'linear issue',+ );++ expect(found.matches.map((tool) => tool.toJSON())).toEqual([+ {+ app: { kind: 'app', key: 'linear', name: 'Linear' },+ name: 'create_issue',+ description: 'Create a Linear issue',+ inputSchema: { type: 'object' },+ },+ ]);+ expect(found.unsearched.map((app) => app.name)).toEqual(['Wiki']);+ expect(urls).toEqual([+ 'https://agent.example.test/agent-sessions/0198a4cc-e138-7670-a308-a6b766602700/code-executions/0198a4cc-e138-7670-a308-a6b766602788/connected-apps/tools?query=linear%20issue',+ ]);+ });+});diff --git a/services/agent_harness_service/AGENTS.md b/services/agent_harness_service/AGENTS.mdindex 2eeabfcc59..2c17767e1c 100644--- a/services/agent_harness_service/AGENTS.md+++ b/services/agent_harness_service/AGENTS.md@@ -30,6 +30,8 @@ Pulumi stacks; they do not host extra agent processes.`ai-code-mode` get only `ExecuteCode`/`DescribeCodeTools`/`ReadCodeDocs` on`tools/list` (`tool_service.rs`); hidden native tools stay callable. The flagis cached per user (`tool_mode_cache.rs`).+ `src/code_mode/connected_apps.rs` serves a running execution's+ `macro.connectedApps` through the in-process egress service.Code execution's destination list in `src/code_mode.rs` also includes theconfigured editing worker, whose comment-mark endpoint requires a scopeddocument token; this does not grant permission to edit document content.diff --git a/services/agent_harness_service/src/api/swagger.rs b/services/agent_harness_service/src/api/swagger.rsindex 33db7e9eff..42ce0c8a36 100644--- a/services/agent_harness_service/src/api/swagger.rs+++ b/services/agent_harness_service/src/api/swagger.rs@@ -72,6 +72,12 @@ impl Modify for SecurityAddon {agent_code_mode::inbound::axum_router::get_review,agent_code_mode::inbound::axum_router::list_reviews,agent_code_mode::inbound::axum_router::decide_review,+ agent_code_mode::inbound::axum_router::list_connected_apps,+ agent_code_mode::inbound::axum_router::list_connected_app_tools,+ agent_code_mode::inbound::axum_router::call_connected_app_tool,+ agent_code_mode::inbound::axum_router::search_connected_app_tools,+ agent_code_mode::inbound::axum_router::discover_connected_apps,+ agent_code_mode::inbound::axum_router::add_connected_mcp_server,axum_router::create_agent_session_handler,axum_router::warm_agent_session_handler,axum_router::get_agent_session_handler,diff --git a/services/agent_harness_service/src/code_mode.rs b/services/agent_harness_service/src/code_mode.rsindex 48a795f1c5..c84f6a8e4c 100644--- a/services/agent_harness_service/src/code_mode.rs+++ b/services/agent_harness_service/src/code_mode.rs@@ -143,6 +143,7 @@ pub fn sdk_hosts() -> anyhow::Result<BTreeMap<String, String>> {.collect())}+pub mod connected_apps;pub mod reviews;async fn approve_run(diff --git a/services/agent_harness_service/src/code_mode/connected_apps.rs b/services/agent_harness_service/src/code_mode/connected_apps.rsnew file mode 100644index 0000000000..a9a00f2672--- /dev/null+++ b/services/agent_harness_service/src/code_mode/connected_apps.rs@@ -0,0 +1,319 @@+//! A code execution's connected apps, served through the session's egress.+//!+//! The program is handed the apps its agent was given (the same listing a+//! session's runtime is), and its calls go through the egress service's+//! credential resolution and actor transport, so no upstream credential+//! ever reaches the sandbox. The account a call spends is the one the+//! execution was approved for when its credential was minted, which+//! `ConnectedAppService` settles before calling here.++use agent_code_mode::domain::CodeModeError;+use agent_code_mode::domain::connected_apps::{+ CallConnectedTool, ConnectedApp, ConnectedAppKind, ConnectedAppRef, ConnectedAppTools,+ ConnectedAppUse, ConnectedTool, ConnectedToolResult, SessionAccounts,+};+use agent_egress::domain::error::EgressError;+use agent_egress::domain::model::{+ CustomMcpServerKey, McpDestination, McpServerSlug, SessionGrant,+};+use agent_egress::domain::service::SessionMcpExchange;+use agent_harness::outbound::egress::EgressProvisioner;+use agent_inmem::domain::tool_gate::{NativeToolGate, NativeToolVerdict};+use agent_session::domain::model::{AgentSessionId, TurnPrompter};+use agent_session::domain::ports::AgentSessionRepo;+use async_trait::async_trait;+use macro_user_id::user_id::MacroUserIdStr;+use mcp_client::domain::ports::McpServerStore;+use mcp_client::domain::service::{AddServerError, AddedBy};+use mcp_client::inbound::toolset::{ConnectMcpServer, ConnectMcpServerResponse};+use pipedream_mcp::domain::ports::{ConnectionStore, ConnectorOverlays};+use pipedream_mcp::domain::service::discovery::DiscoveryRequest;+use pipedream_mcp::inbound::toolset::DiscoverConnectorsResponse;+use serde_json::{Value, json};+use std::sync::Arc;++/// Most `tools/list` pages read for one app.+const MAX_TOOL_PAGES: usize = 20;++pub struct SessionConnectedApps<Egress, Connections, Servers, Sessions> {+ pub egress: Arc<Egress>,+ pub provisioner: EgressProvisioner<Connections, Servers>,+ pub sessions: Sessions,+ /// The gate native tools pass, so discovery and adding a server wait for+ /// the owner exactly as `DiscoverConnectors` and `ConnectMcpServer` do.+ pub gate: Arc<dyn NativeToolGate>,+ pub connectors: ai_tools::ToolConnectorToolContext,+ pub mcp_servers: ai_tools::ToolMcpServerToolContext,+}++/// A use settled against the session: its grant, the account it spends and+/// the apps its agent was given.+struct Settled {+ grant: SessionGrant,+ user: MacroUserIdStr<'static>,+ apps: Vec<ConnectedApp>,+}++impl<Egress, Connections, Servers, Sessions>+ SessionConnectedApps<Egress, Connections, Servers, Sessions>+where+ Egress: SessionMcpExchange + 'static,+ Connections: ConnectionStore + ConnectorOverlays,+ Servers: McpServerStore,+ Sessions: AgentSessionRepo,+{+ async fn settle(&self, usage: &ConnectedAppUse) -> Result<Settled, CodeModeError> {+ let grant = self+ .egress+ .session_grant(usage.session)+ .await+ .map_err(egress_error)?;+ let user = usage.user.clone();++ let session = self+ .sessions+ .get(usage.session)+ .await+ .map_err(|_| CodeModeError::Forbidden)?;+ let (slugs, custom) = self+ .provisioner+ .advertised_all(&grant.owner, &session.mcp_servers)+ .await+ .map_err(|error| {+ tracing::error!(?error, "could not list a session's connected apps");+ CodeModeError::Unavailable+ })?;+ let mut apps: Vec<ConnectedApp> = slugs+ .iter()+ .map(|slug| ConnectedApp {+ kind: ConnectedAppKind::App,+ key: slug.as_str().to_owned(),+ name: grant.display_name(slug),+ })+ .collect();+ apps.extend(custom.into_iter().map(|server| ConnectedApp {+ kind: ConnectedAppKind::Custom,+ key: server.key.as_str().to_owned(),+ name: server.name,+ }));++ Ok(Settled { grant, user, apps })+ }++ /// The destination for `app`, only when the agent was given it.+ fn destination(+ settled: &Settled,+ app: &ConnectedAppRef,+ ) -> Result<McpDestination, CodeModeError> {+ let given = settled+ .apps+ .iter()+ .any(|given| given.kind == app.kind && given.key == app.key);+ if !given {+ return Err(CodeModeError::NotFound);+ }++ let destination = match app.kind {+ ConnectedAppKind::App => McpServerSlug::parse(&app.key).map(McpDestination::Connected),+ ConnectedAppKind::Custom => {+ CustomMcpServerKey::parse(&app.key).map(McpDestination::Custom)+ }+ };+ destination.ok_or(CodeModeError::NotFound)+ }++ /// Pass `tool`'s call through the native tool gate under the execution's+ /// account choice: in a turn somebody else prompted, a call as the owner+ /// waits for their approval.+ async fn gate(+ &self,+ usage: &ConnectedAppUse,+ tool: &str,+ mut arguments: Value,+ ) -> Result<(), CodeModeError> {+ arguments[ai_toolset::actor::ACTING_AS] = json!(usage.acting_as);+ match self.gate.check(usage.session, tool, &arguments).await {+ NativeToolVerdict::Run => Ok(()),+ NativeToolVerdict::RunAs(user) if user == usage.user => Ok(()),+ NativeToolVerdict::RunAs(_) => Err(CodeModeError::Forbidden),+ NativeToolVerdict::Refuse(reason) => Err(CodeModeError::Invalid(reason)),+ }+ }+}++#[async_trait]+impl<Egress, Connections, Servers, Sessions> ConnectedAppTools+ for SessionConnectedApps<Egress, Connections, Servers, Sessions>+where+ Egress: SessionMcpExchange + 'static,+ Connections: ConnectionStore + ConnectorOverlays + 'static,+ Servers: McpServerStore + 'static,+ Sessions: AgentSessionRepo + 'static,+{+ async fn accounts(&self, session: AgentSessionId) -> Result<SessionAccounts, CodeModeError> {+ let grant = self+ .egress+ .session_grant(session)+ .await+ .map_err(egress_error)?;+ let requester = grant+ .prompter+ .as_ref()+ .and_then(TurnPrompter::acting_user)+ .cloned();+ Ok(SessionAccounts {+ owner: grant.owner,+ requester,+ })+ }++ async fn apps(&self, usage: &ConnectedAppUse) -> Result<Vec<ConnectedApp>, CodeModeError> {+ Ok(self.settle(usage).await?.apps)+ }++ async fn tools(+ &self,+ usage: &ConnectedAppUse,+ app: &ConnectedAppRef,+ ) -> Result<Vec<ConnectedTool>, CodeModeError> {+ let settled = self.settle(usage).await?;+ let destination = Self::destination(&settled, app)?;++ let mut tools = Vec::new();+ let mut cursor: Option<Value> = None;+ for page in 0..MAX_TOOL_PAGES {+ let params = match &cursor {+ Some(cursor) => json!({ "cursor": cursor }),+ None => json!({}),+ };+ let request =+ json!({"jsonrpc": "2.0", "id": page, "method": "tools/list", "params": params});+ let result = self+ .egress+ .exchange_as(&settled.grant, &settled.user, &destination, request)+ .await+ .map_err(egress_error)?;+ tools.extend(listed_tools(&result));++ cursor = result+ .get("nextCursor")+ .filter(|next| !next.is_null())+ .cloned();+ if cursor.is_none() {+ break;+ }+ }+ Ok(tools)+ }++ async fn call(+ &self,+ usage: &ConnectedAppUse,+ app: &ConnectedAppRef,+ call: CallConnectedTool,+ ) -> Result<ConnectedToolResult, CodeModeError> {+ let settled = self.settle(usage).await?;+ let destination = Self::destination(&settled, app)?;++ let request = json!({+ "jsonrpc": "2.0",+ "id": 1,+ "method": "tools/call",+ "params": {"name": call.tool, "arguments": call.arguments},+ });+ let result = self+ .egress+ .exchange_as(&settled.grant, &settled.user, &destination, request)+ .await+ .map_err(egress_error)?;+ Ok(ConnectedToolResult {+ is_error: result["isError"].as_bool().unwrap_or(false),+ content: result["content"].as_array().cloned().unwrap_or_default(),+ structured_content: result+ .get("structuredContent")+ .filter(|content| !content.is_null())+ .cloned(),+ })+ }++ async fn discover(+ &self,+ usage: &ConnectedAppUse,+ request: DiscoveryRequest,+ ) -> Result<DiscoverConnectorsResponse, CodeModeError> {+ let arguments = json!({ "request": &request });+ self.gate(usage, "DiscoverConnectors", arguments).await?;+ let result = self+ .connectors+ .service+ .discover(&usage.user, &request)+ .await+ .map_err(|error| CodeModeError::Invalid(error.to_string()))?;+ Ok(DiscoverConnectorsResponse::from(result))+ }++ async fn add_server(+ &self,+ usage: &ConnectedAppUse,+ server: ConnectMcpServer,+ ) -> Result<ConnectMcpServerResponse, CodeModeError> {+ let arguments = json!({ "url": &server.url, "serverName": &server.server_name });+ self.gate(usage, "ConnectMcpServer", arguments).await?;+ let directory = self+ .mcp_servers+ .servers+ .as_ref()+ .ok_or(CodeModeError::Unavailable)?;+ let added = directory+ .add(+ usage.user.clone(),+ &server.url,+ &server.server_name,+ AddedBy::Agent,+ )+ .await+ .map_err(|error| match error {+ AddServerError::InvalidUrl(_)+ | AddServerError::NonPublicDestination(_)+ | AddServerError::EmptyName => CodeModeError::Invalid(error.to_string()),+ AddServerError::Store(error) => {+ tracing::error!(?error, "could not save an MCP server");+ CodeModeError::Unavailable+ }+ })?;+ Ok(ConnectMcpServerResponse::from(added))+ }+}++/// The tools a `tools/list` result names, skipping entries with no name.+fn listed_tools(result: &Value) -> Vec<ConnectedTool> {+ let Some(tools) = result["tools"].as_array() else {+ return Vec::new();+ };+ tools+ .iter()+ .filter_map(|tool| {+ Some(ConnectedTool {+ name: tool["name"].as_str()?.to_owned(),+ description: tool["description"].as_str().map(str::to_owned),+ input_schema: tool+ .get("inputSchema")+ .cloned()+ .unwrap_or_else(|| json!({"type": "object"})),+ })+ })+ .collect()+}++fn egress_error(error: EgressError) -> CodeModeError {+ match error {+ EgressError::Unauthenticated(_) | EgressError::SessionClosed => CodeModeError::Forbidden,+ EgressError::UnknownServer(_)+ | EgressError::UnknownCustomServer(_)+ | EgressError::Unroutable(_) => CodeModeError::NotFound,+ error => {+ tracing::error!(%error, "a connected app could not be reached");+ CodeModeError::Unavailable+ }+ }+}diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex e5274325b0..8abe9d864e 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -744,6 +744,30 @@ async fn run() -> anyhow::Result<()> {Arc::new(runner.clone()) as Arc<dyn code_execution::domain::ProgramExecutor>});let code_mode_enabled = code_executor.is_some();+ let execution_store: Arc<dyn agent_code_mode::domain::ExecutionStore> = Arc::new(+ agent_code_mode::outbound::postgres::PgExecutionStore::new(pool.clone()),+ );+ let execution_turns: Arc<dyn agent_code_mode::domain::ExecutionTurns> = Arc::new(+ agent_code_mode::outbound::turns::SessionTurns(session_repo.clone()),+ );+ // A running execution reaches the apps its session's agent was given,+ // through the same egress credential resolution as the agent's own calls.+ let connected_apps = agent_code_mode::domain::connected_apps::ConnectedAppService::new(+ Arc::clone(&execution_store),+ Arc::clone(&execution_turns),+ Arc::new(code_mode::connected_apps::SessionConnectedApps {+ egress: Arc::clone(&egress),+ provisioner: EgressProvisioner::new(+ Arc::clone(&mcp_connections),+ Arc::clone(&mcp_servers),+ egress_base_url.clone(),+ ),+ sessions: session_repo.clone(),+ gate: owner_tool_gate.clone(),+ connectors: tool_context.connector_tool_context.clone(),+ mcp_servers: tool_context.mcp_server_tool_context.clone(),+ }),+ );let code_mode: Arc<dyn agent_code_mode::domain::SessionCodeMode> =Arc::new(agent_code_mode::domain::CodeModeService::new(code_executor,@@ -756,12 +780,8 @@ async fn run() -> anyhow::Result<()> {gate: owner_tool_gate.clone(),hosts: code_mode::sdk_hosts()?,}),- Arc::new(agent_code_mode::outbound::postgres::PgExecutionStore::new(- pool.clone(),- )),- Arc::new(agent_code_mode::outbound::turns::SessionTurns(- session_repo.clone(),- )),+ execution_store,+ execution_turns,));let session_metadata_realtime = ConnectionGatewayAgentSessionRealtime::new(connection_gateway.clone(),@@ -1679,6 +1699,7 @@ async fn run() -> anyhow::Result<()> {agent_code_mode::inbound::axum_router::CodeExecutionRouterState::new(code_mode,reviews,+ connected_apps,entity_access.clone(),MacroAuthorizationState::new(Arc::new(authorization_service.clone())),),