@composio/core 0.27.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/{CustomTool-CqPoLUD6.d.mts → CustomTool-DyypijT6.d.mts} +2 -2
  2. package/dist/{Telemetry-41JkqpZ7.mjs → Telemetry-D2PJwXKx.mjs} +1 -1
  3. package/dist/{composio-BUa10iB3.d.mts → composio-CwHMpKXb.d.mts} +704 -26
  4. package/dist/{customTool.types-gX421uPT.d.mts → customTool.types-DoItUHkO.d.mts} +11 -10
  5. package/dist/docs/reference/sdk-reference/typescript/session.mdx +3 -3
  6. package/dist/experimental/index.d.mts +2 -2
  7. package/dist/{fileUtils.node-DNLhLg0W.mjs → fileUtils.node-ILI1IjnZ.mjs} +4 -3
  8. package/dist/index.d.mts +4 -4
  9. package/dist/index.mjs +2107 -1977
  10. package/dist/models/Files.node.mjs +2 -2
  11. package/dist/sensitiveFileUploadPaths-BaEORC7-.mjs +588 -0
  12. package/dist/{types-DXxfzBX3.d.mts → types-DWZWePfZ.d.mts} +2 -2
  13. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -1
  14. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -1
  15. package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -1
  16. package/dist/utils/modifiers/FileToolModifier.node.mjs +1 -1
  17. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -1
  18. package/package.json +7 -6
  19. package/src/lib/toolRouterParams.ts +28 -33
  20. package/src/lib/toolRouterSessionDelete.ts +1 -10
  21. package/src/models/ConnectedAccounts.ts +1 -1
  22. package/src/models/CustomTool.ts +1 -1
  23. package/src/models/CustomToolkits.ts +114 -8
  24. package/src/models/Experimental.ts +1 -1
  25. package/src/models/MCP.ts +1 -2
  26. package/src/models/SessionConfigs.ts +11 -3
  27. package/src/models/SessionContext.ts +4 -4
  28. package/src/models/ToolRouter.ts +2 -3
  29. package/src/models/ToolRouterSession.ts +17 -16
  30. package/src/models/Tools.ts +3 -3
  31. package/src/models/Triggers.ts +12 -5
  32. package/src/models/inlineCustomToolsPayload.ts +3 -3
  33. package/src/models/proxyParamsTransform.ts +1 -1
  34. package/src/types/customTool.types.ts +13 -5
  35. package/src/types/customToolkits.types.ts +89 -9
  36. package/src/types/sessionConfigs.types.ts +21 -7
  37. package/src/types/toolRouter.types.ts +14 -7
  38. package/src/types/triggers.types.ts +14 -0
  39. package/src/utils/fileUtils.node.ts +5 -2
  40. package/src/utils/mime.ts +347 -1
  41. package/src/utils/transformers/connectedAccounts.ts +2 -7
  42. package/src/utils/transformers/customToolkits.ts +78 -9
  43. package/src/utils/transformers/sessionConfigs.ts +3 -3
  44. package/src/utils/transformers/toolRouterResponseTransform.ts +23 -75
  45. package/src/utils/transformers/toolkits.ts +7 -13
  46. package/src/utils/transformers/triggers.ts +28 -18
  47. package/dist/sensitiveFileUploadPaths-BlLp-Yo2.mjs +0 -189
package/dist/index.mjs CHANGED
@@ -3,8 +3,8 @@ import { $ as ComposioAuthConfigNotFoundError, A as ComposioInvalidModifierError
3
3
  import { a as ComposioSensitiveFilePathBlockedError, i as ComposioFileUploadPathNotAllowedError, n as ComposioFileUploadAbortedError, o as FileModifierErrorCodes, r as ComposioFileUploadError, t as ComposioFileNotFoundError } from "./FileModifierErrors-CdGSABoq.mjs";
4
4
  import { n as dropEmptyFileUploads, o as isPlainObject, s as schemaHasFileUploadable } from "./FileToolModifier.utils.neutral-DWFpnsj2.mjs";
5
5
  import { a as jsonSchemaToZodSchema, c as toStrictJsonSchema, i as ensureObjectTypeOnProperties, n as deduplicateJsonSchemaRequiredArrays, o as omitNullToolArguments, r as dereferenceJsonSchema, s as removeNonRequiredProperties, t as withCancellation } from "./cancellation-ZoRh6EJQ.mjs";
6
- import { t as telemetry } from "./Telemetry-41JkqpZ7.mjs";
7
- import { a as readResponseBodyWithLimit, i as MAX_URL_UPLOAD_SIZE_BYTES, l as getRandomShortId, n as assertSafeFileUploadPath, o as arrayBufferToBase64, r as isBlockedSensitiveFileUploadPath, t as BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS } from "./sensitiveFileUploadPaths-BlLp-Yo2.mjs";
6
+ import { t as telemetry } from "./Telemetry-D2PJwXKx.mjs";
7
+ import { c as arrayBufferToBase64, d as getRandomShortId, i as getExtensionFromMimeType, n as assertSafeFileUploadPath, o as MAX_URL_UPLOAD_SIZE_BYTES, r as isBlockedSensitiveFileUploadPath, s as readResponseBodyWithLimit, t as BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS } from "./sensitiveFileUploadPaths-BaEORC7-.mjs";
8
8
  import { a as createCustomToolkit, c as getPreloadedCustomToolSlugs, d as CreateCustomToolBaseSchema, f as CreateCustomToolkitBaseSchema, i as createCustomTool, l as serializeCustomToolkits, n as buildCustomToolsMap, o as findCustomToolMapEntryByFinalSlug, p as CustomToolSlugSchema, r as buildCustomToolsMapFromResponse, s as findCustomToolMapEntryByToolkitAndOriginalSlug, t as assertNoCustomToolSlugsInPreload, u as serializeCustomTools } from "./CustomTool-BYHB7sPs.mjs";
9
9
  import ComposioClient, { APIError, Auth, BadRequestError, ConflictError, createFetchTransport } from "@composio/client";
10
10
  import { FileToolModifier } from "#file_tool_modifier";
@@ -1211,1254 +1211,370 @@ function withoutRetries(requestOptions) {
1211
1211
  }
1212
1212
 
1213
1213
  //#endregion
1214
- //#region src/types/connectedAccounts.types.ts
1214
+ //#region src/utils/transformers/toolRouterResponseTransform.ts
1215
1215
  /**
1216
- * Connected Account create parameters
1216
+ * The `result_type` values of a call that ran. `input_required` and `blocked`
1217
+ * are handled before this is read.
1217
1218
  */
1218
- const ConnectedAccountStatuses = {
1219
- INITIALIZING: "INITIALIZING",
1220
- INITIATED: "INITIATED",
1221
- ACTIVE: "ACTIVE",
1222
- FAILED: "FAILED",
1223
- EXPIRED: "EXPIRED",
1224
- INACTIVE: "INACTIVE",
1225
- REVOKED: "REVOKED"
1226
- };
1227
- const ConnectedAccountStatusSchema = z$1.enum([
1228
- ConnectedAccountStatuses.INITIALIZING,
1229
- ConnectedAccountStatuses.INITIATED,
1230
- ConnectedAccountStatuses.ACTIVE,
1231
- ConnectedAccountStatuses.FAILED,
1232
- ConnectedAccountStatuses.EXPIRED,
1233
- ConnectedAccountStatuses.INACTIVE,
1234
- ConnectedAccountStatuses.REVOKED
1235
- ]);
1219
+ const ExecutedResponseSchema = z.object({ result_type: z.enum(["completed", "failed"]) });
1220
+ /** The `reason` of a call a session hook blocked, in camelCase. */
1221
+ const toBlockReason = (reason) => ({
1222
+ type: reason.type,
1223
+ hookId: reason.hook_id
1224
+ });
1236
1225
  /**
1237
- * Sharing model for a connected account.
1238
- *
1239
- * - `PRIVATE` (default): only the owning `userId` can use the connection.
1240
- * - `SHARED`: can be used by other `userId`s, but only when the connection
1241
- * is explicitly pinned in a tool-router session's config and only when
1242
- * the requesting `userId` passes the connection's ACL (see
1243
- * `allowAllUsers` / `allowedUserIds` / `notAllowedUserIds`).
1226
+ * Whether a session tool execution succeeded. `resultType` decides: a `failed`
1227
+ * execution is not successful even when its `error` is `null` or empty.
1244
1228
  */
1245
- const ConnectedAccountTypes = {
1246
- PRIVATE: "PRIVATE",
1247
- SHARED: "SHARED"
1248
- };
1249
- const ConnectedAccountTypeSchema = z$1.enum([ConnectedAccountTypes.PRIVATE, ConnectedAccountTypes.SHARED]);
1229
+ function isExecutionSuccessful(result) {
1230
+ return result.resultType === "completed";
1231
+ }
1250
1232
  /**
1251
- * Per-user access control for a SHARED connected account. Ignored for
1252
- * PRIVATE.
1253
- *
1254
- * Pass `aclConfigForShared` on create / PATCH to grant access; omit it
1255
- * to leave the ACL unchanged (on PATCH) or to keep the default
1256
- * deny-by-default state (on create). On responses, the field is
1257
- * `undefined` when the caller isn't authorised to see the ACL —
1258
- * distinguish that from an empty/default state explicitly.
1259
- *
1260
- * Resolution rule (deny wins):
1261
- * 1. requesting `userId` in `notAllowedUserIds` → DENY
1262
- * 2. `allowAllUsers === true` → ALLOW
1263
- * 3. requesting `userId` in `allowedUserIds` → ALLOW
1264
- * 4. otherwise → DENY (deny-by-default)
1265
- *
1266
- * Default state (block omitted or `{}`) means only the connection's
1267
- * creator can use it. The creator must grant access explicitly.
1268
- *
1269
- * Limits: each list accepts up to 1000 entries; each `userId` is
1270
- * 1..256 characters.
1233
+ * Narrows an execute-family response to the variants that carry a result.
1234
+ * `input_required` means the call did not run: it is raised as a
1235
+ * {@link ComposioToolInputRequiredError} instead of being returned as a result
1236
+ * it is not.
1271
1237
  */
1272
- const ACL_LIST_MAX_LENGTH = 1e3;
1273
- const aclUserIdString = z$1.string().min(1).max(256);
1274
- const ConnectedAccountAclConfigSchema = z$1.object({
1275
- allowAllUsers: z$1.boolean().optional().describe("When true, any `userId` may use this SHARED connection (subject to the deny list). Default false."),
1276
- allowedUserIds: z$1.array(aclUserIdString).max(ACL_LIST_MAX_LENGTH).optional().describe("Explicit list of `userId` strings allowed to use this SHARED connection. Default []."),
1277
- notAllowedUserIds: z$1.array(aclUserIdString).max(ACL_LIST_MAX_LENGTH).optional().describe("Explicit list of `userId` strings denied access. Wins over allow on conflict. Default [].")
1278
- });
1238
+ function assertNotInputRequired(raw, subject) {
1239
+ if (raw.result_type !== "input_required") return;
1240
+ throw new ComposioToolInputRequiredError(subject, {
1241
+ inputRequests: Object.fromEntries(Object.entries(raw.input_requests).map(([id, request]) => [id, {
1242
+ type: request.type,
1243
+ mode: request.mode,
1244
+ message: request.message,
1245
+ requestedSchema: request.requested_schema
1246
+ }])),
1247
+ requestState: raw.request_state
1248
+ });
1249
+ }
1250
+ function transformSearchResult(raw) {
1251
+ return {
1252
+ index: raw.index,
1253
+ useCase: raw.use_case,
1254
+ primaryToolSlugs: raw.primary_tool_slugs,
1255
+ relatedToolSlugs: raw.related_tool_slugs,
1256
+ toolkits: raw.toolkits,
1257
+ difficulty: raw.difficulty,
1258
+ error: raw.error,
1259
+ executionGuidance: raw.execution_guidance,
1260
+ knownPitfalls: raw.known_pitfalls,
1261
+ memory: raw.memory,
1262
+ planId: raw.plan_id,
1263
+ recommendedPlanSteps: raw.recommended_plan_steps,
1264
+ referenceWorkbenchSnippets: raw.reference_workbench_snippets
1265
+ };
1266
+ }
1267
+ function transformToolSchema(raw) {
1268
+ return {
1269
+ toolSlug: raw.tool_slug,
1270
+ toolkit: raw.toolkit,
1271
+ description: raw.description,
1272
+ hasFullSchema: raw.hasFullSchema,
1273
+ inputSchema: raw.input_schema,
1274
+ outputSchema: raw.output_schema,
1275
+ schemaRef: raw.schemaRef ? {
1276
+ args: { toolSlugs: raw.schemaRef.args.tool_slugs },
1277
+ message: raw.schemaRef.message,
1278
+ tool: raw.schemaRef.tool
1279
+ } : void 0
1280
+ };
1281
+ }
1282
+ function transformToolkitConnectionStatus(raw) {
1283
+ return {
1284
+ toolkit: raw.toolkit,
1285
+ description: raw.description,
1286
+ hasActiveConnection: raw.has_active_connection,
1287
+ statusMessage: raw.status_message,
1288
+ connectionDetails: raw.connection_details,
1289
+ currentUserInfo: raw.current_user_info,
1290
+ ...raw.instant_account !== void 0 && { instantAccount: {
1291
+ allowedToolSlugs: raw.instant_account.allowed_tool_slugs,
1292
+ ...raw.instant_account.prices !== void 0 && { prices: raw.instant_account.prices }
1293
+ } }
1294
+ };
1295
+ }
1279
1296
  /**
1280
- * Resolved ACL as it appears on responses. All three fields are populated
1281
- * when the field is visible; the field itself is `undefined` for callers
1282
- * not authorised to see it.
1297
+ * Transforms a raw session search API response to camelCase.
1283
1298
  */
1284
- const ConnectedAccountAclConfigResponseSchema = z$1.object({
1285
- allowAllUsers: z$1.boolean(),
1286
- allowedUserIds: z$1.array(z$1.string()),
1287
- notAllowedUserIds: z$1.array(z$1.string())
1288
- });
1299
+ function transformSearchResponse(raw) {
1300
+ const toolSchemas = {};
1301
+ for (const [slug, schema] of Object.entries(raw.tool_schemas)) toolSchemas[slug] = transformToolSchema(schema);
1302
+ return {
1303
+ success: raw.success,
1304
+ error: raw.error,
1305
+ results: raw.results.map(transformSearchResult),
1306
+ toolSchemas,
1307
+ toolkitConnectionStatuses: raw.toolkit_connection_statuses.map(transformToolkitConnectionStatus),
1308
+ nextStepsGuidance: raw.next_steps_guidance,
1309
+ session: {
1310
+ id: raw.session.id,
1311
+ generateId: raw.session.generate_id,
1312
+ instructions: raw.session.instructions
1313
+ },
1314
+ timeInfo: {
1315
+ currentTimeUtc: raw.time_info.current_time_utc,
1316
+ currentTimeUtcEpochSeconds: raw.time_info.current_time_utc_epoch_seconds,
1317
+ message: raw.time_info.message
1318
+ }
1319
+ };
1320
+ }
1289
1321
  /**
1290
- * Experimental options for SHARED connections, passed at create / link time.
1322
+ * Transforms a raw session execute API response to camelCase.
1291
1323
  *
1292
- * **Experimental — shape may change in future releases.** Wrapped under a
1293
- * dedicated `experimental` block on every input and response so the
1294
- * experimental status is visible at every call site.
1324
+ * @throws {ComposioToolInputRequiredError} If the tool asked for user input instead of running
1325
+ * @throws {ValidationError} If the response carries no `result_type`, or one this SDK does not know
1295
1326
  */
1296
- const ConnectedAccountExperimentalSchema = z$1.object({
1297
- accountType: ConnectedAccountTypeSchema.optional(),
1298
- aclConfigForShared: ConnectedAccountAclConfigSchema.optional()
1299
- });
1327
+ function transformExecuteResponse(raw, toolSlug) {
1328
+ assertNotInputRequired(raw, `Tool ${toolSlug}`);
1329
+ if (raw.result_type === "blocked") return {
1330
+ data: {},
1331
+ error: raw.message,
1332
+ logId: raw.log_id ?? "",
1333
+ resultType: "blocked",
1334
+ blockReason: toBlockReason(raw.reason),
1335
+ ...raw.hook_results !== void 0 && { hookResults: raw.hook_results },
1336
+ ...raw.instant_charge !== void 0 && { instantCharge: raw.instant_charge }
1337
+ };
1338
+ const executed = ExecutedResponseSchema.safeParse(raw);
1339
+ if (!executed.success) throw new ValidationError(`Tool ${toolSlug} returned an execute response without a known result_type`, { cause: executed.error });
1340
+ return {
1341
+ data: raw.data,
1342
+ error: raw.error,
1343
+ logId: raw.log_id,
1344
+ resultType: executed.data.result_type,
1345
+ ...raw.instant_charge !== void 0 && { instantCharge: raw.instant_charge },
1346
+ ...raw.hook_results !== void 0 && { hookResults: raw.hook_results }
1347
+ };
1348
+ }
1300
1349
  /**
1301
- * Resolved experimental block on retrieve / list responses. `accountType`
1302
- * is always present when the block is; `aclConfigForShared` is only
1303
- * present when the caller is authorised to see the ACL.
1350
+ * Projects a session proxy execute response onto the SDK's shape: a request a
1351
+ * session hook blocked comes back as `resultType: 'blocked'` with no HTTP
1352
+ * response.
1304
1353
  */
1305
- const ConnectedAccountExperimentalResponseSchema = z$1.object({
1306
- accountType: ConnectedAccountTypeSchema.optional(),
1307
- aclConfigForShared: ConnectedAccountAclConfigResponseSchema.optional()
1308
- });
1309
- const CreateConnectedAccountParamsSchema = z$1.object({
1310
- authConfig: z$1.object({ id: z$1.string() }),
1311
- connection: z$1.object({
1312
- data: z$1.record(z$1.string(), z$1.unknown()).optional(),
1313
- callbackUrl: z$1.string().optional(),
1314
- userId: z$1.string().optional()
1315
- })
1316
- });
1317
- const DefaultCreateConnectedAccountParamsSchema = z$1.object({
1318
- auth_config: z$1.object({ id: z$1.string() }),
1319
- connection: z$1.object({
1320
- state: ConnectionDataSchema.optional(),
1321
- data: z$1.record(z$1.string(), z$1.unknown()).optional(),
1322
- callback_url: z$1.string().optional(),
1323
- user_id: z$1.string().optional(),
1324
- alias: z$1.string().optional()
1325
- })
1326
- });
1327
- const CreateConnectedAccountOptionsSchema = z$1.object({
1328
- allowMultiple: z$1.boolean().optional(),
1329
- callbackUrl: z$1.string().optional(),
1330
- config: ConnectionDataSchema.optional(),
1331
- alias: z$1.string().optional()
1332
- });
1354
+ function transformProxyExecuteResponse(raw, subject) {
1355
+ assertNotInputRequired(raw, subject);
1356
+ if (raw.result_type === "blocked") return {
1357
+ resultType: "blocked",
1358
+ blockReason: toBlockReason(raw.reason),
1359
+ message: raw.message,
1360
+ ...raw.hook_results !== void 0 && { hookResults: raw.hook_results }
1361
+ };
1362
+ return {
1363
+ resultType: "completed",
1364
+ status: raw.status,
1365
+ data: raw.data,
1366
+ headers: raw.headers,
1367
+ ...raw.binary_data && { binaryData: {
1368
+ contentType: raw.binary_data.content_type,
1369
+ size: raw.binary_data.size,
1370
+ url: raw.binary_data.url,
1371
+ expiresAt: raw.binary_data.expires_at
1372
+ } },
1373
+ ...raw.hook_results !== void 0 && { hookResults: raw.hook_results }
1374
+ };
1375
+ }
1376
+
1377
+ //#endregion
1378
+ //#region src/models/Tools.ts
1379
+ const TOOL_ROUTER_SESSION_TOOLS_PAGE_LIMIT = 500;
1333
1380
  /**
1334
- * Connected Account create response
1381
+ * Normalize a raw `input_parameters` / `output_parameters` payload returned by
1382
+ * the Composio API. Maps `null`, `undefined`, and empty `{}` — all of which
1383
+ * mean "no declared schema" — to `undefined` so the strict `ParametersSchema`
1384
+ * validator never sees them. Non-empty objects pass through unchanged and
1385
+ * remain subject to strict Zod validation.
1386
+ *
1387
+ * MCP-backed toolkits (granola_mcp, apify_mcp, tavily_mcp, …) have no
1388
+ * declared output schema and the API serializes that as `{}`, which would
1389
+ * otherwise trip `ParametersSchema`. See
1390
+ * https://github.com/ComposioHQ/composio/issues/3354.
1335
1391
  */
1336
- const CreateConnectedAccountResponseSchema = z$1.object({
1337
- id: z$1.string(),
1338
- status: ConnectedAccountStatusSchema,
1339
- redirectUrl: z$1.string().nullable()
1340
- });
1341
- const ConnectedAccountAuthConfigSchema = z$1.object({
1342
- id: z$1.string(),
1343
- /** @deprecated Use `connectedAccount.state.authScheme` instead. */
1344
- authScheme: AuthSchemeEnum.optional(),
1345
- isComposioManaged: z$1.boolean(),
1346
- isDisabled: z$1.boolean()
1347
- });
1348
- const ConnectedAccountRetrieveResponseSchema = z$1.object({
1349
- id: z$1.string(),
1350
- authConfig: ConnectedAccountAuthConfigSchema,
1351
- wordId: z$1.string().nullable().optional(),
1352
- alias: z$1.string().nullable().optional(),
1392
+ function normalizeRawToolParameters(params) {
1393
+ if (params == null || Object.keys(params).length === 0) return void 0;
1394
+ return params;
1395
+ }
1396
+ /**
1397
+ * This class is used to manage tools in the Composio SDK.
1398
+ * It provides methods to list, get, and execute tools.
1399
+ */
1400
+ var Tools = class {
1401
+ client;
1402
+ provider;
1403
+ autoUploadDownloadFiles;
1404
+ toolkitVersions;
1405
+ fileUploadPathOptions;
1353
1406
  /**
1354
- * @deprecated Use `connectedAccount.state` instead — `data` is a legacy raw credential field.
1407
+ * Tracks tool slugs we've already warned about to avoid spamming the log when
1408
+ * the same file-input tool is executed repeatedly while auto-upload is off.
1409
+ * Scoped per-instance so a fresh `Composio` starts with a clean slate.
1355
1410
  */
1356
- data: z$1.record(z$1.string(), z$1.unknown()).optional(),
1411
+ warnedAutoUploadDisabledForTool = /* @__PURE__ */ new Set();
1412
+ constructor(client, config) {
1413
+ if (!client) throw new Error("ComposioClient is required");
1414
+ if (!config?.provider) throw new ComposioProviderNotDefinedError("Provider not passed into Tools instance");
1415
+ this.client = client;
1416
+ this.provider = config.provider;
1417
+ this.autoUploadDownloadFiles = config?.dangerouslyAllowAutoUploadDownloadFiles === true;
1418
+ this.toolkitVersions = config?.toolkitVersions ?? CONFIG_DEFAULTS.toolkitVersions;
1419
+ this.fileUploadPathOptions = {
1420
+ sensitiveFileUploadProtection: config?.sensitiveFileUploadProtection,
1421
+ fileUploadPathDenySegments: config?.fileUploadPathDenySegments,
1422
+ fileUploadAllowlist: this.autoUploadDownloadFiles ? resolveEffectiveUploadAllowlist(config?.fileUploadDirs) : void 0,
1423
+ fileDownloadDir: config?.fileDownloadDir
1424
+ };
1425
+ this.execute = this.execute.bind(this);
1426
+ this.provider._setExecuteToolFn(this.createExecuteFnForProviders());
1427
+ this.getRawComposioToolBySlug = this.getRawComposioToolBySlug.bind(this);
1428
+ this.getRawComposioTools = this.getRawComposioTools.bind(this);
1429
+ telemetry.instrument(this, "Tools");
1430
+ }
1357
1431
  /**
1358
- * @deprecated Use `connectedAccount.state` instead — `params` is a legacy raw credential field.
1432
+ * Transforms tool data from snake_case API format to camelCase for internal SDK use.
1433
+ *
1434
+ * This method standardizes the property naming convention for tools retrieved from the Composio API,
1435
+ * making them more consistent with JavaScript/TypeScript conventions.
1436
+ *
1437
+ * @param {ToolRetrieveResponse | ComposioToolListResponse['items'][0]} tool - The tool object to transform
1438
+ * @returns {Tool} The transformed tool with camelCase properties
1439
+ *
1440
+ * @private
1359
1441
  */
1360
- params: z$1.record(z$1.string(), z$1.unknown()).optional(),
1361
- status: ConnectedAccountStatusSchema,
1362
- statusReason: z$1.string().nullable(),
1363
- toolkit: z$1.object({ slug: z$1.string() }),
1364
- state: ConnectionDataSchema.optional(),
1365
- testRequestEndpoint: z$1.string().optional(),
1366
- isDisabled: z$1.boolean(),
1367
- createdAt: z$1.string(),
1368
- updatedAt: z$1.string(),
1369
- experimental: ConnectedAccountExperimentalResponseSchema.optional()
1370
- });
1371
- const ConnectedAccountListParamsSchema = z$1.object({
1372
- authConfigIds: z$1.array(z$1.string()).nullable().optional().describe("The auth config ids of the connected accounts"),
1373
- cursor: z$1.string().nullish().describe("The cursor to paginate through the connected accounts"),
1374
- limit: z$1.number().nullable().optional().describe("The limit of the connected accounts to return"),
1375
- orderBy: z$1.enum(["created_at", "updated_at"]).optional().describe("The order by of the connected accounts"),
1376
- statuses: z$1.array(ConnectedAccountStatusSchema).nullable().optional().describe("The statuses of the connected accounts"),
1377
- toolkitSlugs: z$1.array(z$1.string()).nullable().optional().describe("The toolkit slugs of the connected accounts"),
1378
- userIds: z$1.array(z$1.string()).nullable().optional().describe("The user ids of the connected accounts"),
1442
+ transformToolCases(tool) {
1443
+ return ToolSchema.parse({
1444
+ ...tool,
1445
+ inputParameters: normalizeRawToolParameters(tool.input_parameters),
1446
+ outputParameters: normalizeRawToolParameters(tool.output_parameters),
1447
+ availableVersions: tool.available_versions,
1448
+ isDeprecated: tool.deprecated?.is_deprecated ?? false,
1449
+ isNoAuth: tool.no_auth
1450
+ });
1451
+ }
1379
1452
  /**
1380
- * Experimental — shape may change in future releases. Filter by sharing
1381
- * model. Default (omitted) returns PRIVATE only. Pass `'SHARED'` for only
1382
- * shared accounts, or `'ALL'` for `PRIVATE` + `SHARED`. Kept flat because
1383
- * the wire is a query string and can't carry nested objects.
1453
+ * Transforms tool execution response from snake_case API format to camelCase.
1454
+ *
1455
+ * This method converts the response received from the Composio API to a standardized format
1456
+ * with consistent property naming that follows JavaScript/TypeScript conventions.
1457
+ *
1458
+ * @param {ComposioToolExecuteResponse} response - The raw API response to transform
1459
+ * @returns {ToolExecuteResponse} The transformed response with camelCase properties
1460
+ *
1461
+ * @private
1384
1462
  */
1385
- accountType: z$1.enum([
1386
- "PRIVATE",
1387
- "SHARED",
1388
- "ALL"
1389
- ]).optional()
1390
- });
1391
- const ConnectedAccountListResponseSchema = z$1.object({
1392
- items: z$1.array(ConnectedAccountRetrieveResponseSchema).describe("The list of connected accounts"),
1393
- nextCursor: z$1.string().nullish().describe("The next cursor to paginate through the connected accounts"),
1394
- totalPages: z$1.number().describe("The total number of pages of connected accounts")
1395
- });
1396
- const CreateConnectedAccountLinkOptionsSchema = z$1.object({
1463
+ transformToolExecuteResponse(response) {
1464
+ return ToolExecuteResponseSchema.parse({
1465
+ data: response.data,
1466
+ error: response.error,
1467
+ successful: response.successful,
1468
+ logId: response.log_id,
1469
+ sessionInfo: response.session_info
1470
+ });
1471
+ }
1397
1472
  /**
1398
- * The url to redirect the user to post connecting their account.
1473
+ * Applies the default schema modifiers to the tools.
1399
1474
  *
1400
- * For successful connections, you will get a query param called status=success
1401
- * And for failed connections you will get a query param called status=failed
1475
+ * The `file_uploadable` transform (collapsing the backend's internal
1476
+ * `{ name, mimetype, s3key }` staging shape to `{ type: 'string',
1477
+ * format: 'path' }`) is **gated on `dangerouslyAllowAutoUploadDownloadFiles`**
1478
+ * — the collapsed shape is a promise that the SDK will stage local paths
1479
+ * on your behalf at execute time, and that's only true when the flag is on.
1402
1480
  *
1403
- * @example https://your-app.com/callback
1481
+ * When the flag is off, the raw schema is returned unchanged; callers are
1482
+ * expected to stage files themselves via `composio.files.upload()` and pass
1483
+ * the resulting descriptor into `tools.execute`. If an LLM ends up calling
1484
+ * a file-uploadable tool in this mode, the execute path emits a one-shot
1485
+ * warning per tool slug (see `applyBeforeExecuteModifiers`).
1404
1486
  *
1487
+ * @param tools - The tools to apply the default schema modifiers to
1488
+ * @returns The tools with the default schema modifiers applied
1405
1489
  */
1406
- callbackUrl: z$1.string().optional(),
1490
+ async applyDefaultSchemaModifiers(tools) {
1491
+ if (!this.autoUploadDownloadFiles) return tools;
1492
+ const fileToolModifier = new FileToolModifier(this.client, this.fileUploadPathOptions);
1493
+ return await Promise.all(tools.map((tool) => fileToolModifier.modifyToolSchema(tool)));
1494
+ }
1407
1495
  /**
1408
- * Human-readable alias for the connected account. Must be unique per userId and toolkit within the project.
1496
+ * Applies the before execute modifiers to the tool execution params
1497
+ * @param options.toolSlug - The slug of the tool
1498
+ * @param options.toolkitSlug - The slug of the toolkit
1499
+ * @param options.params - The params of the tool execution
1500
+ * @param modifier - The modifier to apply
1501
+ * @returns The modified params
1409
1502
  */
1410
- alias: z$1.string().optional(),
1503
+ async applyBeforeExecuteModifiers(tool, { toolSlug, toolkitSlug, params }, modifiers, requestOptions) {
1504
+ if (requestOptions?.signal?.aborted) throw new ComposioRequestCancelledError();
1505
+ let modifiedParams = await this.applyFileUploadModifiers(tool, {
1506
+ toolSlug,
1507
+ toolkitSlug,
1508
+ params
1509
+ }, modifiers?.beforeFileUpload, requestOptions);
1510
+ if (modifiers?.beforeExecute) {
1511
+ if (typeof modifiers.beforeExecute === "function") {
1512
+ modifiedParams = await modifiers.beforeExecute({
1513
+ toolSlug,
1514
+ toolkitSlug,
1515
+ params: modifiedParams
1516
+ });
1517
+ if (requestOptions?.signal?.aborted) throw new ComposioRequestCancelledError();
1518
+ } else throw new ComposioInvalidModifierError("Invalid beforeExecute modifier. Not a function.");
1519
+ }
1520
+ return modifiedParams;
1521
+ }
1411
1522
  /**
1412
- * Whether to allow multiple connected accounts for the same user and auth config.
1413
- * When `false` (default), `link()` throws `ComposioMultipleConnectedAccountsError`
1414
- * if the user already has an `ACTIVE` connection on this auth config — matching
1415
- * the guard on `initiate()`. Pair with `alias` and a session-level
1416
- * `multiAccount` config to disambiguate at execution time.
1523
+ * Applies schema-aware file preprocessing shared by direct and Tool Router
1524
+ * session execution. This always runs before the caller's `beforeExecute`
1525
+ * hook so the hook observes the exact arguments sent to the backend.
1417
1526
  */
1418
- allowMultiple: z$1.boolean().optional(),
1527
+ async applyFileUploadModifiers(tool, { toolSlug, toolkitSlug, params }, beforeFileUpload, requestOptions) {
1528
+ let modifiedParams = params;
1529
+ if (this.autoUploadDownloadFiles) {
1530
+ modifiedParams = await new FileToolModifier(this.client, {
1531
+ ...this.fileUploadPathOptions,
1532
+ beforeFileUpload
1533
+ }).fileUploadModifier(tool, {
1534
+ toolSlug,
1535
+ toolkitSlug,
1536
+ params: modifiedParams,
1537
+ signal: requestOptions?.signal
1538
+ });
1539
+ if (requestOptions?.signal?.aborted) throw new ComposioRequestCancelledError();
1540
+ } else if (tool.inputParameters && schemaHasFileUploadable(tool.inputParameters)) {
1541
+ if (modifiedParams.arguments) modifiedParams = {
1542
+ ...modifiedParams,
1543
+ arguments: await dropEmptyFileUploads(modifiedParams.arguments, dereferenceJsonSchema(tool.inputParameters, { onUnresolved: "sentinel" }))
1544
+ };
1545
+ if (!this.warnedAutoUploadDisabledForTool.has(toolSlug)) {
1546
+ this.warnedAutoUploadDisabledForTool.add(toolSlug);
1547
+ logger.warn(`Tool "${toolSlug}" (toolkit "${toolkitSlug}") has a file-uploadable input, but \`dangerouslyAllowAutoUploadDownloadFiles\` is disabled. The SDK will forward the file argument as-is; if it isn't already a staged { name, mimetype, s3key } descriptor, the backend will reject the call. Either:\n 1) Stage the file yourself: \`const f = await composio.files.upload({ file, toolSlug, toolkitSlug }); await composio.tools.execute('${toolSlug}', { userId, arguments: { <fileField>: f } })\`, or\n 2) Enable auto-upload with a scoped allowlist: \`new Composio({ dangerouslyAllowAutoUploadDownloadFiles: true, fileUploadDirs: ['/safe/dir'] })\`.`);
1548
+ }
1549
+ }
1550
+ return modifiedParams;
1551
+ }
1419
1552
  /**
1420
- * Experimental options for SHARED connections. Pass `accountType: 'SHARED'`
1421
- * (and optionally `aclConfigForShared`) to create a connection that can
1422
- * be reached by other `userId`s when pinned in a session.
1423
- *
1424
- * Experimental — shape may change in future releases.
1425
- *
1426
- * `aclConfigForShared` is only valid when `accountType === 'SHARED'`;
1427
- * raises `ComposioAclOnlyForSharedError` on a PRIVATE connection. Omit
1428
- * the inner block (or pass `{}`) to keep the deny-by-default state: only
1429
- * the creator can use the connection. Grant access by setting
1430
- * `allowAllUsers: true` or listing user IDs in `allowedUserIds`.
1431
- * `notAllowedUserIds` always wins over allow.
1553
+ * Applies the after execute modifiers to the tool execution result
1554
+ * @param options.toolSlug - The slug of the tool
1555
+ * @param options.toolkitSlug - The slug of the toolkit
1556
+ * @param options.result - The result of the tool execution
1557
+ * @param modifier - The modifier to apply
1558
+ * @returns The modified result
1432
1559
  */
1433
- experimental: ConnectedAccountExperimentalSchema.optional()
1434
- });
1435
- const CreateConnectedAccountLinkResponseSchema = z$1.object({ redirectUrl: z$1.string() });
1436
- const ConnectedAccountRefreshOptionsSchema = z$1.object({
1437
- redirectUrl: z$1.string().optional(),
1438
- /**
1439
- * @deprecated The Composio API no longer accepts this field. It is ignored
1440
- * and `refresh()` logs a warning when it is set.
1441
- */
1442
- validateCredentials: z$1.boolean().optional()
1443
- });
1444
- const UpdateConnectedAccountParamsSchema = z$1.object({ enabled: z$1.boolean() });
1445
- /**
1446
- * Params for `composio.connectedAccounts.updateAcl()`. Mirrors the inner
1447
- * shape of the wire's `acl_config_for_shared` block — the SDK adds the
1448
- * outer nesting at the boundary, so callers pass the three fields flat.
1449
- *
1450
- * PATCH-style semantics — omit a field to leave it unchanged; pass an
1451
- * empty array to clear an allow/deny list. Raises
1452
- * `ComposioAclOnlyForSharedError` on a PRIVATE connection.
1453
- *
1454
- * Each field is optional, but at least one must be provided — passing an
1455
- * empty object is rejected as a no-op.
1456
- */
1457
- const UpdateConnectedAccountAclParamsSchema = ConnectedAccountAclConfigSchema.refine((acl) => acl.allowAllUsers !== void 0 || acl.allowedUserIds !== void 0 || acl.notAllowedUserIds !== void 0, { message: "At least one of allowAllUsers, allowedUserIds, or notAllowedUserIds must be provided" });
1458
- /**
1459
- * Response of `composio.connectedAccounts.revoke()`.
1460
- */
1461
- const ConnectedAccountRevokedTokenSchema = z$1.enum([
1462
- "access_token",
1463
- "refresh_token",
1464
- "credential"
1465
- ]);
1466
- const ConnectedAccountRevokeResponseSchema = z$1.object({
1467
- /**
1468
- * Tokens revoked at the provider on this call. An empty array means the
1469
- * connection was already revoked (no upstream dispatch).
1470
- */
1471
- revokedTokens: z$1.array(ConnectedAccountRevokedTokenSchema),
1472
- connectedAccount: z$1.object({
1473
- id: z$1.string(),
1474
- /** The connection status after this call (`REVOKED` on success). */
1475
- status: ConnectedAccountStatusSchema
1476
- })
1477
- });
1478
- /**
1479
- * Params for `composio.connectedAccounts.completeAuth()`.
1480
- */
1481
- const ConnectedAccountCompleteAuthParamsSchema = z$1.object({
1482
- /** The user the connection was initiated for. Must match the connection owner. */
1483
- userId: z$1.string().min(1),
1484
- /** The opaque, single-use session URI your OAuth callback verifier received. */
1485
- sessionUri: z$1.string().min(1)
1486
- });
1487
- /**
1488
- * Response of `composio.connectedAccounts.completeAuth()`.
1489
- */
1490
- const ConnectedAccountCompleteAuthResponseSchema = z$1.object({
1491
- /** The connection that was completed; it is now `ACTIVE`. */
1492
- connectedAccountId: z$1.string(),
1493
- /** The toolkit the connection belongs to. */
1494
- toolkitSlug: z$1.string()
1495
- });
1496
-
1497
- //#endregion
1498
- //#region src/lib/sessionConfigConflict.ts
1499
- const SESSION_CONFIG_CONFLICT_MARKER = "sessionConfigConflict";
1500
- /**
1501
- * Adds the issue raised when a saved Session config (`experimental.sessionConfigId`)
1502
- * is combined with inline access fields. `fields` lists every conflicting
1503
- * field that was provided; nothing is added when it is empty.
1504
- */
1505
- const addSessionConfigConflictIssue = (ctx, fields) => {
1506
- if (fields.length === 0) return;
1507
- ctx.addIssue({
1508
- code: z$1.ZodIssueCode.custom,
1509
- message: `experimental.sessionConfigId cannot be combined with ${fields.join(", ")}. A saved Session config sets the session's toolkit, tool and tag access; remove ${fields.length === 1 ? "that field" : "those fields"} or sessionConfigId`,
1510
- path: ["experimental", "sessionConfigId"],
1511
- params: { [SESSION_CONFIG_CONFLICT_MARKER]: true }
1512
- });
1513
- };
1514
- /**
1515
- * Parses session create or update input. A saved Session config combined with
1516
- * inline access fields throws `ValidationError`; any other failure rethrows the
1517
- * original `ZodError`, as `schema.parse()` would.
1518
- */
1519
- const parseSessionConfigInput = (schema, input) => {
1520
- const result = schema.safeParse(input);
1521
- if (result.success) return result.data;
1522
- if (result.error.issues.some((issue) => issue.code === z$1.ZodIssueCode.custom && issue.params?.[SESSION_CONFIG_CONFLICT_MARKER])) throw new ValidationError("Invalid session config", { cause: result.error });
1523
- throw result.error;
1524
- };
1525
-
1526
- //#endregion
1527
- //#region src/types/toolRouter.types.ts
1528
- const SessionPreset = { DIRECT_TOOLS: "direct_tools" };
1529
- const MCPServerTypeSchema = z.enum(["http", "sse"]);
1530
- /**
1531
- * Sandbox compute tier for the session sandbox.
1532
- *
1533
- * | Tier | vCPU | RAM |
1534
- * | -------- | ---- | ----- |
1535
- * | standard | 1 | 1 GB |
1536
- * | medium | 2 | 2 GB |
1537
- * | large | 4 | 4 GB |
1538
- * | xlarge | 8 | 8 GB |
1539
- *
1540
- * Defaults to `standard` server-side when omitted.
1541
- */
1542
- const SandboxSizeSchema = z.enum([
1543
- "standard",
1544
- "medium",
1545
- "large",
1546
- "xlarge"
1547
- ]);
1548
- const ToolRouterSandboxConfigSchema = z.object({
1549
- enable: z.boolean().default(true).describe("Whether to enable the sandbox entirely. Defaults to true. When set to false, no code execution tools (COMPOSIO_REMOTE_WORKBENCH, COMPOSIO_REMOTE_BASH_TOOL) are available in the session."),
1550
- enableProxyExecution: z.boolean().optional().describe("Whether to enable proxy execution in the session sandbox"),
1551
- autoOffloadThreshold: z.number().optional().describe("The auto offload threshold in characters for tool execution to move into the sandbox"),
1552
- sandboxSize: SandboxSizeSchema.optional().describe("Sandbox compute tier. One of \"standard\" (1 vCPU / 1 GB), \"medium\" (2 vCPU / 2 GB), \"large\" (4 vCPU / 4 GB), or \"xlarge\" (8 vCPU / 8 GB). Defaults to \"standard\" server-side. Changing this on an existing session recreates the session sandbox on next access; the in-memory FS is lost, but /mnt/files/ persists.")
1553
- });
1554
- const ToolRouterConfigManageConnectionsSchema = z.object({
1555
- enable: z.boolean().default(true).optional().describe("Whether to use tools to manage connections in the tool router session. Defaults to true, if set to false, you need to manage connections manually"),
1556
- callbackUrl: z.string().optional().describe("The callback uri to use in the tool router session"),
1557
- waitForConnections: z.boolean().optional().describe("Whether to wait for users to finish authenticating connections before proceeding to the next step. Defaults to false, if set to true, a wait for connections tool call will happen and finish when the connections are ready")
1558
- }).strict();
1559
- const ToolRouterToolkitsParamSchema = z.array(z.string()).describe("List of toolkits to enable in the tool router session");
1560
- const ToolRouterToolkitsDisabledConfigSchema = z.object({ disable: ToolRouterToolkitsParamSchema.describe("List of toolkits to disable in the tool router session") }).strict();
1561
- const ToolRouterToolkitsEnabledConfigSchema = z.object({ enable: ToolRouterToolkitsParamSchema.describe("List of toolkits to enable in the tool router session") }).strict();
1562
- /**
1563
- * Toolkits whose tools need the user's approval before they run. A call that
1564
- * needs approval doesn't run: `session.execute()` throws
1565
- * `ComposioToolInputRequiredError` with the question to show the user.
1566
- * @experimental
1567
- */
1568
- const ToolRouterToolkitsRequireApprovalSchema = ToolRouterToolkitsParamSchema.describe("Experimental. Toolkits whose tools need the user approval before they run");
1569
- /** Session toolkit policy: a list to enable, an enable/disable object, or only an approval list. */
1570
- const ToolRouterSessionToolkitsSchema = z.union([
1571
- ToolRouterToolkitsParamSchema,
1572
- ToolRouterToolkitsDisabledConfigSchema.extend({ requireApproval: ToolRouterToolkitsRequireApprovalSchema.optional() }).strict(),
1573
- ToolRouterToolkitsEnabledConfigSchema.extend({ requireApproval: ToolRouterToolkitsRequireApprovalSchema.optional() }).strict(),
1574
- z.object({ requireApproval: ToolRouterToolkitsRequireApprovalSchema }).strict()
1575
- ]);
1576
- /**
1577
- * What happens to a call that needs the user's approval when the session's MCP
1578
- * client can't ask the user.
1579
- * @experimental
1580
- */
1581
- const ToolRouterNoElicitationSupportFallbackSchema = z.enum(["deny", "allow"]).describe("Experimental. What happens to a call that needs approval when the MCP client cannot ask the user");
1582
- /** Experimental Instant usage policy for a Session. */
1583
- const ToolRouterInstantSchema = z.union([z.literal(false), z.object({
1584
- toolkits: z.union([ToolRouterToolkitsEnabledConfigSchema, ToolRouterToolkitsDisabledConfigSchema]).optional(),
1585
- tools: z.record(z.string(), z.union([z.object({ enable: z.array(z.string()) }).strict(), z.object({ disable: z.array(z.string()) }).strict()])).optional(),
1586
- /**
1587
- * Return the actual Instant charge in Session tool responses. Controls
1588
- * visibility only; on update, any policy object still re-enables Instant
1589
- * usage on a Session set to `false`.
1590
- */
1591
- returnInstantCharge: z.boolean().optional(),
1592
- /**
1593
- * Experimental. Show each Instant tool's price in Session search
1594
- * results, under `toolkitConnectionStatuses[].instantAccount.prices`.
1595
- * Controls visibility only.
1596
- */
1597
- returnPricesInSearch: z.boolean().optional()
1598
- }).strict()]);
1599
- const ToolRouterManageConnectionsConfigSchema = z.object({
1600
- enable: z.boolean().optional().describe("Whether to use tools to manage connections in the tool router session. Defaults to true, if set to false, you need to manage connections manually").default(true),
1601
- callbackUrl: z.string().optional().describe("The callback url to use in the tool router session")
1602
- });
1603
- const ToolRouterTagsParamSchema = z.array(z.enum([
1604
- "readOnlyHint",
1605
- "createHint",
1606
- "updateHint",
1607
- "destructiveHint",
1608
- "idempotentHint",
1609
- "openWorldHint"
1610
- ])).describe("The tags to filter the tools by");
1611
- const ToolRouterTagsEnableDisableSchema = z.object({
1612
- enable: ToolRouterTagsParamSchema.optional().describe("The tags to enable in the tool router session"),
1613
- disable: ToolRouterTagsParamSchema.optional().describe("The tags to disable in the tool router session"),
1614
- /**
1615
- * Tools with any of these tags need the user's approval before they run.
1616
- * @experimental
1617
- */
1618
- requireApproval: ToolRouterTagsParamSchema.optional().describe("Experimental. Tools with any of these tags need the user approval before they run")
1619
- }).strict();
1620
- const ToolRouterConfigTagsSchema = z.union([ToolRouterTagsParamSchema, ToolRouterTagsEnableDisableSchema]).describe("The tags to use in the tool router session");
1621
- /**
1622
- * Tools config - Configure tools per toolkit using toolkit slug as key
1623
- * @example
1624
- * ```typescript
1625
- * {
1626
- * gmail: {
1627
- * enable: ['gmail_search', 'gmail_send']
1628
- * },
1629
- * slack: {
1630
- * disable: ['slack_delete_message']
1631
- * }
1632
- * }
1633
- * ```
1634
- *
1635
- * @example
1636
- * ```typescript
1637
- * {
1638
- * gmail: ['gmail_search', 'gmail_send'],
1639
- * slack: { tags: ['readOnlyHint'] }
1640
- * }
1641
- * ```
1642
- */
1643
- const ToolRouterToolsParamSchema = z.array(z.string()).describe("The tools to use in the tool router session");
1644
- /**
1645
- * Tools of the toolkit that need the user's approval before they run.
1646
- * @experimental
1647
- */
1648
- const ToolRouterToolsRequireApprovalSchema = ToolRouterToolsParamSchema.describe("Experimental. Tools of this toolkit that need the user approval before they run");
1649
- const ToolRouterConfigToolsSchema = z.union([
1650
- ToolRouterToolsParamSchema,
1651
- z.object({
1652
- enable: ToolRouterToolsParamSchema.describe("The tools to enable in the tool router session"),
1653
- requireApproval: ToolRouterToolsRequireApprovalSchema.optional()
1654
- }).strict(),
1655
- z.object({
1656
- disable: ToolRouterToolsParamSchema.describe("The tools to disable in the tool router session"),
1657
- requireApproval: ToolRouterToolsRequireApprovalSchema.optional()
1658
- }).strict(),
1659
- z.object({
1660
- tags: ToolRouterConfigTagsSchema.describe("The tags to filter the tools by, this will override the global tags"),
1661
- requireApproval: ToolRouterToolsRequireApprovalSchema.optional()
1662
- }).strict(),
1663
- z.object({ requireApproval: ToolRouterToolsRequireApprovalSchema }).strict()
1664
- ]).superRefine((val, ctx) => {
1665
- if (typeof val === "object" && !Array.isArray(val)) {
1666
- const keys = Object.keys(val).filter((key) => key !== "requireApproval");
1667
- if (keys.length > 1) ctx.addIssue({
1668
- code: z.ZodIssueCode.custom,
1669
- message: `Only one of 'enable', 'disable', or 'tags' can be specified, but found: ${keys.join(", ")}`,
1670
- path: keys
1671
- });
1672
- }
1673
- });
1674
- /**
1675
- * Proxy execute settings for a session. `enable: true` exposes the
1676
- * `COMPOSIO_PROXY_EXECUTE` meta tool and `enable: false` also turns off the
1677
- * sandbox `proxy_execute()` helper. Leaving the block out keeps the meta tool
1678
- * off while `sandbox.enableProxyExecution` controls the helper.
1679
- */
1680
- const ToolRouterProxyExecuteConfigSchema = z.object({ enable: z.boolean().describe("true exposes the COMPOSIO_PROXY_EXECUTE meta tool. false also turns off the sandbox proxy_execute() helper.") }).strict();
1681
- /**
1682
- * `proxyExecute` as accepted by `sessions.create()` and `session.update()`:
1683
- * a boolean is shorthand for `{ enable: boolean }`.
1684
- */
1685
- const ToolRouterProxyExecuteSchema = z.union([z.boolean(), ToolRouterProxyExecuteConfigSchema]);
1686
- /** Which tool calls a hook runs on: `'all'`, or only calls to the listed toolkits (including their proxy calls). */
1687
- const ToolRouterHookAppliesToSchema = z.union([z.literal("all"), z.object({ toolkits: z.array(z.string()).describe("Toolkit slugs") }).strict()]);
1688
- /** Blocks a call or result when it matches `condition`, a plain sentence describing what to block. */
1689
- const ToolRouterHookConditionCheckHandlerSchema = z.object({
1690
- type: z.literal("condition_check"),
1691
- condition: z.string().describe("What to block, written as a plain sentence. For example: \"Sending email to anyone outside example.org\"."),
1692
- action: z.literal("block")
1693
- }).strict();
1694
- /** A pre-defined check that blocks results with text that tries to give the agent instructions. */
1695
- const ToolRouterHookPromptInjectionCheckHandlerSchema = z.object({
1696
- type: z.literal("prompt_injection_check"),
1697
- action: z.literal("block")
1698
- }).strict();
1699
- const toolRouterHookIdentityFields = {
1700
- id: z.string().describe("Unique within the session. Shows up in results and logs."),
1701
- name: z.string().optional().describe("A readable name. The agent sees it when this hook blocks a call."),
1702
- appliesTo: ToolRouterHookAppliesToSchema
1703
- };
1704
- /**
1705
- * A hook on a session's tool calls. A `before_execute` hook can block a call
1706
- * before it runs; an `after_execute` hook can block its result before the
1707
- * agent sees it.
1708
- */
1709
- const ToolRouterHookSchema = z.discriminatedUnion("type", [z.object({
1710
- type: z.literal("before_execute"),
1711
- ...toolRouterHookIdentityFields,
1712
- handler: ToolRouterHookConditionCheckHandlerSchema
1713
- }).strict(), z.object({
1714
- type: z.literal("after_execute"),
1715
- ...toolRouterHookIdentityFields,
1716
- handler: z.discriminatedUnion("type", [ToolRouterHookConditionCheckHandlerSchema, ToolRouterHookPromptInjectionCheckHandlerSchema])
1717
- }).strict()]);
1718
- const ToolRouterCreateSessionConfigBaseSchema = z.object({
1719
- sessionPreset: z.literal(SessionPreset.DIRECT_TOOLS).optional().describe("Shortcut to expose every tool allowed by the session filters directly in session.tools() and the MCP tool list. This disables meta tools by default (search, multi-execute, manage-connections, and workbench). Use when all tools are known upfront and helper/meta tools are not needed. Without this preset, ToolRouter uses its default configuration with meta tools enabled."),
1720
- mcp: z.boolean().optional().describe("When true, the returned session surfaces its hosted MCP endpoint (`session.mcp.url` / `session.mcp.headers`) in the type, and an MCP URL that is not on the API base URL origin throws `ComposioMCPDestinationError` instead of leaving `session.mcp.headers` empty with a warning. The endpoint exists on every session at runtime regardless of this flag, but is only typed when `mcp: true` is passed. Default native tools (`session.tools()`) are unaffected. See https://docs.composio.dev/docs/sessions-via-mcp"),
1721
- tools: z.record(z.string(), z.union([ToolRouterToolsParamSchema, ToolRouterConfigToolsSchema])).optional().describe("The tools to use in the tool router session"),
1722
- tags: ToolRouterConfigTagsSchema.optional().describe("Global tags to filter the tools by"),
1723
- toolkits: ToolRouterSessionToolkitsSchema.optional().describe("The toolkits to use in the tool router session"),
1724
- instant: ToolRouterInstantSchema.optional().describe("Experimental Instant usage policy. Omission permits eligible tools when the project allows Instant usage; false disables it for this Session."),
1725
- authConfigs: z.record(z.string(), z.string()).describe("The auth configs to use in the tool router session. The key is the toolkit slug, the value is the auth config id.").default({}),
1726
- connectedAccounts: z.record(z.string(), z.union([z.string(), z.array(z.string())])).describe("The connected accounts to use in the tool router session. The key is the toolkit slug, the value is a connected account id or an array of ids. Only one account per toolkit is allowed when multi-account mode is disabled.").default({}),
1727
- manageConnections: z.union([z.boolean(), ToolRouterConfigManageConnectionsSchema]).optional().default(true).describe("The config for the manage connections in the tool router session. Defaults to true, if set to false, you need to manage connections manually. If set to an object, you can configure the manage connections settings."),
1728
- sandbox: ToolRouterSandboxConfigSchema.optional().describe("The sandbox config for this session. Prefer this over workbench."),
1729
- workbench: ToolRouterSandboxConfigSchema.optional().describe("Deprecated alias for sandbox. Accepted for backwards compatibility."),
1730
- multiAccount: z.object({
1731
- enable: z.boolean().default(false).describe("When true, enables multi-account mode for this session. Defaults to false."),
1732
- maxAccountsPerToolkit: z.number().int().min(2).max(10).optional().describe("Maximum number of connected accounts allowed per toolkit. Defaults to 5 when multi-account is enabled."),
1733
- requireExplicitSelection: z.boolean().optional().describe("When true, require explicit account selection when multiple accounts are connected. When false (default), use the first/default account.")
1734
- }).optional().describe("Multi-account configuration for this session"),
1735
- proxyExecute: ToolRouterProxyExecuteSchema.optional().describe("Proxy execute configuration for this session; a boolean is shorthand for `{ enable }`. Rejected by the API when enable is false and sandbox.enableProxyExecution is true."),
1736
- hooks: z.array(ToolRouterHookSchema).optional().describe("Hooks that run on this session's tool calls. A hook can block a call before it runs, or block its result before the agent sees it."),
1737
- preload: z.object({ tools: z.union([z.array(z.string()), z.literal("all")]).optional().describe("Tool slugs to preload into session.tools() and the MCP tool list, or \"all\" to preload every app tool allowed by the session filters. \"all\" requires a positive filter such as toolkits, tools, or tags; the backend validates and caps the final tool set.") }).strict().optional().describe("Preload configuration for tools that should be exposed without search."),
1738
- experimental: z.object({
1739
- assistivePrompt: z.object({ userTimezone: z.string().optional().describe("IANA timezone identifier (e.g., \"America/New_York\", \"Europe/London\") for timezone-aware assistive prompts") }).optional().describe("Configuration for assistive prompt generation"),
1740
- customTools: z.array(z.custom()).optional().describe("Custom tools to include in this session. Created via createCustomTool() from @composio/core/experimental."),
1741
- customToolkits: z.array(z.custom()).optional().describe("Custom toolkits to include in this session. Created via createCustomToolkit() from @composio/core/experimental."),
1742
- sessionConfigId: z.string().min(1).optional().describe("ID of a saved Session config (`sc_…`) to apply when the session is created. Cannot be combined with toolkits, tools, tags, customTools or customToolkits."),
1743
- /**
1744
- * What happens to a call that needs the user's approval when the
1745
- * session's MCP client can't ask the user: `deny` (the default) or
1746
- * `allow`.
1747
- * @experimental
1748
- */
1749
- noElicitationSupportFallback: ToolRouterNoElicitationSupportFallbackSchema.optional()
1750
- }).optional().describe("Experimental features configuration - not stable, may be modified or removed")
1751
- }).partial().superRefine((config, ctx) => {
1752
- if (config.experimental?.sessionConfigId !== void 0) addSessionConfigConflictIssue(ctx, [
1753
- config.toolkits !== void 0 && "toolkits",
1754
- config.tools !== void 0 && "tools",
1755
- config.tags !== void 0 && "tags",
1756
- config.hooks !== void 0 && "hooks",
1757
- config.experimental.customTools !== void 0 && "experimental.customTools",
1758
- config.experimental.customToolkits !== void 0 && "experimental.customToolkits"
1759
- ].filter((field) => field !== false));
1760
- if (config.sandbox !== void 0 && config.workbench !== void 0) ctx.addIssue({
1761
- code: z.ZodIssueCode.custom,
1762
- message: "Pass either sandbox or workbench, not both. workbench is a backwards-compatible alias for sandbox.",
1763
- path: ["sandbox"]
1764
- });
1765
- }).describe("The config for the tool router session");
1766
- const applyDirectToolsPresetDefaults = (value) => {
1767
- if (!value || typeof value !== "object" || Array.isArray(value)) return value;
1768
- const config = value;
1769
- if (config.sessionPreset !== SessionPreset.DIRECT_TOOLS) return value;
1770
- const hasSandboxConfig = config.sandbox !== void 0 || config.workbench !== void 0;
1771
- return {
1772
- ...config,
1773
- manageConnections: config.manageConnections === void 0 ? false : config.manageConnections,
1774
- ...hasSandboxConfig ? {} : { sandbox: { enable: false } },
1775
- preload: config.preload === void 0 ? { tools: "all" } : config.preload
1776
- };
1777
- };
1778
- const ToolRouterCreateSessionConfigSchema = z.preprocess(applyDirectToolsPresetDefaults, ToolRouterCreateSessionConfigBaseSchema).describe("The config for the tool router session");
1779
- const ToolkitConnectionStateSchema = z.object({
1780
- slug: z.string().describe("The slug of a toolkit"),
1781
- name: z.string().describe("The name of a toolkit"),
1782
- logo: z.string().optional().describe("The logo of a toolkit"),
1783
- isNoAuth: z.boolean().default(false).describe("Whether the toolkit is no auth or not"),
1784
- connection: z.object({
1785
- isActive: z.boolean().describe("Whether the connection is active or not"),
1786
- authConfig: z.object({
1787
- id: z.string().describe("The id of the auth config"),
1788
- mode: z.string().describe("The auth scheme used by the auth config"),
1789
- isComposioManaged: z.boolean().describe("Whether the auth config is managed by Composio")
1790
- }).nullish().describe("The auth config of a toolkit"),
1791
- connectedAccount: z.object({
1792
- id: z.string().describe("The id of the connected account"),
1793
- status: z.string().describe("The status of the connected account")
1794
- }).optional().describe("The connected account of a toolkit")
1795
- }).optional().describe("The connection of a toolkit")
1796
- }).describe("The connection state of a toolkit");
1797
- const ToolkitConnectionsDetailsSchema = z.object({
1798
- items: z.array(ToolkitConnectionStateSchema),
1799
- cursor: z.string().optional(),
1800
- totalPages: z.number()
1801
- });
1802
- const ToolRouterMCPServerConfigSchema = z.object({
1803
- type: MCPServerTypeSchema,
1804
- url: z.string(),
1805
- headers: z.record(z.string(), z.string()).optional()
1806
- });
1807
- const ToolRouterToolkitsOptionsSchema = z.object({
1808
- toolkits: z.array(z.string()).optional(),
1809
- cursor: z.string().optional(),
1810
- limit: z.number().optional(),
1811
- isConnected: z.boolean().optional(),
1812
- search: z.string().optional()
1813
- });
1814
- const ToolRouterSessionSearchResultReferenceWorkbenchSnippetSchema = z.object({
1815
- code: z.string(),
1816
- description: z.string()
1817
- });
1818
- const ToolRouterSessionSearchResultSchema = z.object({
1819
- index: z.number(),
1820
- useCase: z.string(),
1821
- primaryToolSlugs: z.array(z.string()),
1822
- relatedToolSlugs: z.array(z.string()),
1823
- toolkits: z.array(z.string()),
1824
- difficulty: z.string().optional(),
1825
- error: z.string().nullable().optional(),
1826
- executionGuidance: z.string().optional(),
1827
- knownPitfalls: z.array(z.string()).optional(),
1828
- memory: z.record(z.string(), z.array(z.string())).optional(),
1829
- planId: z.string().optional(),
1830
- recommendedPlanSteps: z.array(z.string()).optional(),
1831
- referenceWorkbenchSnippets: z.array(ToolRouterSessionSearchResultReferenceWorkbenchSnippetSchema).optional()
1832
- });
1833
- const ToolRouterSessionSearchSessionSchema = z.object({
1834
- id: z.string(),
1835
- generateId: z.boolean(),
1836
- instructions: z.string()
1837
- });
1838
- const ToolRouterSessionSearchTimeInfoSchema = z.object({
1839
- currentTimeUtc: z.string(),
1840
- currentTimeUtcEpochSeconds: z.number(),
1841
- message: z.string()
1842
- });
1843
- const ToolRouterSessionSearchToolSchemasSchemaRefSchema = z.object({
1844
- args: z.object({ toolSlugs: z.array(z.string()) }),
1845
- message: z.string().optional(),
1846
- tool: z.literal("COMPOSIO_GET_TOOL_SCHEMAS")
1847
- });
1848
- const ToolRouterSessionSearchToolSchemaSchema = z.object({
1849
- toolSlug: z.string(),
1850
- toolkit: z.string(),
1851
- description: z.string().optional(),
1852
- hasFullSchema: z.boolean().optional(),
1853
- inputSchema: z.record(z.string(), z.unknown()).optional(),
1854
- outputSchema: z.record(z.string(), z.unknown()).optional(),
1855
- schemaRef: ToolRouterSessionSearchToolSchemasSchemaRefSchema.optional()
1856
- });
1857
- const ToolRouterSessionSearchToolkitConnectionStatusSchema = z.object({
1858
- toolkit: z.string(),
1859
- description: z.string(),
1860
- hasActiveConnection: z.boolean(),
1861
- statusMessage: z.string(),
1862
- connectionDetails: z.record(z.string(), z.unknown()).optional(),
1863
- currentUserInfo: z.record(z.string(), z.unknown()).optional(),
1864
- /** Present when the toolkit runs on a Composio Instant account; only these tools run on it. */
1865
- instantAccount: z.object({
1866
- allowedToolSlugs: z.array(z.string()),
1867
- /**
1868
- * Price of each tool, keyed by tool slug. Present only when the Session
1869
- * sets `instant.returnPricesInSearch`.
1870
- */
1871
- prices: z.record(z.string(), z.object({
1872
- description: z.string().optional(),
1873
- discount: z.string().nullable().optional()
1874
- })).optional()
1875
- }).optional()
1876
- });
1877
- const ToolRouterSessionSearchResponseSchema = z.object({
1878
- success: z.boolean(),
1879
- error: z.string().nullable(),
1880
- results: z.array(ToolRouterSessionSearchResultSchema),
1881
- toolSchemas: z.record(z.string(), ToolRouterSessionSearchToolSchemaSchema),
1882
- toolkitConnectionStatuses: z.array(ToolRouterSessionSearchToolkitConnectionStatusSchema),
1883
- nextStepsGuidance: z.array(z.string()),
1884
- session: ToolRouterSessionSearchSessionSchema,
1885
- timeInfo: ToolRouterSessionSearchTimeInfoSchema
1886
- });
1887
- /**
1888
- * What one session hook decided about a call. `unavailable` means the hook
1889
- * could not be evaluated (for example it timed out); it does not block the
1890
- * call.
1891
- */
1892
- const ToolRouterHookResultSchema = z.discriminatedUnion("status", [z.object({
1893
- id: z.string().describe("The hook id"),
1894
- status: z.literal("evaluated"),
1895
- outcome: z.enum(["continue", "block"]).describe("What the hook decided")
1896
- }), z.object({
1897
- id: z.string().describe("The hook id"),
1898
- status: z.literal("unavailable")
1899
- })]);
1900
- /**
1901
- * Why a session hook blocked a call. `request_blocked`: a `before_execute` hook
1902
- * blocked it and the tool did not run. `response_blocked`: the tool ran and an
1903
- * `after_execute` hook blocked its result.
1904
- */
1905
- const ToolRouterBlockReasonSchema = z.object({
1906
- type: z.enum(["request_blocked", "response_blocked"]),
1907
- hookId: z.string()
1908
- });
1909
- const ToolRouterSessionExecuteResponseSchema = z.object({
1910
- data: z.record(z.string(), z.unknown()),
1911
- error: z.string().nullable(),
1912
- logId: z.string(),
1913
- /**
1914
- * Whether the tool ran and succeeded (`completed`), ran and failed
1915
- * (`failed`), or was blocked by a session hook (`blocked`). A failed
1916
- * execution can carry a `null` or empty `error`, so read this rather than
1917
- * `error` to tell them apart. A blocked call has empty `data` and the
1918
- * agent-facing message in `error`.
1919
- */
1920
- resultType: z.enum([
1921
- "completed",
1922
- "failed",
1923
- "blocked"
1924
- ]),
1925
- /** Actual Instant usage charge when the Session opts into returning it. */
1926
- instantCharge: z.unknown().optional(),
1927
- /** Set when `resultType` is `blocked`: which hook blocked the call, and at which stage. */
1928
- blockReason: ToolRouterBlockReasonSchema.optional(),
1929
- /** Every session hook that applied to this call. Absent when none applied. */
1930
- hookResults: z.array(ToolRouterHookResultSchema).optional()
1931
- });
1932
- const SessionProxyExecuteParamsSchema = z.object({
1933
- /** The toolkit whose connected account to use for auth (e.g. 'gmail', 'github') */
1934
- toolkit: z.string(),
1935
- /** The API endpoint URL to call */
1936
- endpoint: z.string(),
1937
- /** HTTP method */
1938
- method: z.enum([
1939
- "GET",
1940
- "POST",
1941
- "PUT",
1942
- "DELETE",
1943
- "PATCH"
1944
- ]),
1945
- /** Request body (for POST/PUT/PATCH) */
1946
- body: z.unknown().optional(),
1947
- /** Query params or headers to include */
1948
- parameters: z.array(z.object({
1949
- in: z.enum(["query", "header"]),
1950
- name: z.string(),
1951
- value: z.union([z.string(), z.number()])
1952
- })).optional()
1953
- });
1954
- /**
1955
- * `manageConnections` shape accepted by `session.update()`. Unlike the create
1956
- * schema, `callbackUrl: null` removes the stored callback URL while leaving
1957
- * the sibling connection settings untouched.
1958
- */
1959
- const ToolRouterUpdateManageConnectionsSchema = z.object({
1960
- enable: z.boolean().optional().describe("Whether to use tools to manage connections in the tool router session. Defaults to true, if set to false, you need to manage connections manually"),
1961
- callbackUrl: z.string().nullable().optional().describe("The callback url to use in the tool router session. `null` removes the stored callback url; sibling settings are untouched"),
1962
- waitForConnections: z.boolean().optional().describe("Whether to wait for users to finish authenticating connections before proceeding to the next step. Defaults to false, if set to true, a wait for connections tool call will happen and finish when the connections are ready"),
1963
- enableConnectionRemoval: z.boolean().nullable().optional().describe("Whether the session exposes the connection removal tool. `null` removes the stored override")
1964
- }).strict();
1965
- const ToolRouterElicitationDefaultSchema = z.enum([
1966
- "allow_all",
1967
- "ask_every_call",
1968
- "ask_once_per_session"
1969
- ]);
1970
- const ToolRouterElicitationOverrideSchema = z.enum([
1971
- "always_allow",
1972
- "always_deny",
1973
- "ask_once",
1974
- "ask_always"
1975
- ]);
1976
- /**
1977
- * `experimental` block accepted by `session.update()`. Each leaf follows the
1978
- * PATCH contract of the API: omit to keep the stored value, `null` to remove
1979
- * it, a value to replace it.
1980
- */
1981
- const ToolRouterUpdateExperimentalSchema = z.object({
1982
- permissions: z.object({
1983
- default: ToolRouterElicitationDefaultSchema,
1984
- overrides: z.record(z.string(), ToolRouterElicitationOverrideSchema).optional()
1985
- }).strict().nullable().optional().describe("Per-tool elicitation permission config. `null` removes the stored block"),
1986
- linkUrlOverwrite: z.string().nullable().optional().describe("Base URL override for connection link redirects. `null` removes the stored override"),
1987
- fastMode: z.boolean().nullable().optional().describe("Fast search mode. `null` removes the stored override"),
1988
- submitFeedback: z.object({ enable: z.boolean() }).strict().nullable().optional().describe("Exposes the COMPOSIO_SUBMIT_FEEDBACK helper tool. `null` removes the stored block"),
1989
- /**
1990
- * What happens to a call that needs the user's approval when the session's
1991
- * MCP client can't ask the user: `deny` or `allow`.
1992
- * @experimental
1993
- */
1994
- noElicitationSupportFallback: ToolRouterNoElicitationSupportFallbackSchema.optional(),
1995
- sessionConfigId: z.string().min(1).optional().describe("Apply the latest active saved Session config (`sc_…`) from this project to this session. Replaces the session's toolkit, tool and tag access and cannot be combined with toolkits, tools or tags")
1996
- }).strict();
1997
- /**
1998
- * Options for `session.update()`. For every policy block, omitting the key
1999
- * preserves the stored value and `null` removes the stored override (which can
2000
- * increase access: `toolkits: null` restores the unrestricted default, unlike
2001
- * `toolkits: []`, which denies every app toolkit).
2002
- */
2003
- const ToolRouterUpdateSessionConfigSchema = z.object({
2004
- instant: ToolRouterInstantSchema.optional().describe("Experimental Instant usage policy. False disables it. Any supplied object, even one that only sets returnInstantCharge, re-enables it. Omitted subfields keep their stored values."),
2005
- toolkits: ToolRouterSessionToolkitsSchema.nullable().optional().describe("Toolkit policy. An empty allowlist (`[]` or `{ enable: [] }`) is sent as-is and denies every app toolkit; `null` removes the stored policy and restores the unrestricted default"),
2006
- tools: z.record(z.string(), z.union([ToolRouterToolsParamSchema, ToolRouterConfigToolsSchema])).nullable().optional().describe("Replaces the entire stored tools map; `null` removes the override"),
2007
- tags: ToolRouterConfigTagsSchema.nullable().optional().describe("Replaces the global tag policy; `null` removes the override"),
2008
- authConfigs: z.record(z.string(), z.string()).nullable().optional().describe("Replaces the entire stored auth config map; `null` removes the override"),
2009
- connectedAccounts: z.record(z.string(), z.union([z.string(), z.array(z.string())])).transform((rec) => {
2010
- const out = {};
2011
- for (const [k, v] of Object.entries(rec)) out[k] = typeof v === "string" ? [v] : v;
2012
- return out;
2013
- }).nullable().optional().describe("Replaces the entire stored connected accounts map; `null` removes the override"),
2014
- manageConnections: z.union([z.boolean(), ToolRouterUpdateManageConnectionsSchema]).nullable().optional(),
2015
- sandbox: ToolRouterSandboxConfigSchema.partial().nullable().optional(),
2016
- workbench: ToolRouterSandboxConfigSchema.partial().nullable().optional(),
2017
- multiAccount: z.object({
2018
- enable: z.boolean().optional(),
2019
- maxAccountsPerToolkit: z.number().int().min(2).max(10).nullable().optional().describe("`null` removes the stored maximum so the default applies again"),
2020
- requireExplicitSelection: z.boolean().optional()
2021
- }).nullable().optional().describe("`null` removes the session override; the mode then resolves to disabled"),
2022
- proxyExecute: ToolRouterProxyExecuteSchema.nullable().optional().describe("Replaces the proxy execute block; a boolean is shorthand for `{ enable }` and `null` removes it"),
2023
- hooks: z.array(ToolRouterHookSchema).nullable().optional().describe("Replaces the whole list of hooks; `null` removes every hook"),
2024
- preload: z.object({ tools: z.union([z.array(z.string()), z.literal("all")]).optional() }).strict().nullable().optional().describe("Replaces the stored preload; `null` removes it"),
2025
- search: z.object({ enable: z.boolean().optional() }).strict().nullable().optional().describe("Replaces the search block; `null` removes it and restores the defaults"),
2026
- execute: z.object({ enableMultiExecute: z.boolean().optional() }).strict().nullable().optional().describe("Replaces the execute block; `null` removes it and restores the defaults"),
2027
- experimental: ToolRouterUpdateExperimentalSchema.nullable().optional().describe("Experimental settings; `null` removes the stored block"),
2028
- expectedConfigVersion: z.union([z.number().int().positive(), z.literal(false)]).optional().describe("Precondition sent as `expected_config_version`. A positive integer (for example `session.configVersion`) makes the update conditional, so a concurrent change surfaces as ComposioSessionConfigConflictError instead of being overwritten; the API must support the field. Omitted or `false`: no precondition (last writer wins)")
2029
- }).partial().superRefine((config, ctx) => {
2030
- if (config.experimental?.sessionConfigId !== void 0) addSessionConfigConflictIssue(ctx, [
2031
- config.toolkits !== void 0 && "toolkits",
2032
- config.tools !== void 0 && "tools",
2033
- config.tags !== void 0 && "tags",
2034
- config.hooks !== void 0 && "hooks"
2035
- ].filter((field) => field !== false));
2036
- if (config.sandbox !== void 0 && config.workbench !== void 0) ctx.addIssue({
2037
- code: z.ZodIssueCode.custom,
2038
- message: "Pass either sandbox or workbench, not both. workbench is a backwards-compatible alias for sandbox.",
2039
- path: ["sandbox"]
2040
- });
2041
- });
2042
- const ToolRouterSessionDeleteResponseSchema = z.object({
2043
- sessionId: z.string(),
2044
- deleted: z.literal(true)
2045
- });
2046
- /**
2047
- * Options for `session.listConfigHistory()`.
2048
- */
2049
- const ToolRouterSessionListConfigHistoryOptionsSchema = z.object({
2050
- /** Cursor from a previous response's `nextCursor`. */
2051
- cursor: z.string().optional(),
2052
- /** Number of items per page, max allowed is 100. */
2053
- limit: z.number().optional()
2054
- });
2055
- const ToolRouterSessionEnsureConnectedOptionsSchema = z.object({
2056
- callbackUrl: z.string().optional(),
2057
- alias: z.string().optional(),
2058
- experimental: ConnectedAccountExperimentalSchema.optional(),
2059
- /** Max time to wait for a newly-initiated connection to become active, in milliseconds. Defaults to 60000. */
2060
- timeout: z.number().int().positive().optional()
2061
- });
2062
-
2063
- //#endregion
2064
- //#region src/utils/transformers/toolRouterResponseTransform.ts
2065
- /**
2066
- * The `result_type` values of a call that ran. `input_required` and `blocked`
2067
- * are handled before this is read. `hook_results` is validated in its own step
2068
- * so a shape drift there doesn't read as an unknown `result_type`.
2069
- */
2070
- const ExecutedResponseSchema = z.object({ result_type: z.enum(["completed", "failed"]) });
2071
- /** A call a session hook blocked. The generated client does not type it yet. */
2072
- const BlockedResponseSchema = z.object({
2073
- result_type: z.literal("blocked"),
2074
- reason: z.object({
2075
- type: z.enum(["request_blocked", "response_blocked"]),
2076
- hook_id: z.string()
2077
- }),
2078
- message: z.string(),
2079
- log_id: z.string().optional(),
2080
- instant_charge: z.unknown().optional(),
2081
- hook_results: z.array(ToolRouterHookResultSchema).optional()
2082
- });
2083
- const IsBlockedSchema = z.object({ result_type: z.literal("blocked") });
2084
- /**
2085
- * Reads a `blocked` response, or returns `undefined` for any other
2086
- * `result_type`. A `blocked` response that does not match its schema is
2087
- * raised rather than read as a result.
2088
- */
2089
- function parseBlockedResponse(raw, subject) {
2090
- if (!IsBlockedSchema.safeParse(raw).success) return void 0;
2091
- const blocked = BlockedResponseSchema.safeParse(raw);
2092
- if (!blocked.success) throw new ValidationError(`${subject} returned a malformed blocked response`, { cause: blocked.error });
2093
- return blocked.data;
2094
- }
2095
- /**
2096
- * Whether a session tool execution succeeded. `resultType` decides: a `failed`
2097
- * execution is not successful even when its `error` is `null` or empty.
2098
- */
2099
- function isExecutionSuccessful(result) {
2100
- return result.resultType === "completed";
2101
- }
2102
- /**
2103
- * Narrows an execute-family response to the variants that carry a result.
2104
- * `input_required` means the call did not run: it is raised as a
2105
- * {@link ComposioToolInputRequiredError} instead of being returned as a result
2106
- * it is not.
2107
- */
2108
- function assertNotInputRequired(raw, subject) {
2109
- if (raw.result_type !== "input_required") return;
2110
- throw new ComposioToolInputRequiredError(subject, {
2111
- inputRequests: Object.fromEntries(Object.entries(raw.input_requests).map(([id, request]) => [id, {
2112
- type: request.type,
2113
- mode: request.mode,
2114
- message: request.message,
2115
- requestedSchema: request.requested_schema
2116
- }])),
2117
- requestState: raw.request_state
2118
- });
2119
- }
2120
- function transformSearchResult(raw) {
2121
- return {
2122
- index: raw.index,
2123
- useCase: raw.use_case,
2124
- primaryToolSlugs: raw.primary_tool_slugs,
2125
- relatedToolSlugs: raw.related_tool_slugs,
2126
- toolkits: raw.toolkits,
2127
- difficulty: raw.difficulty,
2128
- error: raw.error,
2129
- executionGuidance: raw.execution_guidance,
2130
- knownPitfalls: raw.known_pitfalls,
2131
- memory: raw.memory,
2132
- planId: raw.plan_id,
2133
- recommendedPlanSteps: raw.recommended_plan_steps,
2134
- referenceWorkbenchSnippets: raw.reference_workbench_snippets
2135
- };
2136
- }
2137
- function transformToolSchema(raw) {
2138
- return {
2139
- toolSlug: raw.tool_slug,
2140
- toolkit: raw.toolkit,
2141
- description: raw.description,
2142
- hasFullSchema: raw.hasFullSchema,
2143
- inputSchema: raw.input_schema,
2144
- outputSchema: raw.output_schema,
2145
- schemaRef: raw.schemaRef ? {
2146
- args: { toolSlugs: raw.schemaRef.args.tool_slugs },
2147
- message: raw.schemaRef.message,
2148
- tool: raw.schemaRef.tool
2149
- } : void 0
2150
- };
2151
- }
2152
- function transformToolkitConnectionStatus(raw) {
2153
- return {
2154
- toolkit: raw.toolkit,
2155
- description: raw.description,
2156
- hasActiveConnection: raw.has_active_connection,
2157
- statusMessage: raw.status_message,
2158
- connectionDetails: raw.connection_details,
2159
- currentUserInfo: raw.current_user_info,
2160
- ...raw.instant_account !== void 0 && { instantAccount: {
2161
- allowedToolSlugs: raw.instant_account.allowed_tool_slugs,
2162
- ...raw.instant_account.prices !== void 0 && { prices: raw.instant_account.prices }
2163
- } }
2164
- };
2165
- }
2166
- /**
2167
- * Transforms a raw session search API response to camelCase.
2168
- */
2169
- function transformSearchResponse(raw) {
2170
- const toolSchemas = {};
2171
- for (const [slug, schema] of Object.entries(raw.tool_schemas)) toolSchemas[slug] = transformToolSchema(schema);
2172
- return {
2173
- success: raw.success,
2174
- error: raw.error,
2175
- results: raw.results.map(transformSearchResult),
2176
- toolSchemas,
2177
- toolkitConnectionStatuses: raw.toolkit_connection_statuses.map(transformToolkitConnectionStatus),
2178
- nextStepsGuidance: raw.next_steps_guidance,
2179
- session: {
2180
- id: raw.session.id,
2181
- generateId: raw.session.generate_id,
2182
- instructions: raw.session.instructions
2183
- },
2184
- timeInfo: {
2185
- currentTimeUtc: raw.time_info.current_time_utc,
2186
- currentTimeUtcEpochSeconds: raw.time_info.current_time_utc_epoch_seconds,
2187
- message: raw.time_info.message
2188
- }
2189
- };
2190
- }
2191
- /**
2192
- * Transforms a raw session execute API response to camelCase.
2193
- *
2194
- * @throws {ComposioToolInputRequiredError} If the tool asked for user input instead of running
2195
- * @throws {ValidationError} If the response carries no `result_type`, one this SDK does not know, or malformed `hook_results`
2196
- */
2197
- function transformExecuteResponse(raw, toolSlug) {
2198
- assertNotInputRequired(raw, `Tool ${toolSlug}`);
2199
- const blocked = parseBlockedResponse(raw, `Tool ${toolSlug}`);
2200
- if (blocked) return {
2201
- data: {},
2202
- error: blocked.message,
2203
- logId: blocked.log_id ?? "",
2204
- resultType: "blocked",
2205
- blockReason: {
2206
- type: blocked.reason.type,
2207
- hookId: blocked.reason.hook_id
2208
- },
2209
- ...blocked.hook_results !== void 0 && { hookResults: blocked.hook_results },
2210
- ...blocked.instant_charge !== void 0 && { instantCharge: blocked.instant_charge }
2211
- };
2212
- const executed = ExecutedResponseSchema.safeParse(raw);
2213
- if (!executed.success) throw new ValidationError(`Tool ${toolSlug} returned an execute response without a known result_type`, { cause: executed.error });
2214
- const hookResults = CompletedHookResultsSchema.safeParse(raw);
2215
- if (!hookResults.success) throw new ValidationError(`Tool ${toolSlug} returned malformed hook results`, { cause: hookResults.error });
2216
- return {
2217
- data: raw.data,
2218
- error: raw.error,
2219
- logId: raw.log_id,
2220
- resultType: executed.data.result_type,
2221
- ...raw.instant_charge !== void 0 && { instantCharge: raw.instant_charge },
2222
- ...hookResults.data.hook_results !== void 0 && { hookResults: hookResults.data.hook_results }
2223
- };
2224
- }
2225
- /** Hook results on a call that ran: session execute, or a proxied request that was sent. */
2226
- const CompletedHookResultsSchema = z.object({ hook_results: z.array(ToolRouterHookResultSchema).optional() });
2227
- /**
2228
- * Projects a session proxy execute response onto the SDK's shape: a request a
2229
- * session hook blocked comes back as `resultType: 'blocked'` with no HTTP
2230
- * response.
2231
- */
2232
- function transformProxyExecuteResponse(raw, subject) {
2233
- assertNotInputRequired(raw, subject);
2234
- const blocked = parseBlockedResponse(raw, subject);
2235
- if (blocked) return {
2236
- resultType: "blocked",
2237
- blockReason: {
2238
- type: blocked.reason.type,
2239
- hookId: blocked.reason.hook_id
2240
- },
2241
- message: blocked.message,
2242
- ...blocked.hook_results !== void 0 && { hookResults: blocked.hook_results }
2243
- };
2244
- const hookResults = CompletedHookResultsSchema.safeParse(raw);
2245
- if (!hookResults.success) throw new ValidationError(`${subject} returned malformed hook results`, { cause: hookResults.error });
2246
- return {
2247
- resultType: "completed",
2248
- status: raw.status,
2249
- data: raw.data,
2250
- headers: raw.headers,
2251
- ...raw.binary_data && { binaryData: {
2252
- contentType: raw.binary_data.content_type,
2253
- size: raw.binary_data.size,
2254
- url: raw.binary_data.url,
2255
- expiresAt: raw.binary_data.expires_at
2256
- } },
2257
- ...hookResults.data.hook_results !== void 0 && { hookResults: hookResults.data.hook_results }
2258
- };
2259
- }
2260
-
2261
- //#endregion
2262
- //#region src/models/Tools.ts
2263
- const TOOL_ROUTER_SESSION_TOOLS_PAGE_LIMIT = 500;
2264
- /**
2265
- * Normalize a raw `input_parameters` / `output_parameters` payload returned by
2266
- * the Composio API. Maps `null`, `undefined`, and empty `{}` — all of which
2267
- * mean "no declared schema" — to `undefined` so the strict `ParametersSchema`
2268
- * validator never sees them. Non-empty objects pass through unchanged and
2269
- * remain subject to strict Zod validation.
2270
- *
2271
- * MCP-backed toolkits (granola_mcp, apify_mcp, tavily_mcp, …) have no
2272
- * declared output schema and the API serializes that as `{}`, which would
2273
- * otherwise trip `ParametersSchema`. See
2274
- * https://github.com/ComposioHQ/composio/issues/3354.
2275
- */
2276
- function normalizeRawToolParameters(params) {
2277
- if (params == null || Object.keys(params).length === 0) return void 0;
2278
- return params;
2279
- }
2280
- /**
2281
- * This class is used to manage tools in the Composio SDK.
2282
- * It provides methods to list, get, and execute tools.
2283
- */
2284
- var Tools = class {
2285
- client;
2286
- provider;
2287
- autoUploadDownloadFiles;
2288
- toolkitVersions;
2289
- fileUploadPathOptions;
2290
- /**
2291
- * Tracks tool slugs we've already warned about to avoid spamming the log when
2292
- * the same file-input tool is executed repeatedly while auto-upload is off.
2293
- * Scoped per-instance so a fresh `Composio` starts with a clean slate.
2294
- */
2295
- warnedAutoUploadDisabledForTool = /* @__PURE__ */ new Set();
2296
- constructor(client, config) {
2297
- if (!client) throw new Error("ComposioClient is required");
2298
- if (!config?.provider) throw new ComposioProviderNotDefinedError("Provider not passed into Tools instance");
2299
- this.client = client;
2300
- this.provider = config.provider;
2301
- this.autoUploadDownloadFiles = config?.dangerouslyAllowAutoUploadDownloadFiles === true;
2302
- this.toolkitVersions = config?.toolkitVersions ?? CONFIG_DEFAULTS.toolkitVersions;
2303
- this.fileUploadPathOptions = {
2304
- sensitiveFileUploadProtection: config?.sensitiveFileUploadProtection,
2305
- fileUploadPathDenySegments: config?.fileUploadPathDenySegments,
2306
- fileUploadAllowlist: this.autoUploadDownloadFiles ? resolveEffectiveUploadAllowlist(config?.fileUploadDirs) : void 0,
2307
- fileDownloadDir: config?.fileDownloadDir
2308
- };
2309
- this.execute = this.execute.bind(this);
2310
- this.provider._setExecuteToolFn(this.createExecuteFnForProviders());
2311
- this.getRawComposioToolBySlug = this.getRawComposioToolBySlug.bind(this);
2312
- this.getRawComposioTools = this.getRawComposioTools.bind(this);
2313
- telemetry.instrument(this, "Tools");
2314
- }
2315
- /**
2316
- * Transforms tool data from snake_case API format to camelCase for internal SDK use.
2317
- *
2318
- * This method standardizes the property naming convention for tools retrieved from the Composio API,
2319
- * making them more consistent with JavaScript/TypeScript conventions.
2320
- *
2321
- * @param {ToolRetrieveResponse | ComposioToolListResponse['items'][0]} tool - The tool object to transform
2322
- * @returns {Tool} The transformed tool with camelCase properties
2323
- *
2324
- * @private
2325
- */
2326
- transformToolCases(tool) {
2327
- return ToolSchema.parse({
2328
- ...tool,
2329
- inputParameters: normalizeRawToolParameters(tool.input_parameters),
2330
- outputParameters: normalizeRawToolParameters(tool.output_parameters),
2331
- availableVersions: tool.available_versions,
2332
- isDeprecated: tool.deprecated?.is_deprecated ?? false,
2333
- isNoAuth: tool.no_auth
2334
- });
2335
- }
2336
- /**
2337
- * Transforms tool execution response from snake_case API format to camelCase.
2338
- *
2339
- * This method converts the response received from the Composio API to a standardized format
2340
- * with consistent property naming that follows JavaScript/TypeScript conventions.
2341
- *
2342
- * @param {ComposioToolExecuteResponse} response - The raw API response to transform
2343
- * @returns {ToolExecuteResponse} The transformed response with camelCase properties
2344
- *
2345
- * @private
2346
- */
2347
- transformToolExecuteResponse(response) {
2348
- return ToolExecuteResponseSchema.parse({
2349
- data: response.data,
2350
- error: response.error,
2351
- successful: response.successful,
2352
- logId: response.log_id,
2353
- sessionInfo: response.session_info
2354
- });
2355
- }
2356
- /**
2357
- * Applies the default schema modifiers to the tools.
2358
- *
2359
- * The `file_uploadable` transform (collapsing the backend's internal
2360
- * `{ name, mimetype, s3key }` staging shape to `{ type: 'string',
2361
- * format: 'path' }`) is **gated on `dangerouslyAllowAutoUploadDownloadFiles`**
2362
- * — the collapsed shape is a promise that the SDK will stage local paths
2363
- * on your behalf at execute time, and that's only true when the flag is on.
2364
- *
2365
- * When the flag is off, the raw schema is returned unchanged; callers are
2366
- * expected to stage files themselves via `composio.files.upload()` and pass
2367
- * the resulting descriptor into `tools.execute`. If an LLM ends up calling
2368
- * a file-uploadable tool in this mode, the execute path emits a one-shot
2369
- * warning per tool slug (see `applyBeforeExecuteModifiers`).
2370
- *
2371
- * @param tools - The tools to apply the default schema modifiers to
2372
- * @returns The tools with the default schema modifiers applied
2373
- */
2374
- async applyDefaultSchemaModifiers(tools) {
2375
- if (!this.autoUploadDownloadFiles) return tools;
2376
- const fileToolModifier = new FileToolModifier(this.client, this.fileUploadPathOptions);
2377
- return await Promise.all(tools.map((tool) => fileToolModifier.modifyToolSchema(tool)));
2378
- }
2379
- /**
2380
- * Applies the before execute modifiers to the tool execution params
2381
- * @param options.toolSlug - The slug of the tool
2382
- * @param options.toolkitSlug - The slug of the toolkit
2383
- * @param options.params - The params of the tool execution
2384
- * @param modifier - The modifier to apply
2385
- * @returns The modified params
2386
- */
2387
- async applyBeforeExecuteModifiers(tool, { toolSlug, toolkitSlug, params }, modifiers, requestOptions) {
2388
- if (requestOptions?.signal?.aborted) throw new ComposioRequestCancelledError();
2389
- let modifiedParams = await this.applyFileUploadModifiers(tool, {
2390
- toolSlug,
2391
- toolkitSlug,
2392
- params
2393
- }, modifiers?.beforeFileUpload, requestOptions);
2394
- if (modifiers?.beforeExecute) {
2395
- if (typeof modifiers.beforeExecute === "function") {
2396
- modifiedParams = await modifiers.beforeExecute({
2397
- toolSlug,
2398
- toolkitSlug,
2399
- params: modifiedParams
2400
- });
2401
- if (requestOptions?.signal?.aborted) throw new ComposioRequestCancelledError();
2402
- } else throw new ComposioInvalidModifierError("Invalid beforeExecute modifier. Not a function.");
2403
- }
2404
- return modifiedParams;
2405
- }
2406
- /**
2407
- * Applies schema-aware file preprocessing shared by direct and Tool Router
2408
- * session execution. This always runs before the caller's `beforeExecute`
2409
- * hook so the hook observes the exact arguments sent to the backend.
2410
- */
2411
- async applyFileUploadModifiers(tool, { toolSlug, toolkitSlug, params }, beforeFileUpload, requestOptions) {
2412
- let modifiedParams = params;
2413
- if (this.autoUploadDownloadFiles) {
2414
- modifiedParams = await new FileToolModifier(this.client, {
2415
- ...this.fileUploadPathOptions,
2416
- beforeFileUpload
2417
- }).fileUploadModifier(tool, {
2418
- toolSlug,
2419
- toolkitSlug,
2420
- params: modifiedParams,
2421
- signal: requestOptions?.signal
2422
- });
2423
- if (requestOptions?.signal?.aborted) throw new ComposioRequestCancelledError();
2424
- } else if (tool.inputParameters && schemaHasFileUploadable(tool.inputParameters)) {
2425
- if (modifiedParams.arguments) modifiedParams = {
2426
- ...modifiedParams,
2427
- arguments: await dropEmptyFileUploads(modifiedParams.arguments, dereferenceJsonSchema(tool.inputParameters, { onUnresolved: "sentinel" }))
2428
- };
2429
- if (!this.warnedAutoUploadDisabledForTool.has(toolSlug)) {
2430
- this.warnedAutoUploadDisabledForTool.add(toolSlug);
2431
- logger.warn(`Tool "${toolSlug}" (toolkit "${toolkitSlug}") has a file-uploadable input, but \`dangerouslyAllowAutoUploadDownloadFiles\` is disabled. The SDK will forward the file argument as-is; if it isn't already a staged { name, mimetype, s3key } descriptor, the backend will reject the call. Either:\n 1) Stage the file yourself: \`const f = await composio.files.upload({ file, toolSlug, toolkitSlug }); await composio.tools.execute('${toolSlug}', { userId, arguments: { <fileField>: f } })\`, or\n 2) Enable auto-upload with a scoped allowlist: \`new Composio({ dangerouslyAllowAutoUploadDownloadFiles: true, fileUploadDirs: ['/safe/dir'] })\`.`);
2432
- }
2433
- }
2434
- return modifiedParams;
2435
- }
2436
- /**
2437
- * Applies the after execute modifiers to the tool execution result
2438
- * @param options.toolSlug - The slug of the tool
2439
- * @param options.toolkitSlug - The slug of the toolkit
2440
- * @param options.result - The result of the tool execution
2441
- * @param modifier - The modifier to apply
2442
- * @returns The modified result
2443
- */
2444
- async applyAfterExecuteModifiers(tool, { toolSlug, toolkitSlug, result }, modifier, requestOptions) {
2445
- let modifiedResult = result;
2446
- if (this.autoUploadDownloadFiles) modifiedResult = await new FileToolModifier(this.client, this.fileUploadPathOptions).fileDownloadModifier(tool, {
2447
- toolSlug,
2448
- toolkitSlug,
2449
- result: modifiedResult,
2450
- signal: requestOptions?.signal
2451
- });
2452
- if (modifier) {
2453
- if (typeof modifier === "function") modifiedResult = await modifier({
2454
- toolSlug,
2455
- toolkitSlug,
2456
- result: modifiedResult
2457
- });
2458
- else throw new ComposioInvalidModifierError("Invalid afterExecute modifier. Not a function.");
2459
- }
2460
- return modifiedResult;
2461
- }
1560
+ async applyAfterExecuteModifiers(tool, { toolSlug, toolkitSlug, result }, modifier, requestOptions) {
1561
+ let modifiedResult = result;
1562
+ if (this.autoUploadDownloadFiles) modifiedResult = await new FileToolModifier(this.client, this.fileUploadPathOptions).fileDownloadModifier(tool, {
1563
+ toolSlug,
1564
+ toolkitSlug,
1565
+ result: modifiedResult,
1566
+ signal: requestOptions?.signal
1567
+ });
1568
+ if (modifier) {
1569
+ if (typeof modifier === "function") modifiedResult = await modifier({
1570
+ toolSlug,
1571
+ toolkitSlug,
1572
+ result: modifiedResult
1573
+ });
1574
+ else throw new ComposioInvalidModifierError("Invalid afterExecute modifier. Not a function.");
1575
+ }
1576
+ return modifiedResult;
1577
+ }
2462
1578
  /**
2463
1579
  * Lists Composio API tools available to the SDK.
2464
1580
  *
@@ -3478,210 +2594,494 @@ var AuthConfigs = class {
3478
2594
  return transformAuthConfigListResponse(result);
3479
2595
  }
3480
2596
  /**
3481
- * Create a new auth config
3482
- * @param {string} toolkit - Unique identifier of the toolkit
3483
- * @param {CreateAuthConfigParams} options - Options for creating a new auth config
3484
- * @returns {Promise<CreateAuthConfigResponse>} Created auth config
2597
+ * Create a new auth config
2598
+ * @param {string} toolkit - Unique identifier of the toolkit
2599
+ * @param {CreateAuthConfigParams} options - Options for creating a new auth config
2600
+ * @returns {Promise<CreateAuthConfigResponse>} Created auth config
2601
+ *
2602
+ * @example
2603
+ * const authConfig = await authConfigs.create('my-toolkit', {
2604
+ * type: AuthConfigTypes.CUSTOM,
2605
+ * name: 'My Custom Auth Config',
2606
+ * authScheme: AuthSchemeTypes.API_KEY,
2607
+ * credentials: {
2608
+ * apiKey: '1234567890',
2609
+ * },
2610
+ * });
2611
+ *
2612
+ * @link https://docs.composio.dev/reference/auth-configs/create-auth-config
2613
+ */
2614
+ async create(toolkit, options = { type: "use_composio_managed_auth" }, requestOptions) {
2615
+ const parsedOptions = CreateAuthConfigParamsSchema.safeParse(options);
2616
+ if (parsedOptions.error) throw new ValidationError("Failed to parse auth config create options", { cause: parsedOptions.error });
2617
+ const createBody = {
2618
+ toolkit: { slug: toolkit },
2619
+ auth_config: parsedOptions.data.type === "use_custom_auth" ? {
2620
+ type: parsedOptions.data.type,
2621
+ name: parsedOptions.data.name,
2622
+ authScheme: parsedOptions.data.authScheme,
2623
+ credentials: parsedOptions.data.credentials,
2624
+ is_enabled_for_tool_router: parsedOptions.data.isEnabledForToolRouter,
2625
+ proxy_config: parsedOptions.data.proxyConfig ? {
2626
+ proxy_url: parsedOptions.data.proxyConfig.proxyUrl,
2627
+ proxy_auth_key: parsedOptions.data.proxyConfig.proxyAuthKey
2628
+ } : void 0,
2629
+ tool_access_config: parsedOptions.data.toolAccessConfig ? { tools_for_connected_account_creation: parsedOptions.data.toolAccessConfig.toolsForConnectedAccountCreation } : void 0
2630
+ } : {
2631
+ type: parsedOptions.data.type,
2632
+ credentials: parsedOptions.data.credentials,
2633
+ name: parsedOptions.data.name,
2634
+ is_enabled_for_tool_router: parsedOptions.data.isEnabledForToolRouter,
2635
+ tool_access_config: parsedOptions.data.toolAccessConfig ? { tools_for_connected_account_creation: parsedOptions.data.toolAccessConfig.toolsForConnectedAccountCreation } : void 0
2636
+ }
2637
+ };
2638
+ const result = await withCancellation(() => this.client.authConfigs.create(createBody, requestOptions), requestOptions?.signal);
2639
+ return transformCreateAuthConfigResponse(result);
2640
+ }
2641
+ /**
2642
+ * Retrieves a specific authentication configuration by its ID.
2643
+ *
2644
+ * This method fetches detailed information about a single auth config
2645
+ * and transforms the response to the SDK's standardized format.
2646
+ *
2647
+ * @param {string} nanoid - The unique identifier of the auth config to retrieve
2648
+ * @returns {Promise<AuthConfigRetrieveResponse>} The auth config details
2649
+ * @throws {Error} If the auth config cannot be found or an API error occurs
2650
+ * @throws {ValidationError} If the response fails validation
2651
+ *
2652
+ * @example
2653
+ * ```typescript
2654
+ * // Get an auth config by ID
2655
+ * const authConfig = await composio.authConfigs.get('auth_abc123');
2656
+ * console.log(authConfig.name); // e.g., 'GitHub Auth'
2657
+ * console.log(authConfig.toolkit.slug); // e.g., 'github'
2658
+ * ```
2659
+ */
2660
+ async get(nanoid, requestOptions) {
2661
+ const result = await withCancellation(() => this.client.authConfigs.retrieve(nanoid, requestOptions), requestOptions?.signal);
2662
+ return transformAuthConfigRetrieveResponse(result);
2663
+ }
2664
+ /**
2665
+ * Updates an existing authentication configuration.
2666
+ *
2667
+ * This method allows you to modify properties of an auth config such as credentials,
2668
+ * scopes, or tool restrictions. The update type (custom or default) determines which
2669
+ * fields can be updated.
2670
+ *
2671
+ * @param {string} nanoid - The unique identifier of the auth config to update
2672
+ * @param {AuthConfigUpdateParams} data - The data to update, which can be either custom or default type
2673
+ * @returns {Promise<AuthConfigUpdateResponse>} The updated auth config
2674
+ * @throws {ValidationError} If the update parameters are invalid
2675
+ * @throws {Error} If the auth config cannot be found or updated
2676
+ *
2677
+ * @example
2678
+ * ```typescript
2679
+ * // Update a custom auth config with new credentials
2680
+ * const updatedConfig = await composio.authConfigs.update('auth_abc123', {
2681
+ * type: 'custom',
2682
+ * credentials: {
2683
+ * apiKey: 'new-api-key-value'
2684
+ * }
2685
+ * });
2686
+ *
2687
+ * // Update a default auth config with new scopes
2688
+ * const updatedConfig = await composio.authConfigs.update('auth_abc123', {
2689
+ * type: 'default',
2690
+ * scopes: ['read:user', 'repo']
2691
+ * });
2692
+ * ```
2693
+ */
2694
+ async update(nanoid, data, requestOptions) {
2695
+ const parsedData = AuthConfigUpdateParamsSchema.safeParse(data);
2696
+ if (parsedData.error) throw new ValidationError("Failed to parse auth config update data", { cause: parsedData.error });
2697
+ const updateBody = parsedData.data.type === "custom" ? {
2698
+ type: "custom",
2699
+ credentials: parsedData.data.credentials,
2700
+ is_enabled_for_tool_router: parsedData.data.isEnabledForToolRouter,
2701
+ tool_access_config: {
2702
+ tools_for_connected_account_creation: parsedData.data.toolAccessConfig?.toolsForConnectedAccountCreation,
2703
+ tools_available_for_execution: parsedData.data.toolAccessConfig?.toolsAvailableForExecution ?? parsedData.data.restrictToFollowingTools
2704
+ }
2705
+ } : {
2706
+ type: "default",
2707
+ scopes: parsedData.data.scopes,
2708
+ is_enabled_for_tool_router: parsedData.data.isEnabledForToolRouter,
2709
+ tool_access_config: {
2710
+ tools_for_connected_account_creation: parsedData.data.toolAccessConfig?.toolsForConnectedAccountCreation,
2711
+ tools_available_for_execution: parsedData.data.toolAccessConfig?.toolsAvailableForExecution ?? parsedData.data.restrictToFollowingTools
2712
+ }
2713
+ };
2714
+ return withCancellation(() => this.client.authConfigs.update(nanoid, updateBody, requestOptions), requestOptions?.signal);
2715
+ }
2716
+ /**
2717
+ * Deletes an authentication configuration.
2718
+ *
2719
+ * This method permanently removes an auth config from the Composio platform.
2720
+ * This action cannot be undone and will prevent any connected accounts that use
2721
+ * this auth config from functioning.
2722
+ *
2723
+ * @param {string} nanoid - The unique identifier of the auth config to delete
2724
+ * @returns {Promise<AuthConfigDeleteResponse>} The deletion response
2725
+ * @throws {Error} If the auth config doesn't exist or cannot be deleted
2726
+ *
2727
+ * @example
2728
+ * ```typescript
2729
+ * // Delete an auth config
2730
+ * await composio.authConfigs.delete('auth_abc123');
2731
+ * ```
2732
+ */
2733
+ async delete(nanoid, requestOptions) {
2734
+ return withCancellation(() => this.client.authConfigs.delete(nanoid, void 0, requestOptions), requestOptions?.signal);
2735
+ }
2736
+ /**
2737
+ * Updates the status of an authentication configuration.
2738
+ *
2739
+ * This method allows you to enable or disable an auth config. When disabled,
2740
+ * the auth config cannot be used to create new connected accounts or authenticate
2741
+ * with third-party services.
2742
+ *
2743
+ * @param {string} status - The status to set ('ENABLED' or 'DISABLED')
2744
+ * @param {string} nanoid - The unique identifier of the auth config
2745
+ * @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
2746
+ * @throws {Error} If the auth config cannot be found or the status cannot be updated
2747
+ *
2748
+ * @example
2749
+ * ```typescript
2750
+ * // Disable an auth config
2751
+ * await composio.authConfigs.updateStatus('DISABLED', 'auth_abc123');
2752
+ *
2753
+ * // Enable an auth config
2754
+ * await composio.authConfigs.updateStatus('ENABLED', 'auth_abc123');
2755
+ * ```
2756
+ */
2757
+ async updateStatus(status, nanoid, requestOptions) {
2758
+ return withCancellation(() => this.client.authConfigs.updateStatus(status, { nanoid }, requestOptions), requestOptions?.signal);
2759
+ }
2760
+ /**
2761
+ * Enables an authentication configuration.
3485
2762
  *
3486
- * @example
3487
- * const authConfig = await authConfigs.create('my-toolkit', {
3488
- * type: AuthConfigTypes.CUSTOM,
3489
- * name: 'My Custom Auth Config',
3490
- * authScheme: AuthSchemeTypes.API_KEY,
3491
- * credentials: {
3492
- * apiKey: '1234567890',
3493
- * },
3494
- * });
2763
+ * This is a convenience method that calls updateStatus with 'ENABLED'.
2764
+ * When enabled, the auth config can be used to create new connected accounts
2765
+ * and authenticate with third-party services.
3495
2766
  *
3496
- * @link https://docs.composio.dev/reference/auth-configs/create-auth-config
2767
+ * @param {string} nanoid - The unique identifier of the auth config to enable
2768
+ * @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
2769
+ * @throws {Error} If the auth config cannot be found or enabled
2770
+ *
2771
+ * @example
2772
+ * ```typescript
2773
+ * // Enable an auth config
2774
+ * await composio.authConfigs.enable('auth_abc123');
2775
+ * ```
3497
2776
  */
3498
- async create(toolkit, options = { type: "use_composio_managed_auth" }, requestOptions) {
3499
- const parsedOptions = CreateAuthConfigParamsSchema.safeParse(options);
3500
- if (parsedOptions.error) throw new ValidationError("Failed to parse auth config create options", { cause: parsedOptions.error });
3501
- const createBody = {
3502
- toolkit: { slug: toolkit },
3503
- auth_config: parsedOptions.data.type === "use_custom_auth" ? {
3504
- type: parsedOptions.data.type,
3505
- name: parsedOptions.data.name,
3506
- authScheme: parsedOptions.data.authScheme,
3507
- credentials: parsedOptions.data.credentials,
3508
- is_enabled_for_tool_router: parsedOptions.data.isEnabledForToolRouter,
3509
- proxy_config: parsedOptions.data.proxyConfig ? {
3510
- proxy_url: parsedOptions.data.proxyConfig.proxyUrl,
3511
- proxy_auth_key: parsedOptions.data.proxyConfig.proxyAuthKey
3512
- } : void 0,
3513
- tool_access_config: parsedOptions.data.toolAccessConfig ? { tools_for_connected_account_creation: parsedOptions.data.toolAccessConfig.toolsForConnectedAccountCreation } : void 0
3514
- } : {
3515
- type: parsedOptions.data.type,
3516
- credentials: parsedOptions.data.credentials,
3517
- name: parsedOptions.data.name,
3518
- is_enabled_for_tool_router: parsedOptions.data.isEnabledForToolRouter,
3519
- tool_access_config: parsedOptions.data.toolAccessConfig ? { tools_for_connected_account_creation: parsedOptions.data.toolAccessConfig.toolsForConnectedAccountCreation } : void 0
3520
- }
3521
- };
3522
- const result = await withCancellation(() => this.client.authConfigs.create(createBody, requestOptions), requestOptions?.signal);
3523
- return transformCreateAuthConfigResponse(result);
2777
+ async enable(nanoid, requestOptions) {
2778
+ return withCancellation(() => this.client.authConfigs.updateStatus("ENABLED", { nanoid }, requestOptions), requestOptions?.signal);
3524
2779
  }
3525
2780
  /**
3526
- * Retrieves a specific authentication configuration by its ID.
2781
+ * Disables an authentication configuration.
3527
2782
  *
3528
- * This method fetches detailed information about a single auth config
3529
- * and transforms the response to the SDK's standardized format.
2783
+ * This is a convenience method that calls updateStatus with 'DISABLED'.
2784
+ * When disabled, the auth config cannot be used to create new connected accounts
2785
+ * or authenticate with third-party services, but existing connections may continue to work.
3530
2786
  *
3531
- * @param {string} nanoid - The unique identifier of the auth config to retrieve
3532
- * @returns {Promise<AuthConfigRetrieveResponse>} The auth config details
3533
- * @throws {Error} If the auth config cannot be found or an API error occurs
3534
- * @throws {ValidationError} If the response fails validation
2787
+ * @param {string} nanoid - The unique identifier of the auth config to disable
2788
+ * @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
2789
+ * @throws {Error} If the auth config cannot be found or disabled
3535
2790
  *
3536
2791
  * @example
3537
2792
  * ```typescript
3538
- * // Get an auth config by ID
3539
- * const authConfig = await composio.authConfigs.get('auth_abc123');
3540
- * console.log(authConfig.name); // e.g., 'GitHub Auth'
3541
- * console.log(authConfig.toolkit.slug); // e.g., 'github'
2793
+ * // Disable an auth config
2794
+ * await composio.authConfigs.disable('auth_abc123');
3542
2795
  * ```
3543
2796
  */
3544
- async get(nanoid, requestOptions) {
3545
- const result = await withCancellation(() => this.client.authConfigs.retrieve(nanoid, requestOptions), requestOptions?.signal);
3546
- return transformAuthConfigRetrieveResponse(result);
2797
+ async disable(nanoid, requestOptions) {
2798
+ return withCancellation(() => this.client.authConfigs.updateStatus("DISABLED", { nanoid }, requestOptions), requestOptions?.signal);
3547
2799
  }
2800
+ };
2801
+
2802
+ //#endregion
2803
+ //#region src/types/connectedAccounts.types.ts
2804
+ /**
2805
+ * Connected Account create parameters
2806
+ */
2807
+ const ConnectedAccountStatuses = {
2808
+ INITIALIZING: "INITIALIZING",
2809
+ INITIATED: "INITIATED",
2810
+ ACTIVE: "ACTIVE",
2811
+ FAILED: "FAILED",
2812
+ EXPIRED: "EXPIRED",
2813
+ INACTIVE: "INACTIVE",
2814
+ REVOKED: "REVOKED"
2815
+ };
2816
+ const ConnectedAccountStatusSchema = z$1.enum([
2817
+ ConnectedAccountStatuses.INITIALIZING,
2818
+ ConnectedAccountStatuses.INITIATED,
2819
+ ConnectedAccountStatuses.ACTIVE,
2820
+ ConnectedAccountStatuses.FAILED,
2821
+ ConnectedAccountStatuses.EXPIRED,
2822
+ ConnectedAccountStatuses.INACTIVE,
2823
+ ConnectedAccountStatuses.REVOKED
2824
+ ]);
2825
+ /**
2826
+ * Sharing model for a connected account.
2827
+ *
2828
+ * - `PRIVATE` (default): only the owning `userId` can use the connection.
2829
+ * - `SHARED`: can be used by other `userId`s, but only when the connection
2830
+ * is explicitly pinned in a tool-router session's config and only when
2831
+ * the requesting `userId` passes the connection's ACL (see
2832
+ * `allowAllUsers` / `allowedUserIds` / `notAllowedUserIds`).
2833
+ */
2834
+ const ConnectedAccountTypes = {
2835
+ PRIVATE: "PRIVATE",
2836
+ SHARED: "SHARED"
2837
+ };
2838
+ const ConnectedAccountTypeSchema = z$1.enum([ConnectedAccountTypes.PRIVATE, ConnectedAccountTypes.SHARED]);
2839
+ /**
2840
+ * Per-user access control for a SHARED connected account. Ignored for
2841
+ * PRIVATE.
2842
+ *
2843
+ * Pass `aclConfigForShared` on create / PATCH to grant access; omit it
2844
+ * to leave the ACL unchanged (on PATCH) or to keep the default
2845
+ * deny-by-default state (on create). On responses, the field is
2846
+ * `undefined` when the caller isn't authorised to see the ACL —
2847
+ * distinguish that from an empty/default state explicitly.
2848
+ *
2849
+ * Resolution rule (deny wins):
2850
+ * 1. requesting `userId` in `notAllowedUserIds` → DENY
2851
+ * 2. `allowAllUsers === true` → ALLOW
2852
+ * 3. requesting `userId` in `allowedUserIds` → ALLOW
2853
+ * 4. otherwise → DENY (deny-by-default)
2854
+ *
2855
+ * Default state (block omitted or `{}`) means only the connection's
2856
+ * creator can use it. The creator must grant access explicitly.
2857
+ *
2858
+ * Limits: each list accepts up to 1000 entries; each `userId` is
2859
+ * 1..256 characters.
2860
+ */
2861
+ const ACL_LIST_MAX_LENGTH = 1e3;
2862
+ const aclUserIdString = z$1.string().min(1).max(256);
2863
+ const ConnectedAccountAclConfigSchema = z$1.object({
2864
+ allowAllUsers: z$1.boolean().optional().describe("When true, any `userId` may use this SHARED connection (subject to the deny list). Default false."),
2865
+ allowedUserIds: z$1.array(aclUserIdString).max(ACL_LIST_MAX_LENGTH).optional().describe("Explicit list of `userId` strings allowed to use this SHARED connection. Default []."),
2866
+ notAllowedUserIds: z$1.array(aclUserIdString).max(ACL_LIST_MAX_LENGTH).optional().describe("Explicit list of `userId` strings denied access. Wins over allow on conflict. Default [].")
2867
+ });
2868
+ /**
2869
+ * Resolved ACL as it appears on responses. All three fields are populated
2870
+ * when the field is visible; the field itself is `undefined` for callers
2871
+ * not authorised to see it.
2872
+ */
2873
+ const ConnectedAccountAclConfigResponseSchema = z$1.object({
2874
+ allowAllUsers: z$1.boolean(),
2875
+ allowedUserIds: z$1.array(z$1.string()),
2876
+ notAllowedUserIds: z$1.array(z$1.string())
2877
+ });
2878
+ /**
2879
+ * Experimental options for SHARED connections, passed at create / link time.
2880
+ *
2881
+ * **Experimental — shape may change in future releases.** Wrapped under a
2882
+ * dedicated `experimental` block on every input and response so the
2883
+ * experimental status is visible at every call site.
2884
+ */
2885
+ const ConnectedAccountExperimentalSchema = z$1.object({
2886
+ accountType: ConnectedAccountTypeSchema.optional(),
2887
+ aclConfigForShared: ConnectedAccountAclConfigSchema.optional()
2888
+ });
2889
+ /**
2890
+ * Resolved experimental block on retrieve / list responses. `accountType`
2891
+ * is always present when the block is; `aclConfigForShared` is only
2892
+ * present when the caller is authorised to see the ACL.
2893
+ */
2894
+ const ConnectedAccountExperimentalResponseSchema = z$1.object({
2895
+ accountType: ConnectedAccountTypeSchema.optional(),
2896
+ aclConfigForShared: ConnectedAccountAclConfigResponseSchema.optional()
2897
+ });
2898
+ const CreateConnectedAccountParamsSchema = z$1.object({
2899
+ authConfig: z$1.object({ id: z$1.string() }),
2900
+ connection: z$1.object({
2901
+ data: z$1.record(z$1.string(), z$1.unknown()).optional(),
2902
+ callbackUrl: z$1.string().optional(),
2903
+ userId: z$1.string().optional()
2904
+ })
2905
+ });
2906
+ const DefaultCreateConnectedAccountParamsSchema = z$1.object({
2907
+ auth_config: z$1.object({ id: z$1.string() }),
2908
+ connection: z$1.object({
2909
+ state: ConnectionDataSchema.optional(),
2910
+ data: z$1.record(z$1.string(), z$1.unknown()).optional(),
2911
+ callback_url: z$1.string().optional(),
2912
+ user_id: z$1.string().optional(),
2913
+ alias: z$1.string().optional()
2914
+ })
2915
+ });
2916
+ const CreateConnectedAccountOptionsSchema = z$1.object({
2917
+ allowMultiple: z$1.boolean().optional(),
2918
+ callbackUrl: z$1.string().optional(),
2919
+ config: ConnectionDataSchema.optional(),
2920
+ alias: z$1.string().optional()
2921
+ });
2922
+ /**
2923
+ * Connected Account create response
2924
+ */
2925
+ const CreateConnectedAccountResponseSchema = z$1.object({
2926
+ id: z$1.string(),
2927
+ status: ConnectedAccountStatusSchema,
2928
+ redirectUrl: z$1.string().nullable()
2929
+ });
2930
+ const ConnectedAccountAuthConfigSchema = z$1.object({
2931
+ id: z$1.string(),
2932
+ /** @deprecated Use `connectedAccount.state.authScheme` instead. */
2933
+ authScheme: AuthSchemeEnum.optional(),
2934
+ isComposioManaged: z$1.boolean(),
2935
+ isDisabled: z$1.boolean()
2936
+ });
2937
+ const ConnectedAccountRetrieveResponseSchema = z$1.object({
2938
+ id: z$1.string(),
2939
+ authConfig: ConnectedAccountAuthConfigSchema,
2940
+ wordId: z$1.string().nullable().optional(),
2941
+ alias: z$1.string().nullable().optional(),
2942
+ /**
2943
+ * @deprecated Use `connectedAccount.state` instead — `data` is a legacy raw credential field.
2944
+ */
2945
+ data: z$1.record(z$1.string(), z$1.unknown()).optional(),
2946
+ /**
2947
+ * @deprecated Use `connectedAccount.state` instead — `params` is a legacy raw credential field.
2948
+ */
2949
+ params: z$1.record(z$1.string(), z$1.unknown()).optional(),
2950
+ status: ConnectedAccountStatusSchema,
2951
+ statusReason: z$1.string().nullable(),
2952
+ toolkit: z$1.object({ slug: z$1.string() }),
2953
+ state: ConnectionDataSchema.optional(),
2954
+ testRequestEndpoint: z$1.string().optional(),
2955
+ isDisabled: z$1.boolean(),
2956
+ createdAt: z$1.string(),
2957
+ updatedAt: z$1.string(),
2958
+ experimental: ConnectedAccountExperimentalResponseSchema.optional()
2959
+ });
2960
+ const ConnectedAccountListParamsSchema = z$1.object({
2961
+ authConfigIds: z$1.array(z$1.string()).nullable().optional().describe("The auth config ids of the connected accounts"),
2962
+ cursor: z$1.string().nullish().describe("The cursor to paginate through the connected accounts"),
2963
+ limit: z$1.number().nullable().optional().describe("The limit of the connected accounts to return"),
2964
+ orderBy: z$1.enum(["created_at", "updated_at"]).optional().describe("The order by of the connected accounts"),
2965
+ statuses: z$1.array(ConnectedAccountStatusSchema).nullable().optional().describe("The statuses of the connected accounts"),
2966
+ toolkitSlugs: z$1.array(z$1.string()).nullable().optional().describe("The toolkit slugs of the connected accounts"),
2967
+ userIds: z$1.array(z$1.string()).nullable().optional().describe("The user ids of the connected accounts"),
2968
+ /**
2969
+ * Experimental — shape may change in future releases. Filter by sharing
2970
+ * model. Default (omitted) returns PRIVATE only. Pass `'SHARED'` for only
2971
+ * shared accounts, or `'ALL'` for `PRIVATE` + `SHARED`. Kept flat because
2972
+ * the wire is a query string and can't carry nested objects.
2973
+ */
2974
+ accountType: z$1.enum([
2975
+ "PRIVATE",
2976
+ "SHARED",
2977
+ "ALL"
2978
+ ]).optional()
2979
+ });
2980
+ const ConnectedAccountListResponseSchema = z$1.object({
2981
+ items: z$1.array(ConnectedAccountRetrieveResponseSchema).describe("The list of connected accounts"),
2982
+ nextCursor: z$1.string().nullish().describe("The next cursor to paginate through the connected accounts"),
2983
+ totalPages: z$1.number().describe("The total number of pages of connected accounts")
2984
+ });
2985
+ const CreateConnectedAccountLinkOptionsSchema = z$1.object({
3548
2986
  /**
3549
- * Updates an existing authentication configuration.
3550
- *
3551
- * This method allows you to modify properties of an auth config such as credentials,
3552
- * scopes, or tool restrictions. The update type (custom or default) determines which
3553
- * fields can be updated.
2987
+ * The url to redirect the user to post connecting their account.
3554
2988
  *
3555
- * @param {string} nanoid - The unique identifier of the auth config to update
3556
- * @param {AuthConfigUpdateParams} data - The data to update, which can be either custom or default type
3557
- * @returns {Promise<AuthConfigUpdateResponse>} The updated auth config
3558
- * @throws {ValidationError} If the update parameters are invalid
3559
- * @throws {Error} If the auth config cannot be found or updated
2989
+ * For successful connections, you will get a query param called status=success
2990
+ * And for failed connections you will get a query param called status=failed
3560
2991
  *
3561
- * @example
3562
- * ```typescript
3563
- * // Update a custom auth config with new credentials
3564
- * const updatedConfig = await composio.authConfigs.update('auth_abc123', {
3565
- * type: 'custom',
3566
- * credentials: {
3567
- * apiKey: 'new-api-key-value'
3568
- * }
3569
- * });
2992
+ * @example https://your-app.com/callback
3570
2993
  *
3571
- * // Update a default auth config with new scopes
3572
- * const updatedConfig = await composio.authConfigs.update('auth_abc123', {
3573
- * type: 'default',
3574
- * scopes: ['read:user', 'repo']
3575
- * });
3576
- * ```
3577
2994
  */
3578
- async update(nanoid, data, requestOptions) {
3579
- const parsedData = AuthConfigUpdateParamsSchema.safeParse(data);
3580
- if (parsedData.error) throw new ValidationError("Failed to parse auth config update data", { cause: parsedData.error });
3581
- const updateBody = parsedData.data.type === "custom" ? {
3582
- type: "custom",
3583
- credentials: parsedData.data.credentials,
3584
- is_enabled_for_tool_router: parsedData.data.isEnabledForToolRouter,
3585
- tool_access_config: {
3586
- tools_for_connected_account_creation: parsedData.data.toolAccessConfig?.toolsForConnectedAccountCreation,
3587
- tools_available_for_execution: parsedData.data.toolAccessConfig?.toolsAvailableForExecution ?? parsedData.data.restrictToFollowingTools
3588
- }
3589
- } : {
3590
- type: "default",
3591
- scopes: parsedData.data.scopes,
3592
- is_enabled_for_tool_router: parsedData.data.isEnabledForToolRouter,
3593
- tool_access_config: {
3594
- tools_for_connected_account_creation: parsedData.data.toolAccessConfig?.toolsForConnectedAccountCreation,
3595
- tools_available_for_execution: parsedData.data.toolAccessConfig?.toolsAvailableForExecution ?? parsedData.data.restrictToFollowingTools
3596
- }
3597
- };
3598
- return withCancellation(() => this.client.authConfigs.update(nanoid, updateBody, requestOptions), requestOptions?.signal);
3599
- }
2995
+ callbackUrl: z$1.string().optional(),
3600
2996
  /**
3601
- * Deletes an authentication configuration.
3602
- *
3603
- * This method permanently removes an auth config from the Composio platform.
3604
- * This action cannot be undone and will prevent any connected accounts that use
3605
- * this auth config from functioning.
3606
- *
3607
- * @param {string} nanoid - The unique identifier of the auth config to delete
3608
- * @returns {Promise<AuthConfigDeleteResponse>} The deletion response
3609
- * @throws {Error} If the auth config doesn't exist or cannot be deleted
3610
- *
3611
- * @example
3612
- * ```typescript
3613
- * // Delete an auth config
3614
- * await composio.authConfigs.delete('auth_abc123');
3615
- * ```
2997
+ * Human-readable alias for the connected account. Must be unique per userId and toolkit within the project.
3616
2998
  */
3617
- async delete(nanoid, requestOptions) {
3618
- return withCancellation(() => this.client.authConfigs.delete(nanoid, void 0, requestOptions), requestOptions?.signal);
3619
- }
2999
+ alias: z$1.string().optional(),
3620
3000
  /**
3621
- * Updates the status of an authentication configuration.
3622
- *
3623
- * This method allows you to enable or disable an auth config. When disabled,
3624
- * the auth config cannot be used to create new connected accounts or authenticate
3625
- * with third-party services.
3626
- *
3627
- * @param {string} status - The status to set ('ENABLED' or 'DISABLED')
3628
- * @param {string} nanoid - The unique identifier of the auth config
3629
- * @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
3630
- * @throws {Error} If the auth config cannot be found or the status cannot be updated
3631
- *
3632
- * @example
3633
- * ```typescript
3634
- * // Disable an auth config
3635
- * await composio.authConfigs.updateStatus('DISABLED', 'auth_abc123');
3636
- *
3637
- * // Enable an auth config
3638
- * await composio.authConfigs.updateStatus('ENABLED', 'auth_abc123');
3639
- * ```
3001
+ * Whether to allow multiple connected accounts for the same user and auth config.
3002
+ * When `false` (default), `link()` throws `ComposioMultipleConnectedAccountsError`
3003
+ * if the user already has an `ACTIVE` connection on this auth config — matching
3004
+ * the guard on `initiate()`. Pair with `alias` and a session-level
3005
+ * `multiAccount` config to disambiguate at execution time.
3640
3006
  */
3641
- async updateStatus(status, nanoid, requestOptions) {
3642
- return withCancellation(() => this.client.authConfigs.updateStatus(status, { nanoid }, requestOptions), requestOptions?.signal);
3643
- }
3007
+ allowMultiple: z$1.boolean().optional(),
3644
3008
  /**
3645
- * Enables an authentication configuration.
3646
- *
3647
- * This is a convenience method that calls updateStatus with 'ENABLED'.
3648
- * When enabled, the auth config can be used to create new connected accounts
3649
- * and authenticate with third-party services.
3009
+ * Experimental options for SHARED connections. Pass `accountType: 'SHARED'`
3010
+ * (and optionally `aclConfigForShared`) to create a connection that can
3011
+ * be reached by other `userId`s when pinned in a session.
3650
3012
  *
3651
- * @param {string} nanoid - The unique identifier of the auth config to enable
3652
- * @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
3653
- * @throws {Error} If the auth config cannot be found or enabled
3013
+ * Experimental — shape may change in future releases.
3654
3014
  *
3655
- * @example
3656
- * ```typescript
3657
- * // Enable an auth config
3658
- * await composio.authConfigs.enable('auth_abc123');
3659
- * ```
3015
+ * `aclConfigForShared` is only valid when `accountType === 'SHARED'`;
3016
+ * raises `ComposioAclOnlyForSharedError` on a PRIVATE connection. Omit
3017
+ * the inner block (or pass `{}`) to keep the deny-by-default state: only
3018
+ * the creator can use the connection. Grant access by setting
3019
+ * `allowAllUsers: true` or listing user IDs in `allowedUserIds`.
3020
+ * `notAllowedUserIds` always wins over allow.
3660
3021
  */
3661
- async enable(nanoid, requestOptions) {
3662
- return withCancellation(() => this.client.authConfigs.updateStatus("ENABLED", { nanoid }, requestOptions), requestOptions?.signal);
3663
- }
3022
+ experimental: ConnectedAccountExperimentalSchema.optional()
3023
+ });
3024
+ const CreateConnectedAccountLinkResponseSchema = z$1.object({ redirectUrl: z$1.string() });
3025
+ const ConnectedAccountRefreshOptionsSchema = z$1.object({
3026
+ redirectUrl: z$1.string().optional(),
3664
3027
  /**
3665
- * Disables an authentication configuration.
3666
- *
3667
- * This is a convenience method that calls updateStatus with 'DISABLED'.
3668
- * When disabled, the auth config cannot be used to create new connected accounts
3669
- * or authenticate with third-party services, but existing connections may continue to work.
3670
- *
3671
- * @param {string} nanoid - The unique identifier of the auth config to disable
3672
- * @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
3673
- * @throws {Error} If the auth config cannot be found or disabled
3674
- *
3675
- * @example
3676
- * ```typescript
3677
- * // Disable an auth config
3678
- * await composio.authConfigs.disable('auth_abc123');
3679
- * ```
3028
+ * @deprecated The Composio API no longer accepts this field. It is ignored
3029
+ * and `refresh()` logs a warning when it is set.
3680
3030
  */
3681
- async disable(nanoid, requestOptions) {
3682
- return withCancellation(() => this.client.authConfigs.updateStatus("DISABLED", { nanoid }, requestOptions), requestOptions?.signal);
3683
- }
3684
- };
3031
+ validateCredentials: z$1.boolean().optional()
3032
+ });
3033
+ const UpdateConnectedAccountParamsSchema = z$1.object({ enabled: z$1.boolean() });
3034
+ /**
3035
+ * Params for `composio.connectedAccounts.updateAcl()`. Mirrors the inner
3036
+ * shape of the wire's `acl_config_for_shared` block — the SDK adds the
3037
+ * outer nesting at the boundary, so callers pass the three fields flat.
3038
+ *
3039
+ * PATCH-style semantics — omit a field to leave it unchanged; pass an
3040
+ * empty array to clear an allow/deny list. Raises
3041
+ * `ComposioAclOnlyForSharedError` on a PRIVATE connection.
3042
+ *
3043
+ * Each field is optional, but at least one must be provided — passing an
3044
+ * empty object is rejected as a no-op.
3045
+ */
3046
+ const UpdateConnectedAccountAclParamsSchema = ConnectedAccountAclConfigSchema.refine((acl) => acl.allowAllUsers !== void 0 || acl.allowedUserIds !== void 0 || acl.notAllowedUserIds !== void 0, { message: "At least one of allowAllUsers, allowedUserIds, or notAllowedUserIds must be provided" });
3047
+ /**
3048
+ * Response of `composio.connectedAccounts.revoke()`.
3049
+ */
3050
+ const ConnectedAccountRevokedTokenSchema = z$1.enum([
3051
+ "access_token",
3052
+ "refresh_token",
3053
+ "credential"
3054
+ ]);
3055
+ const ConnectedAccountRevokeResponseSchema = z$1.object({
3056
+ /**
3057
+ * Tokens revoked at the provider on this call. An empty array means the
3058
+ * connection was already revoked (no upstream dispatch).
3059
+ */
3060
+ revokedTokens: z$1.array(ConnectedAccountRevokedTokenSchema),
3061
+ connectedAccount: z$1.object({
3062
+ id: z$1.string(),
3063
+ /** The connection status after this call (`REVOKED` on success). */
3064
+ status: ConnectedAccountStatusSchema
3065
+ })
3066
+ });
3067
+ /**
3068
+ * Params for `composio.connectedAccounts.completeAuth()`.
3069
+ */
3070
+ const ConnectedAccountCompleteAuthParamsSchema = z$1.object({
3071
+ /** The user the connection was initiated for. Must match the connection owner. */
3072
+ userId: z$1.string().min(1),
3073
+ /** The opaque, single-use session URI your OAuth callback verifier received. */
3074
+ sessionUri: z$1.string().min(1)
3075
+ });
3076
+ /**
3077
+ * Response of `composio.connectedAccounts.completeAuth()`.
3078
+ */
3079
+ const ConnectedAccountCompleteAuthResponseSchema = z$1.object({
3080
+ /** The connection that was completed; it is now `ACTIVE`. */
3081
+ connectedAccountId: z$1.string(),
3082
+ /** The toolkit the connection belongs to. */
3083
+ toolkitSlug: z$1.string()
3084
+ });
3685
3085
 
3686
3086
  //#endregion
3687
3087
  //#region src/utils/transformers/connectedAccounts.ts
@@ -4060,6 +3460,10 @@ var Usage = class {
4060
3460
 
4061
3461
  //#endregion
4062
3462
  //#region src/types/customToolkits.types.ts
3463
+ const CustomToolkitApiKeyFieldSchema = z$1.object({
3464
+ displayName: z$1.string().min(1).max(100).optional(),
3465
+ description: z$1.string().min(1).max(500).optional()
3466
+ });
4063
3467
  /**
4064
3468
  * How end users authenticate to a custom toolkit.
4065
3469
  * **Experimental — custom toolkits are in pilot; shape may change.**
@@ -4075,10 +3479,12 @@ const CustomToolkitAuthSchemeSchema = z$1.discriminatedUnion("mode", [
4075
3479
  */
4076
3480
  headers: z$1.record(z$1.string(), z$1.string()),
4077
3481
  /** End-user copy for the API key input on the connect page. */
4078
- apiKeyField: z$1.object({
4079
- displayName: z$1.string().min(1).max(100).optional(),
3482
+ apiKeyField: CustomToolkitApiKeyFieldSchema.optional(),
3483
+ /** Additional connect-page input used by `{{generic_id}}` in headers. */
3484
+ additionalFields: z$1.object({ genericId: z$1.object({
3485
+ displayName: z$1.string().min(1).max(100),
4080
3486
  description: z$1.string().min(1).max(500).optional()
4081
- }).optional()
3487
+ }) }).optional()
4082
3488
  }),
4083
3489
  z$1.object({
4084
3490
  mode: z$1.literal("DCR_OAUTH"),
@@ -4089,9 +3495,69 @@ const CustomToolkitAuthSchemeSchema = z$1.discriminatedUnion("mode", [
4089
3495
  discoveryUrl: z$1.string().url()
4090
3496
  })
4091
3497
  ]);
3498
+ const CustomToolkitLogoFileSchema = z$1.object({
3499
+ content: z$1.string().min(1),
3500
+ mimeType: z$1.enum(["image/png", "image/jpeg"])
3501
+ });
3502
+ /**
3503
+ * Params for `composio.experimental.customToolkits.create()`.
3504
+ * **Experimental — custom toolkits are in pilot; shape may change.**
3505
+ */
3506
+ const CustomToolkitCreateParamsSchema = z$1.object({
3507
+ /** Human-readable toolkit name. */
3508
+ name: z$1.string().min(1).max(200),
3509
+ /** The MCP server URL. Must use https. */
3510
+ appUrl: z$1.string().url(),
3511
+ /** Square PNG or JPEG logo (256-1024px, max 3MB), base64-encoded. Defaults to the MCP logo. */
3512
+ logoFile: CustomToolkitLogoFileSchema.optional(),
3513
+ /** At least one scheme. Cannot be changed after create. */
3514
+ authSchemes: z$1.array(CustomToolkitAuthSchemeSchema).min(1),
3515
+ /**
3516
+ * `'all'` to share the toolkit with every user in the project, or a user ID
3517
+ * to make it private to that user. Cannot be changed after create.
3518
+ */
3519
+ userId: z$1.string().min(1),
3520
+ /** Where to send the user after they connect. Used only for `connectLink`. */
3521
+ callbackUrl: z$1.string().url().optional()
3522
+ });
3523
+ const CustomToolkitCreateResponseSchema = z$1.object({
3524
+ /** Slug of the created toolkit. Store it to update, sync or delete the toolkit later. */
3525
+ slug: z$1.string(),
3526
+ /**
3527
+ * Hosted connect page for a private toolkit's user. `null` for shared or
3528
+ * no-auth toolkits, or if the link could not be created.
3529
+ */
3530
+ connectLink: z$1.object({
3531
+ redirectUrl: z$1.string(),
3532
+ expiresAt: z$1.string(),
3533
+ connectedAccountId: z$1.string()
3534
+ }).nullable()
3535
+ });
3536
+ /**
3537
+ * Params for `composio.experimental.customToolkits.update()`.
3538
+ * **Experimental — custom toolkits are in pilot; shape may change.**
3539
+ */
3540
+ const CustomToolkitUpdateParamsSchema = z$1.object({
3541
+ name: z$1.string().min(1).max(200).optional(),
3542
+ logoFile: CustomToolkitLogoFileSchema.optional(),
3543
+ /** End-user copy for the API key input on the connect page. API_KEY toolkits only. */
3544
+ apiKeyField: CustomToolkitApiKeyFieldSchema.optional(),
3545
+ /**
3546
+ * The user the toolkit is private to. Required to update a private toolkit
3547
+ * when the project has 2FA enabled.
3548
+ */
3549
+ userId: z$1.string().min(1).optional()
3550
+ }).refine((params) => [
3551
+ params.name,
3552
+ params.logoFile,
3553
+ params.apiKeyField
3554
+ ].some((value) => value !== void 0), { message: "Provide at least one of name, logoFile, apiKeyField" });
3555
+ const CustomToolkitUpdateResponseSchema = z$1.object({ success: z$1.literal(true) });
4092
3556
  /**
4093
3557
  * Params for `composio.experimental.customToolkits.upsert()`.
4094
3558
  * **Experimental — custom toolkits are in pilot; shape may change.**
3559
+ *
3560
+ * @deprecated Use `CustomToolkitCreateParams` with `create()`.
4095
3561
  */
4096
3562
  const CustomToolkitUpsertParamsSchema = z$1.object({
4097
3563
  /**
@@ -4105,10 +3571,7 @@ const CustomToolkitUpsertParamsSchema = z$1.object({
4105
3571
  /** The app URL. For an MCP app, the MCP server URL. */
4106
3572
  appUrl: z$1.string().url(),
4107
3573
  /** Square PNG or JPEG logo (256-1024px, max 3MB), base64-encoded. Defaults to the Composio logo. */
4108
- logoFile: z$1.object({
4109
- content: z$1.string().min(1),
4110
- mimeType: z$1.enum(["image/png", "image/jpeg"])
4111
- }).optional(),
3574
+ logoFile: CustomToolkitLogoFileSchema.optional(),
4112
3575
  /** At least one scheme. The schemes cannot change once the toolkit exists. */
4113
3576
  authSchemes: z$1.array(CustomToolkitAuthSchemeSchema).min(1)
4114
3577
  })
@@ -4142,16 +3605,25 @@ const CustomToolkitDeleteResponseSchema = z$1.object({
4142
3605
 
4143
3606
  //#endregion
4144
3607
  //#region src/utils/transformers/customToolkits.ts
3608
+ const transformCustomToolkitLogoFile = (logoFile) => logoFile && {
3609
+ content: logoFile.content,
3610
+ mime_type: logoFile.mimeType
3611
+ };
3612
+ const transformCustomToolkitApiKeyField = (apiKeyField) => apiKeyField && {
3613
+ display_name: apiKeyField.displayName,
3614
+ description: apiKeyField.description
3615
+ };
4145
3616
  const transformCustomToolkitAuthScheme = (scheme) => {
4146
3617
  switch (scheme.mode) {
4147
3618
  case "NO_AUTH": return { mode: "NO_AUTH" };
4148
3619
  case "API_KEY": return {
4149
3620
  mode: "API_KEY",
4150
3621
  headers: scheme.headers,
4151
- api_key_field: scheme.apiKeyField && {
4152
- display_name: scheme.apiKeyField.displayName,
4153
- description: scheme.apiKeyField.description
4154
- }
3622
+ api_key_field: transformCustomToolkitApiKeyField(scheme.apiKeyField),
3623
+ ...scheme.additionalFields && { additional_fields: { generic_id: {
3624
+ display_name: scheme.additionalFields.genericId.displayName,
3625
+ description: scheme.additionalFields.genericId.description
3626
+ } } }
4155
3627
  };
4156
3628
  case "DCR_OAUTH": return {
4157
3629
  mode: "DCR_OAUTH",
@@ -4159,15 +3631,39 @@ const transformCustomToolkitAuthScheme = (scheme) => {
4159
3631
  };
4160
3632
  }
4161
3633
  };
3634
+ const transformCustomToolkitCreateParams = (params) => ({
3635
+ name: params.name,
3636
+ app_url: params.appUrl,
3637
+ logo_file: transformCustomToolkitLogoFile(params.logoFile),
3638
+ auth_schemes: params.authSchemes.map(transformCustomToolkitAuthScheme),
3639
+ user_id: params.userId,
3640
+ callback_url: params.callbackUrl
3641
+ });
3642
+ const transformCustomToolkitCreateResponse = (response) => {
3643
+ return transform(response).with(CustomToolkitCreateResponseSchema).using((response) => ({
3644
+ slug: response.slug,
3645
+ connectLink: response.connect_link && {
3646
+ redirectUrl: response.connect_link.redirect_url,
3647
+ expiresAt: response.connect_link.expires_at,
3648
+ connectedAccountId: response.connect_link.connected_account_id
3649
+ }
3650
+ }));
3651
+ };
3652
+ const transformCustomToolkitUpdateParams = (params) => ({
3653
+ name: params.name,
3654
+ logo_file: transformCustomToolkitLogoFile(params.logoFile),
3655
+ api_key_field: transformCustomToolkitApiKeyField(params.apiKeyField),
3656
+ user_id: params.userId
3657
+ });
3658
+ const transformCustomToolkitUpdateResponse = (response) => {
3659
+ return transform(response).with(CustomToolkitUpdateResponseSchema).using((response) => ({ success: response.success }));
3660
+ };
4162
3661
  const transformCustomToolkitUpsertParams = (params) => ({
4163
3662
  slug: params.slug,
4164
3663
  toolkit_config: {
4165
3664
  name: params.toolkitConfig.name,
4166
3665
  app_url: params.toolkitConfig.appUrl,
4167
- logo_file: params.toolkitConfig.logoFile && {
4168
- content: params.toolkitConfig.logoFile.content,
4169
- mime_type: params.toolkitConfig.logoFile.mimeType
4170
- },
3666
+ logo_file: transformCustomToolkitLogoFile(params.toolkitConfig.logoFile),
4171
3667
  auth_schemes: params.toolkitConfig.authSchemes.map(transformCustomToolkitAuthScheme)
4172
3668
  }
4173
3669
  });
@@ -4197,6 +3693,8 @@ const transformCustomToolkitDeleteResponse = (response) => {
4197
3693
 
4198
3694
  //#endregion
4199
3695
  //#region src/models/CustomToolkits.ts
3696
+ const UPSERT_DEPRECATION = "[Deprecation] composio.experimental.customToolkits.upsert() is deprecated. Use create() for a new toolkit and update(slug, ...) to change its name, logo or API key field.";
3697
+ let _upsertDeprecationWarned = false;
4200
3698
  /**
4201
3699
  * `composio.experimental.customToolkits` — toolkits your project registers
4202
3700
  * from its own app or MCP server, with their own auth configs and connected
@@ -4208,15 +3706,13 @@ const transformCustomToolkitDeleteResponse = (response) => {
4208
3706
  *
4209
3707
  * @example
4210
3708
  * ```typescript
4211
- * const { slug } = await composio.experimental.customToolkits.upsert({
4212
- * slug: 'MY_TOOLKIT',
4213
- * toolkitConfig: {
4214
- * name: 'My Toolkit',
4215
- * appUrl: 'https://mcp.example.com/mcp',
4216
- * authSchemes: [{ mode: 'DCR_OAUTH', discoveryUrl: 'https://mcp.example.com/.well-known/oauth-authorization-server' }],
4217
- * },
3709
+ * const { slug } = await composio.experimental.customToolkits.create({
3710
+ * name: 'My Toolkit',
3711
+ * appUrl: 'https://mcp.example.com/mcp',
3712
+ * authSchemes: [{ mode: 'DCR_OAUTH', discoveryUrl: 'https://mcp.example.com/.well-known/oauth-authorization-server' }],
3713
+ * userId: 'all',
4218
3714
  * });
4219
- * await composio.experimental.customToolkits.sync(slug);
3715
+ * await composio.experimental.customToolkits.update(slug, { name: 'My Renamed Toolkit' });
4220
3716
  * ```
4221
3717
  */
4222
3718
  var CustomToolkits = class {
@@ -4226,6 +3722,67 @@ var CustomToolkits = class {
4226
3722
  telemetry.instrument(this, "CustomToolkits");
4227
3723
  }
4228
3724
  /**
3725
+ * Creates a custom MCP toolkit and returns its generated slug.
3726
+ * **Experimental — custom toolkits are in pilot; shape may change.**
3727
+ *
3728
+ * Set `userId` to `'all'` to share the toolkit with every user in the
3729
+ * project, or to a user ID to make it private to that user. `appUrl`,
3730
+ * `authSchemes` and `userId` cannot change later: delete and re-create the
3731
+ * toolkit instead. For a private toolkit, `connectLink` is where to send
3732
+ * that user to connect.
3733
+ *
3734
+ * @param {CustomToolkitCreateParams} params - The toolkit to create
3735
+ * @returns {Promise<CustomToolkitCreateResponse>} The toolkit's slug and, for a private toolkit, a connect link
3736
+ * @throws {ValidationError} If the params fail validation
3737
+ *
3738
+ * @example
3739
+ * ```typescript
3740
+ * const { slug, connectLink } = await composio.experimental.customToolkits.create({
3741
+ * name: 'Internal API',
3742
+ * appUrl: 'https://mcp.internal.example.com/mcp',
3743
+ * authSchemes: [
3744
+ * { mode: 'API_KEY', headers: { Authorization: 'Bearer {{generic_api_key}}' } },
3745
+ * ],
3746
+ * userId: 'user_123',
3747
+ * });
3748
+ * ```
3749
+ */
3750
+ async create(params, requestOptions) {
3751
+ const parsedParams = CustomToolkitCreateParamsSchema.safeParse(params);
3752
+ if (!parsedParams.success) throw new ValidationError("Failed to parse custom toolkit create params", { cause: parsedParams.error });
3753
+ const body = transformCustomToolkitCreateParams(parsedParams.data);
3754
+ const result = await withCancellation(() => this.client.custom.createToolkit(body, requestOptions), requestOptions?.signal);
3755
+ return transformCustomToolkitCreateResponse(result);
3756
+ }
3757
+ /**
3758
+ * Updates a custom toolkit's name, logo or API key field copy. Omitted
3759
+ * fields keep their current value.
3760
+ * **Experimental — custom toolkits are in pilot; shape may change.**
3761
+ *
3762
+ * On a project with 2FA enabled, updating a private toolkit requires the
3763
+ * `userId` it is private to.
3764
+ *
3765
+ * @param {string} slug - The custom toolkit slug returned by `create()`
3766
+ * @param {CustomToolkitUpdateParams} params - At least one of `name`, `logoFile`, `apiKeyField`
3767
+ * @returns {Promise<CustomToolkitUpdateResponse>} `{ success: true }`
3768
+ * @throws {ValidationError} If the params fail validation
3769
+ *
3770
+ * @example
3771
+ * ```typescript
3772
+ * await composio.experimental.customToolkits.update('CUSTOM_INTERNAL_API_K7F2Q', {
3773
+ * name: 'Internal API (prod)',
3774
+ * userId: 'user_123',
3775
+ * });
3776
+ * ```
3777
+ */
3778
+ async update(slug, params, requestOptions) {
3779
+ const parsedParams = CustomToolkitUpdateParamsSchema.safeParse(params);
3780
+ if (!parsedParams.success) throw new ValidationError("Failed to parse custom toolkit update params", { cause: parsedParams.error });
3781
+ const body = transformCustomToolkitUpdateParams(parsedParams.data);
3782
+ const result = await withCancellation(() => this.client.custom.updateToolkits(slug, body, requestOptions), requestOptions?.signal);
3783
+ return transformCustomToolkitUpdateResponse(result);
3784
+ }
3785
+ /**
4229
3786
  * Creates a custom toolkit, or updates its display metadata (name, API key
4230
3787
  * field copy) when the project already owns a toolkit with this slug.
4231
3788
  * **Experimental — custom toolkits are in pilot; shape may change.**
@@ -4251,8 +3808,16 @@ var CustomToolkits = class {
4251
3808
  * },
4252
3809
  * });
4253
3810
  * ```
3811
+ *
3812
+ * @deprecated Use `create()` for a new toolkit and `update(slug, ...)` to change
3813
+ * its name, logo or API key field. `create()` generates the slug, so store the
3814
+ * slug it returns.
4254
3815
  */
4255
3816
  async upsert(params, requestOptions) {
3817
+ if (!_upsertDeprecationWarned) {
3818
+ _upsertDeprecationWarned = true;
3819
+ logger.warn(UPSERT_DEPRECATION);
3820
+ }
4256
3821
  const parsedParams = CustomToolkitUpsertParamsSchema.safeParse(params);
4257
3822
  if (!parsedParams.success) throw new ValidationError("Failed to parse custom toolkit upsert params", { cause: parsedParams.error });
4258
3823
  const body = transformCustomToolkitUpsertParams(parsedParams.data);
@@ -4384,7 +3949,7 @@ var Experimental = class {
4384
3949
  */
4385
3950
  usage;
4386
3951
  /**
4387
- * Register and manage project-owned custom toolkits (`upsert()` / `sync()` / `delete()`).
3952
+ * Register and manage project-owned custom toolkits (`create()` / `update()` / `sync()` / `delete()`).
4388
3953
  * **Experimental — custom toolkits are in pilot; shape may change.**
4389
3954
  *
4390
3955
  * @example
@@ -5051,7 +4616,8 @@ const transformToolkitRetrieveResponse = (response) => {
5051
4616
  slug: category.slug,
5052
4617
  name: category.name
5053
4618
  })),
5054
- availableVersions: response.meta.available_versions
4619
+ availableVersions: response.meta.available_versions,
4620
+ ...response.meta.app_url != null && { appUrl: response.meta.app_url }
5055
4621
  },
5056
4622
  isLocalToolkit: response.is_local_toolkit,
5057
4623
  composioManagedAuthSchemes: response.composio_managed_auth_schemes,
@@ -5459,6 +5025,7 @@ const TriggerInstanceListActiveParamsSchema = z$1.object({
5459
5025
  triggerIds: z$1.array(z$1.string()).nullable().optional(),
5460
5026
  triggerNames: z$1.array(z$1.string()).nullable().optional()
5461
5027
  });
5028
+ const TriggerInstanceTypeSchema = z$1.enum(["webhook", "poll"]);
5462
5029
  const TriggerInstanceListActiveResponseItemSchema = z$1.object({
5463
5030
  id: z$1.string(),
5464
5031
  connectedAccountId: z$1.string(),
@@ -5468,7 +5035,10 @@ const TriggerInstanceListActiveResponseItemSchema = z$1.object({
5468
5035
  triggerName: z$1.string(),
5469
5036
  updatedAt: z$1.string(),
5470
5037
  triggerData: z$1.string().optional(),
5471
- uuid: z$1.string().optional()
5038
+ uuid: z$1.string().optional(),
5039
+ type: TriggerInstanceTypeSchema,
5040
+ fallbackReason: z$1.string().nullable(),
5041
+ pollingInterval: z$1.number().nullable()
5472
5042
  });
5473
5043
  const TriggerInstanceListActiveResponseSchema = z$1.object({
5474
5044
  items: z$1.array(TriggerInstanceListActiveResponseItemSchema),
@@ -5477,9 +5047,16 @@ const TriggerInstanceListActiveResponseSchema = z$1.object({
5477
5047
  });
5478
5048
  const TriggerInstanceUpsertParamsSchema = z$1.object({
5479
5049
  connectedAccountId: z$1.string().optional(),
5480
- triggerConfig: z$1.record(z$1.unknown()).optional()
5050
+ triggerConfig: z$1.record(z$1.unknown()).optional(),
5051
+ type: TriggerInstanceTypeSchema.optional(),
5052
+ pollingInterval: z$1.number().int().positive().optional()
5053
+ });
5054
+ const TriggerInstanceUpsertResponseSchema = z$1.object({
5055
+ triggerId: z$1.string(),
5056
+ type: TriggerInstanceTypeSchema,
5057
+ fallbackReason: z$1.string().nullable(),
5058
+ pollingInterval: z$1.number().nullable()
5481
5059
  });
5482
- const TriggerInstanceUpsertResponseSchema = z$1.object({ triggerId: z$1.string() });
5483
5060
  const TriggerInstanceManageUpdateParamsSchema = z$1.object({ status: z$1.enum(["enable", "disable"]) });
5484
5061
  const TriggerInstanceManageUpdateResponseSchema = z$1.object({ status: z$1.enum(["success"]) });
5485
5062
  const TriggerInstanceManageDeleteResponseSchema = z$1.object({ triggerId: z$1.string() });
@@ -5525,7 +5102,10 @@ const TriggerTypeSchema = z$1.object({
5525
5102
  }),
5526
5103
  payload: z$1.record(z$1.unknown()),
5527
5104
  config: z$1.record(z$1.unknown()),
5528
- version: z$1.string().optional()
5105
+ version: z$1.string().optional(),
5106
+ type: TriggerInstanceTypeSchema,
5107
+ types: z$1.array(TriggerInstanceTypeSchema),
5108
+ requiresWebhookEndpointSetup: z$1.boolean().optional()
5529
5109
  });
5530
5110
  const TriggersTypeListResponseSchema = z$1.object({
5531
5111
  items: z$1.array(TriggerTypeSchema),
@@ -6838,8 +6418,8 @@ function transformIncomingTriggerPayload(response) {
6838
6418
  }
6839
6419
  }));
6840
6420
  }
6841
- function transformTriggerTypeRetrieveResponse(response) {
6842
- return transform(response).with(TriggerTypeSchema).using((response) => ({
6421
+ function toTriggerType(response) {
6422
+ return {
6843
6423
  slug: response.slug,
6844
6424
  name: response.name,
6845
6425
  description: response.description,
@@ -6851,12 +6431,18 @@ function transformTriggerTypeRetrieveResponse(response) {
6851
6431
  },
6852
6432
  version: response.version,
6853
6433
  payload: response.payload,
6854
- config: response.config
6855
- }));
6434
+ config: response.config,
6435
+ type: response.type,
6436
+ types: response.types,
6437
+ requiresWebhookEndpointSetup: response.requires_webhook_endpoint_setup
6438
+ };
6439
+ }
6440
+ function transformTriggerTypeRetrieveResponse(response) {
6441
+ return transform(response).with(TriggerTypeSchema).using(toTriggerType);
6856
6442
  }
6857
6443
  function transformTriggerTypeListResponse(response) {
6858
6444
  return transform(response).with(TriggersTypeListResponseSchema).using((response) => ({
6859
- items: response.items,
6445
+ items: response.items.map(toTriggerType),
6860
6446
  nextCursor: response.next_cursor ?? null,
6861
6447
  totalPages: response.total_pages
6862
6448
  }));
@@ -6877,7 +6463,10 @@ function transformTriggerInstanceListActiveItem(response) {
6877
6463
  triggerName: response.trigger_name,
6878
6464
  updatedAt: response.updated_at,
6879
6465
  triggerData: response.trigger_data,
6880
- uuid: response.uuid
6466
+ uuid: response.uuid,
6467
+ type: response.type,
6468
+ fallbackReason: response.fallback_reason,
6469
+ pollingInterval: response.polling_interval
6881
6470
  }));
6882
6471
  }
6883
6472
  function transformTriggerInstanceListActiveResponse(response) {
@@ -7040,10 +6629,14 @@ var Triggers = class {
7040
6629
  * Create a new trigger instance for a user
7041
6630
  * If the connected account id is not provided, the first connected account for the user and toolkit will be used
7042
6631
  *
6632
+ * For a trigger that supports both webhook and polling, `body.type` picks one; omit it to let Composio choose.
6633
+ * `body.pollingInterval` sets the minutes between polls and wins over `triggerConfig.interval`.
6634
+ *
7043
6635
  * @param {string} userId - The user id of the trigger instance
7044
6636
  * @param {string} slug - The slug of the trigger instance
7045
6637
  * @param {TriggerInstanceUpsertParams} body - The parameters to create the trigger instance
7046
- * @returns {Promise<TriggerInstanceUpsertResponse>} The created trigger instance
6638
+ * @returns {Promise<TriggerInstanceUpsertResponse>} The trigger instance, with the type it uses, why it polls
6639
+ * when it fell back from a webhook, and its polling interval
7047
6640
  */
7048
6641
  async create(userId, slug, body, requestOptions) {
7049
6642
  if (!userId?.trim()) throw new ValidationError(`A non-empty userId is required to create a trigger`);
@@ -7065,10 +6658,18 @@ var Triggers = class {
7065
6658
  const upsertParams = {
7066
6659
  connected_account_id: parsedBody.data.connectedAccountId,
7067
6660
  trigger_config: parsedBody.data.triggerConfig,
6661
+ type: parsedBody.data.type,
6662
+ polling_interval: parsedBody.data.pollingInterval,
7068
6663
  toolkit_versions: this.toolkitVersions,
7069
6664
  user_id: userId
7070
6665
  };
7071
- return { triggerId: (await withCancellation(() => this.client.triggerInstances.upsert(slug, upsertParams, requestOptions), requestOptions?.signal)).trigger_id };
6666
+ const result = await withCancellation(() => this.client.triggerInstances.upsert(slug, upsertParams, requestOptions), requestOptions?.signal);
6667
+ return {
6668
+ triggerId: result.trigger_id,
6669
+ type: result.type,
6670
+ fallbackReason: result.fallback_reason,
6671
+ pollingInterval: result.polling_interval
6672
+ };
7072
6673
  }
7073
6674
  /**
7074
6675
  * Update an existing trigger instance
@@ -7867,512 +7468,1078 @@ var MCP = class {
7867
7468
  if (toolkit.authConfigId) auth_config_ids.push(toolkit.authConfigId);
7868
7469
  }
7869
7470
  });
7870
- const createBody = {
7871
- name,
7872
- toolkits,
7873
- auth_config_ids,
7874
- allowed_tools,
7875
- managed_auth_via_composio: config.data.manuallyManageConnections ? false : true
7876
- };
7877
- const server = await withCancellation(() => this.client.mcp.custom.create(createBody, requestOptions), requestOptions?.signal);
7878
- return {
7879
- ...transform(server).with(MCPConfigResponseSchema).using((raw) => ({
7880
- name: raw.name,
7881
- allowedTools: raw.allowed_tools,
7882
- id: raw.id,
7883
- authConfigIds: raw.auth_config_ids,
7884
- commands: raw.commands,
7885
- MCPUrl: raw.mcp_url
7886
- })),
7887
- generate: async (userId) => {
7888
- return await this.generate(userId, server.id, { manuallyManageConnections: config.data.manuallyManageConnections });
7889
- }
7471
+ const createBody = {
7472
+ name,
7473
+ toolkits,
7474
+ auth_config_ids,
7475
+ allowed_tools,
7476
+ managed_auth_via_composio: config.data.manuallyManageConnections ? false : true
7477
+ };
7478
+ const server = await withCancellation(() => this.client.mcp.custom.create(createBody, requestOptions), requestOptions?.signal);
7479
+ return {
7480
+ ...transform(server).with(MCPConfigResponseSchema).using((raw) => ({
7481
+ name: raw.name,
7482
+ allowedTools: raw.allowed_tools,
7483
+ id: raw.id,
7484
+ authConfigIds: raw.auth_config_ids,
7485
+ commands: raw.commands,
7486
+ MCPUrl: raw.mcp_url
7487
+ })),
7488
+ generate: async (userId) => {
7489
+ return await this.generate(userId, server.id, { manuallyManageConnections: config.data.manuallyManageConnections });
7490
+ }
7491
+ };
7492
+ }
7493
+ /**
7494
+ * List the MCP servers with optional filtering and pagination
7495
+ * @param {Object} options - Filtering and pagination options
7496
+ * @param {number} [options.page=1] - Page number for pagination (1-based)
7497
+ * @param {number} [options.limit=10] - Maximum number of items to return per page
7498
+ * @param {string[]} [options.toolkits=[]] - Array of toolkit names to filter by
7499
+ * @param {string[]} [options.authConfigs=[]] - Array of auth configuration IDs to filter by
7500
+ * @param {string} [options.name] - Filter by MCP server name (partial match)
7501
+ * @returns {Promise<MCPListResponse>} Paginated list of MCP servers with metadata
7502
+ *
7503
+ * @example
7504
+ * ```typescript
7505
+ * // List all MCP servers
7506
+ * const allServers = await composio.experimental.mcp.list({});
7507
+ *
7508
+ * // List with pagination
7509
+ * const pagedServers = await composio.experimental.mcp.list({
7510
+ * page: 2,
7511
+ * limit: 5
7512
+ * });
7513
+ *
7514
+ * // Filter by toolkit
7515
+ * const githubServers = await composio.experimental.mcp.list({
7516
+ * toolkits: ['github', 'slack']
7517
+ * });
7518
+ *
7519
+ * // Filter by name
7520
+ * const namedServers = await composio.experimental.mcp.list({
7521
+ * name: 'personal'
7522
+ * });
7523
+ * ```
7524
+ */
7525
+ async list(options, requestOptions) {
7526
+ const { data: params, error } = MCPListParamsSchema.safeParse(options);
7527
+ if (error) throw new ValidationError("Failed to validate list options", { cause: error });
7528
+ const listParams = {
7529
+ page_no: params.page,
7530
+ limit: params.limit,
7531
+ toolkits: params.toolkits?.length > 0 ? params.toolkits.join(",") : void 0,
7532
+ auth_config_ids: params.authConfigs?.length > 0 ? params.authConfigs.join(",") : void 0,
7533
+ name: params.name
7534
+ };
7535
+ const listResponse = await withCancellation(() => this.client.mcp.list(listParams, requestOptions), requestOptions?.signal);
7536
+ return transform(listResponse).with(MCPListResponseSchema).using((raw) => ({
7537
+ currentPage: raw.current_page,
7538
+ totalPages: raw.total_pages,
7539
+ items: raw.items.map((item) => ({
7540
+ name: item.name,
7541
+ allowedTools: item.allowed_tools,
7542
+ id: item.id,
7543
+ authConfigIds: item.auth_config_ids,
7544
+ commands: item.commands,
7545
+ MCPUrl: item.mcp_url,
7546
+ toolkitIcons: item.toolkit_icons,
7547
+ serverInstanceCount: item.server_instance_count,
7548
+ toolkits: item.toolkits
7549
+ }))
7550
+ }));
7551
+ }
7552
+ /**
7553
+ * Retrieve detailed information about a specific MCP server by its ID
7554
+ * @param {string} serverId - The unique identifier of the MCP server to retrieve
7555
+ * @returns {Promise<MCPItem>} Complete MCP server details including configuration, tools, and metadata
7556
+ *
7557
+ * @example
7558
+ * ```typescript
7559
+ * // Get a specific MCP server by ID
7560
+ * const server = await composio.experimental.mcp.get("mcp_12345");
7561
+ *
7562
+ * console.log(server.name); // "My Personal MCP Server"
7563
+ * console.log(server.allowedTools); // ["GITHUB_CREATE_ISSUE", "SLACK_SEND_MESSAGE"]
7564
+ * console.log(server.toolkits); // ["github", "slack"]
7565
+ * console.log(server.serverInstanceCount); // 3
7566
+ *
7567
+ * // Access setup commands for different clients
7568
+ * console.log(server.commands.claude); // Claude setup command
7569
+ * console.log(server.commands.cursor); // Cursor setup command
7570
+ * console.log(server.commands.windsurf); // Windsurf setup command
7571
+ *
7572
+ * // Use the MCP URL for direct connections
7573
+ * const mcpUrl = server.MCPUrl;
7574
+ * ```
7575
+ *
7576
+ * @throws {ValidationError} When the server ID is invalid or server not found
7577
+ */
7578
+ async get(serverId, requestOptions) {
7579
+ return transformMCPItemResponse(await withCancellation(() => this.client.mcp.retrieve(serverId, requestOptions), requestOptions?.signal));
7580
+ }
7581
+ /**
7582
+ * Delete an MCP server configuration permanently
7583
+ * @param {string} serverId - The unique identifier of the MCP server to delete
7584
+ * @returns {Promise<{id: string; deleted: boolean}>} Confirmation object with server ID and deletion status
7585
+ *
7586
+ * @example
7587
+ * ```typescript
7588
+ * // Delete an MCP server by ID
7589
+ * const result = await composio.experimental.mcp.delete("mcp_12345");
7590
+ *
7591
+ * if (result.deleted) {
7592
+ * console.log(`Server ${result.id} has been successfully deleted`);
7593
+ * } else {
7594
+ * console.log(`Failed to delete server ${result.id}`);
7595
+ * }
7596
+ *
7597
+ * // Example with error handling
7598
+ * try {
7599
+ * const result = await composio.experimental.mcp.delete("mcp_12345");
7600
+ * console.log("Deletion successful:", result);
7601
+ * } catch (error) {
7602
+ * console.error("Failed to delete MCP server:", error.message);
7603
+ * }
7604
+ *
7605
+ * // Delete and verify from list
7606
+ * await composio.experimental.mcp.delete("mcp_12345");
7607
+ * const servers = await composio.experimental.mcp.list({});
7608
+ * const serverExists = servers.items.some(server => server.id === "mcp_12345");
7609
+ * console.log("Server still exists:", serverExists); // Should be false
7610
+ * ```
7611
+ *
7612
+ * @throws {ValidationError} When the server ID is invalid or server not found
7613
+ * @throws {Error} When the server cannot be deleted due to active connections or other constraints
7614
+ *
7615
+ * @warning This operation is irreversible. Once deleted, the MCP server configuration and all its associated data will be permanently removed.
7616
+ */
7617
+ async delete(serverId, requestOptions) {
7618
+ return withCancellation(() => this.client.mcp.delete(serverId, requestOptions), requestOptions?.signal);
7619
+ }
7620
+ /**
7621
+ * Update an existing MCP server configuration with new settings
7622
+ * @param {string} serverId - The unique identifier of the MCP server to update
7623
+ * @param {Object} config - Update configuration parameters
7624
+ * @param {string} [config.name] - New name for the MCP server
7625
+ * @param {Array} [config.toolkits] - Updated toolkit configurations
7626
+ * @param {string} [config.toolkits[].toolkit] - Toolkit identifier (e.g., "github", "slack")
7627
+ * @param {string} [config.toolkits[].authConfigId] - Auth configuration ID for the toolkit
7628
+ * @param {string[]} [config.toolkits[].allowedTools] - Specific tools to enable for this toolkit
7629
+ * @param {boolean} [config.manuallyManageConnections] - Whether to manually manage account connections
7630
+ * @returns {Promise<MCPItem>} Updated MCP server configuration with all details
7631
+ *
7632
+ * @example
7633
+ * ```typescript
7634
+ * // Update server name only
7635
+ * const updatedServer = await composio.experimental.mcp.update("mcp_12345", {
7636
+ * name: "My Updated MCP Server"
7637
+ * });
7638
+ *
7639
+ * // Update toolkits and tools
7640
+ * const serverWithNewTools = await composio.experimental.mcp.update("mcp_12345", {
7641
+ * toolkits: [
7642
+ * {
7643
+ * toolkit: "github",
7644
+ * authConfigId: "auth_abc123",
7645
+ * allowedTools: ["GITHUB_CREATE_ISSUE", "GITHUB_LIST_REPOS"]
7646
+ * },
7647
+ * {
7648
+ * toolkit: "slack",
7649
+ * authConfigId: "auth_xyz789",
7650
+ * allowedTools: ["SLACK_SEND_MESSAGE", "SLACK_LIST_CHANNELS"]
7651
+ * }
7652
+ * ]
7653
+ * });
7654
+ *
7655
+ * // Update connection management setting
7656
+ * const serverWithManualAuth = await composio.experimental.mcp.update("mcp_12345", {
7657
+ * name: "Manual Auth Server",
7658
+ * manuallyManageConnections: true
7659
+ * });
7660
+ *
7661
+ * // Complete update example
7662
+ * const fullyUpdatedServer = await composio.experimental.mcp.update("mcp_12345", {
7663
+ * name: "Production MCP Server",
7664
+ * toolkits: [
7665
+ * {
7666
+ * toolkit: "gmail",
7667
+ * authConfigId: "auth_gmail_prod",
7668
+ * }
7669
+ * ],
7670
+ * allowedTools: ["GMAIL_SEND_EMAIL", "GMAIL_FETCH_EMAILS"]
7671
+ * manuallyManageConnections: false
7672
+ * });
7673
+ *
7674
+ * console.log("Updated server:", fullyUpdatedServer.name);
7675
+ * console.log("New tools:", fullyUpdatedServer.allowedTools);
7676
+ * ```
7677
+ *
7678
+ * @throws {ValidationError} When the update parameters are invalid or malformed
7679
+ * @throws {Error} When the server ID doesn't exist or update fails
7680
+ *
7681
+ * @note Only provided fields will be updated. Omitted fields will retain their current values.
7682
+ * @note When updating toolkits, the entire toolkit configuration is replaced, not merged.
7683
+ */
7684
+ async update(serverId, config, requestOptions) {
7685
+ const { data: params, error } = MCPUpdateParamsSchema.safeParse(config);
7686
+ if (error) throw new ValidationError("Failed to validate update params", { cause: error });
7687
+ const toolkits = [];
7688
+ const auth_config_ids = [];
7689
+ params.toolkits?.forEach((toolkit) => {
7690
+ if (typeof toolkit === "string") toolkits.push(toolkit);
7691
+ else {
7692
+ if (toolkit.toolkit) toolkits.push(toolkit.toolkit);
7693
+ if (toolkit.authConfigId) auth_config_ids.push(toolkit.authConfigId);
7694
+ }
7695
+ });
7696
+ const updateBody = {
7697
+ ...params.name !== void 0 ? { name: params.name } : {},
7698
+ ...params.toolkits !== void 0 ? {
7699
+ toolkits,
7700
+ auth_config_ids
7701
+ } : {},
7702
+ ...params.allowedTools !== void 0 ? { allowed_tools: params.allowedTools } : {},
7703
+ ...params.manuallyManageConnections !== void 0 ? { managed_auth_via_composio: !params.manuallyManageConnections } : {}
7890
7704
  };
7705
+ return transformMCPItemResponse(await withCancellation(() => this.client.mcp.update(serverId, updateBody, requestOptions), requestOptions?.signal));
7891
7706
  }
7892
7707
  /**
7893
- * List the MCP servers with optional filtering and pagination
7894
- * @param {Object} options - Filtering and pagination options
7895
- * @param {number} [options.page=1] - Page number for pagination (1-based)
7896
- * @param {number} [options.limit=10] - Maximum number of items to return per page
7897
- * @param {string[]} [options.toolkits=[]] - Array of toolkit names to filter by
7898
- * @param {string[]} [options.authConfigs=[]] - Array of auth configuration IDs to filter by
7899
- * @param {string} [options.name] - Filter by MCP server name (partial match)
7900
- * @returns {Promise<MCPListResponse>} Paginated list of MCP servers with metadata
7708
+ * Get server URLs for an existing MCP server.
7709
+ * The response is wrapped according to the provider's specifications.
7901
7710
  *
7902
7711
  * @example
7903
7712
  * ```typescript
7904
- * // List all MCP servers
7905
- * const allServers = await composio.experimental.mcp.list({});
7906
- *
7907
- * // List with pagination
7908
- * const pagedServers = await composio.experimental.mcp.list({
7909
- * page: 2,
7910
- * limit: 5
7911
- * });
7912
- *
7913
- * // Filter by toolkit
7914
- * const githubServers = await composio.experimental.mcp.list({
7915
- * toolkits: ['github', 'slack']
7916
- * });
7713
+ * import { Composio } from "@composio/code";
7917
7714
  *
7918
- * // Filter by name
7919
- * const namedServers = await composio.experimental.mcp.list({
7920
- * name: 'personal'
7921
- * });
7715
+ * const composio = new Composio();
7716
+ * const mcp = await composio.experimental.mcp.generate("default", "<mcp_config_id>");
7922
7717
  * ```
7718
+ *
7719
+ * @param userId {string} external user id from your database for whom you want the server for
7720
+ * @param mcpConfigId {string} config id of the MCPConfig for which you want to create a server for
7721
+ * @param options {object} additional options
7722
+ * @param options.isChatAuth {boolean} Authenticate the users via chat when they use the MCP Server
7923
7723
  */
7924
- async list(options, requestOptions) {
7925
- const { data: params, error } = MCPListParamsSchema.safeParse(options);
7926
- if (error) throw new ValidationError("Failed to validate list options", { cause: error });
7927
- const listParams = {
7928
- page_no: params.page,
7929
- limit: params.limit,
7930
- toolkits: params.toolkits?.length > 0 ? params.toolkits.join(",") : void 0,
7931
- auth_config_ids: params.authConfigs?.length > 0 ? params.authConfigs.join(",") : void 0,
7932
- name: params.name
7724
+ async generate(userId, mcpConfigId, options, requestOptions) {
7725
+ const server = await withCancellation(() => this.client.mcp.retrieve(mcpConfigId, requestOptions), requestOptions?.signal);
7726
+ const params = MCPGetInstanceParamsSchema.safeParse(options ?? { manuallyManageConnections: false });
7727
+ if (params.error) throw new ValidationError("Invalid params passed for Get Instance Params", { cause: params.error });
7728
+ const urlBody = {
7729
+ mcp_server_id: mcpConfigId,
7730
+ user_ids: [userId],
7731
+ managed_auth_by_composio: options?.manuallyManageConnections ? false : true
7933
7732
  };
7934
- const listResponse = await withCancellation(() => this.client.mcp.list(listParams, requestOptions), requestOptions?.signal);
7935
- return transform(listResponse).with(MCPListResponseSchema).using((raw) => ({
7936
- currentPage: raw.current_page,
7937
- totalPages: raw.total_pages,
7938
- items: raw.items.map((item) => ({
7939
- name: item.name,
7940
- allowedTools: item.allowed_tools,
7941
- id: item.id,
7942
- authConfigIds: item.auth_config_ids,
7943
- commands: item.commands,
7944
- MCPUrl: item.mcp_url,
7945
- toolkitIcons: item.toolkit_icons,
7946
- serverInstanceCount: item.server_instance_count,
7947
- toolkits: item.toolkits
7948
- }))
7949
- }));
7733
+ if (urlBody.managed_auth_by_composio && !_managedAuthDeprecationWarned) {
7734
+ _managedAuthDeprecationWarned = true;
7735
+ logger.warn(MANAGED_AUTH_DEPRECATION);
7736
+ }
7737
+ const userIdsURL = (await withCancellation(() => this.client.withOptions({ logLevel: "error" }).mcp.generate.url(urlBody, requestOptions), requestOptions?.signal)).user_ids_url[0];
7738
+ const serverInstance = MCPServerInstanceSchema.safeParse({
7739
+ id: server.id,
7740
+ name: server.name,
7741
+ type: "streamable_http",
7742
+ url: userIdsURL,
7743
+ userId,
7744
+ allowedTools: server.allowed_tools,
7745
+ authConfigs: server.auth_config_ids
7746
+ });
7747
+ if (serverInstance.error) throw new ValidationError("Failed to parse MCP server instance", { cause: serverInstance.error });
7748
+ return serverInstance.data;
7749
+ }
7750
+ };
7751
+
7752
+ //#endregion
7753
+ //#region src/types/logs.types.ts
7754
+ /**
7755
+ * Fields a tool-execution log search can filter on.
7756
+ */
7757
+ const LogSearchFilterFieldSchema = z$1.enum([
7758
+ "tool_slug",
7759
+ "toolkit_slug",
7760
+ "connected_account_id",
7761
+ "auth_config_id",
7762
+ "status",
7763
+ "user_id",
7764
+ "session_id",
7765
+ "sandbox_id",
7766
+ "request_id",
7767
+ "log_id"
7768
+ ]);
7769
+ const LogSearchFilterOperatorSchema = z$1.enum([
7770
+ "==",
7771
+ "!=",
7772
+ "contains",
7773
+ "not_contains"
7774
+ ]);
7775
+ const LogSearchFilterSchema = z$1.object({
7776
+ field: LogSearchFilterFieldSchema,
7777
+ operator: LogSearchFilterOperatorSchema,
7778
+ value: z$1.string()
7779
+ });
7780
+ const LogSearchTimeRangeSchema = z$1.object({
7781
+ /** Start time in epoch milliseconds (inclusive). */
7782
+ from: z$1.number(),
7783
+ /** End time in epoch milliseconds. */
7784
+ to: z$1.number()
7785
+ });
7786
+ /**
7787
+ * Params for `composio.logs.search()`.
7788
+ */
7789
+ const LogSearchParamsSchema = z$1.object({
7790
+ limit: z$1.number().optional(),
7791
+ cursor: z$1.string().nullable().optional(),
7792
+ filters: z$1.array(LogSearchFilterSchema).optional(),
7793
+ timeRange: LogSearchTimeRangeSchema.optional()
7794
+ });
7795
+ const ToolExecutionLogStatusSchema = z$1.enum(["success", "failed"]);
7796
+ const ToolExecutionLogLevelSchema = z$1.enum([
7797
+ "info",
7798
+ "error",
7799
+ "warn"
7800
+ ]);
7801
+ const ToolExecutionLogParentSchema = z$1.object({
7802
+ logId: z$1.string(),
7803
+ toolSlug: z$1.string()
7804
+ }).nullable();
7805
+ /** Tool log metadata, including the optional exact USD Instant charge. */
7806
+ const ToolExecutionLogMetadataSchema = z$1.object({ instant_charge: z$1.string().optional() }).catchall(z$1.unknown());
7807
+ /**
7808
+ * A tool-execution log entry as returned by `composio.logs.search()`.
7809
+ */
7810
+ const ToolExecutionLogSchema = z$1.object({
7811
+ id: z$1.string(),
7812
+ /** ISO 8601 timestamp. */
7813
+ timestamp: z$1.string(),
7814
+ /** Log event type, e.g. `tool.execution`. */
7815
+ type: z$1.string(),
7816
+ status: ToolExecutionLogStatusSchema,
7817
+ level: ToolExecutionLogLevelSchema,
7818
+ message: z$1.string().optional(),
7819
+ metadata: ToolExecutionLogMetadataSchema,
7820
+ metrics: z$1.record(z$1.string(), z$1.unknown()),
7821
+ parent: ToolExecutionLogParentSchema
7822
+ });
7823
+ const LogSearchResponseSchema = z$1.object({
7824
+ logs: z$1.array(ToolExecutionLogSchema),
7825
+ nextCursor: z$1.string().nullable()
7826
+ });
7827
+ /**
7828
+ * A single tool-execution log with its full detail, as returned by
7829
+ * `composio.logs.get()`.
7830
+ */
7831
+ const ToolExecutionLogDetailSchema = ToolExecutionLogSchema.extend({
7832
+ timings: z$1.object({
7833
+ /** Epoch milliseconds. */
7834
+ startTime: z$1.number(),
7835
+ /** Epoch milliseconds. */
7836
+ endTime: z$1.number()
7837
+ }).optional(),
7838
+ context: z$1.object({
7839
+ sessionId: z$1.string().optional(),
7840
+ traceId: z$1.string().optional(),
7841
+ requestId: z$1.string().optional()
7842
+ }),
7843
+ source: z$1.object({
7844
+ host: z$1.string().optional(),
7845
+ framework: z$1.string().optional(),
7846
+ language: z$1.string().optional()
7847
+ }),
7848
+ data: z$1.record(z$1.string(), z$1.unknown())
7849
+ });
7850
+
7851
+ //#endregion
7852
+ //#region src/utils/transformers/logs.ts
7853
+ const transformLogSearchParams = (params) => ({
7854
+ limit: params.limit,
7855
+ cursor: params.cursor,
7856
+ filters: params.filters,
7857
+ time_range: params.timeRange
7858
+ });
7859
+ const transformToolExecutionLog = (response) => {
7860
+ return transform(response).with(ToolExecutionLogSchema).using((response) => ({
7861
+ id: response.id,
7862
+ timestamp: response.timestamp,
7863
+ type: response.type,
7864
+ status: response.status,
7865
+ level: response.level,
7866
+ message: response.message,
7867
+ metadata: ToolExecutionLogMetadataSchema.parse(response.metadata),
7868
+ metrics: response.metrics,
7869
+ parent: response.parent ? {
7870
+ logId: response.parent.log_id,
7871
+ toolSlug: response.parent.tool_slug
7872
+ } : null
7873
+ }));
7874
+ };
7875
+ const transformLogSearchResponse = (response) => {
7876
+ return transform(response).with(LogSearchResponseSchema).using((response) => ({
7877
+ logs: response.logs.map(transformToolExecutionLog),
7878
+ nextCursor: response.next_cursor
7879
+ }));
7880
+ };
7881
+ const transformToolExecutionLogDetail = (response) => {
7882
+ return transform(response).with(ToolExecutionLogDetailSchema).using((response) => ({
7883
+ id: response.id,
7884
+ timestamp: response.timestamp,
7885
+ type: response.type,
7886
+ status: response.status,
7887
+ level: response.level,
7888
+ message: response.message,
7889
+ metadata: ToolExecutionLogMetadataSchema.parse(response.metadata),
7890
+ metrics: response.metrics,
7891
+ parent: response.parent ? {
7892
+ logId: response.parent.log_id,
7893
+ toolSlug: response.parent.tool_slug
7894
+ } : null,
7895
+ timings: response.timings ? {
7896
+ startTime: response.timings.start_time,
7897
+ endTime: response.timings.end_time
7898
+ } : void 0,
7899
+ context: {
7900
+ sessionId: response.context.session_id,
7901
+ traceId: response.context.trace_id,
7902
+ requestId: response.context.request_id
7903
+ },
7904
+ source: {
7905
+ host: response.source.host,
7906
+ framework: response.source.framework,
7907
+ language: response.source.language
7908
+ },
7909
+ data: response.data
7910
+ }));
7911
+ };
7912
+
7913
+ //#endregion
7914
+ //#region src/models/Logs.ts
7915
+ /**
7916
+ * `composio.logs` — tool-execution logs.
7917
+ *
7918
+ * @example
7919
+ * ```typescript
7920
+ * const { logs, nextCursor } = await composio.logs.search({
7921
+ * filters: [{ field: 'toolkit_slug', operator: '==', value: 'github' }],
7922
+ * limit: 20,
7923
+ * });
7924
+ * const detail = await composio.logs.get(logs[0].id);
7925
+ * ```
7926
+ */
7927
+ var Logs = class {
7928
+ client;
7929
+ constructor(client) {
7930
+ this.client = client;
7931
+ telemetry.instrument(this, "Logs");
7950
7932
  }
7951
7933
  /**
7952
- * Retrieve detailed information about a specific MCP server by its ID
7953
- * @param {string} serverId - The unique identifier of the MCP server to retrieve
7954
- * @returns {Promise<MCPItem>} Complete MCP server details including configuration, tools, and metadata
7934
+ * Search tool-execution logs with filters, a time range and cursor
7935
+ * pagination.
7936
+ *
7937
+ * @param {LogSearchParams} [params] - Filters, `timeRange`, `limit` and `cursor`
7938
+ * @returns {Promise<LogSearchResponse>} Matching logs and the next cursor. Charged calls include `metadata.instant_charge` as an exact USD string.
7939
+ * @throws {ValidationError} If the params fail validation
7955
7940
  *
7956
7941
  * @example
7957
7942
  * ```typescript
7958
- * // Get a specific MCP server by ID
7959
- * const server = await composio.experimental.mcp.get("mcp_12345");
7960
- *
7961
- * console.log(server.name); // "My Personal MCP Server"
7962
- * console.log(server.allowedTools); // ["GITHUB_CREATE_ISSUE", "SLACK_SEND_MESSAGE"]
7963
- * console.log(server.toolkits); // ["github", "slack"]
7964
- * console.log(server.serverInstanceCount); // 3
7965
- *
7966
- * // Access setup commands for different clients
7967
- * console.log(server.commands.claude); // Claude setup command
7968
- * console.log(server.commands.cursor); // Cursor setup command
7969
- * console.log(server.commands.windsurf); // Windsurf setup command
7970
- *
7971
- * // Use the MCP URL for direct connections
7972
- * const mcpUrl = server.MCPUrl;
7943
+ * const { logs } = await composio.logs.search({
7944
+ * filters: [
7945
+ * { field: 'status', operator: '==', value: 'failed' },
7946
+ * { field: 'user_id', operator: '==', value: 'user_123' },
7947
+ * ],
7948
+ * timeRange: { from: Date.now() - 24 * 60 * 60 * 1000, to: Date.now() },
7949
+ * });
7973
7950
  * ```
7974
- *
7975
- * @throws {ValidationError} When the server ID is invalid or server not found
7976
7951
  */
7977
- async get(serverId, requestOptions) {
7978
- return transformMCPItemResponse(await withCancellation(() => this.client.mcp.retrieve(serverId, requestOptions), requestOptions?.signal));
7952
+ async search(params, requestOptions) {
7953
+ const parsedParams = LogSearchParamsSchema.safeParse(params ?? {});
7954
+ if (!parsedParams.success) throw new ValidationError("Failed to parse log search params", { cause: parsedParams.error });
7955
+ const body = transformLogSearchParams(parsedParams.data);
7956
+ const result = await withCancellation(() => this.client.logs.createToolExecution(body, requestOptions), requestOptions?.signal);
7957
+ return transformLogSearchResponse(result);
7979
7958
  }
7980
7959
  /**
7981
- * Delete an MCP server configuration permanently
7982
- * @param {string} serverId - The unique identifier of the MCP server to delete
7983
- * @returns {Promise<{id: string; deleted: boolean}>} Confirmation object with server ID and deletion status
7960
+ * Retrieve one tool-execution log with its full detail (timings, context,
7961
+ * source and raw `data`).
7962
+ *
7963
+ * @param {string} id - The log id
7964
+ * @returns {Promise<ToolExecutionLogDetail>} The log detail, with an optional exact USD charge in `metadata.instant_charge`
7984
7965
  *
7985
7966
  * @example
7986
7967
  * ```typescript
7987
- * // Delete an MCP server by ID
7988
- * const result = await composio.experimental.mcp.delete("mcp_12345");
7989
- *
7990
- * if (result.deleted) {
7991
- * console.log(`Server ${result.id} has been successfully deleted`);
7992
- * } else {
7993
- * console.log(`Failed to delete server ${result.id}`);
7994
- * }
7995
- *
7996
- * // Example with error handling
7997
- * try {
7998
- * const result = await composio.experimental.mcp.delete("mcp_12345");
7999
- * console.log("Deletion successful:", result);
8000
- * } catch (error) {
8001
- * console.error("Failed to delete MCP server:", error.message);
8002
- * }
8003
- *
8004
- * // Delete and verify from list
8005
- * await composio.experimental.mcp.delete("mcp_12345");
8006
- * const servers = await composio.experimental.mcp.list({});
8007
- * const serverExists = servers.items.some(server => server.id === "mcp_12345");
8008
- * console.log("Server still exists:", serverExists); // Should be false
7968
+ * const log = await composio.logs.get('log_abc123');
7969
+ * console.log(log.status, log.timings?.endTime);
8009
7970
  * ```
8010
- *
8011
- * @throws {ValidationError} When the server ID is invalid or server not found
8012
- * @throws {Error} When the server cannot be deleted due to active connections or other constraints
8013
- *
8014
- * @warning This operation is irreversible. Once deleted, the MCP server configuration and all its associated data will be permanently removed.
8015
7971
  */
8016
- async delete(serverId, requestOptions) {
8017
- return withCancellation(() => this.client.mcp.delete(serverId, requestOptions), requestOptions?.signal);
7972
+ async get(id, requestOptions) {
7973
+ const result = await withCancellation(() => this.client.logs.retrieveToolExecution(id, requestOptions), requestOptions?.signal);
7974
+ return transformToolExecutionLogDetail(result);
8018
7975
  }
8019
- /**
8020
- * Update an existing MCP server configuration with new settings
8021
- * @param {string} serverId - The unique identifier of the MCP server to update
8022
- * @param {Object} config - Update configuration parameters
8023
- * @param {string} [config.name] - New name for the MCP server
8024
- * @param {Array} [config.toolkits] - Updated toolkit configurations
8025
- * @param {string} [config.toolkits[].toolkit] - Toolkit identifier (e.g., "github", "slack")
8026
- * @param {string} [config.toolkits[].authConfigId] - Auth configuration ID for the toolkit
8027
- * @param {string[]} [config.toolkits[].allowedTools] - Specific tools to enable for this toolkit
8028
- * @param {boolean} [config.manuallyManageConnections] - Whether to manually manage account connections
8029
- * @returns {Promise<MCPItem>} Updated MCP server configuration with all details
8030
- *
8031
- * @example
8032
- * ```typescript
8033
- * // Update server name only
8034
- * const updatedServer = await composio.experimental.mcp.update("mcp_12345", {
8035
- * name: "My Updated MCP Server"
8036
- * });
8037
- *
8038
- * // Update toolkits and tools
8039
- * const serverWithNewTools = await composio.experimental.mcp.update("mcp_12345", {
8040
- * toolkits: [
8041
- * {
8042
- * toolkit: "github",
8043
- * authConfigId: "auth_abc123",
8044
- * allowedTools: ["GITHUB_CREATE_ISSUE", "GITHUB_LIST_REPOS"]
8045
- * },
8046
- * {
8047
- * toolkit: "slack",
8048
- * authConfigId: "auth_xyz789",
8049
- * allowedTools: ["SLACK_SEND_MESSAGE", "SLACK_LIST_CHANNELS"]
8050
- * }
8051
- * ]
8052
- * });
8053
- *
8054
- * // Update connection management setting
8055
- * const serverWithManualAuth = await composio.experimental.mcp.update("mcp_12345", {
8056
- * name: "Manual Auth Server",
8057
- * manuallyManageConnections: true
8058
- * });
8059
- *
8060
- * // Complete update example
8061
- * const fullyUpdatedServer = await composio.experimental.mcp.update("mcp_12345", {
8062
- * name: "Production MCP Server",
8063
- * toolkits: [
8064
- * {
8065
- * toolkit: "gmail",
8066
- * authConfigId: "auth_gmail_prod",
8067
- * }
8068
- * ],
8069
- * allowedTools: ["GMAIL_SEND_EMAIL", "GMAIL_FETCH_EMAILS"]
8070
- * manuallyManageConnections: false
8071
- * });
8072
- *
8073
- * console.log("Updated server:", fullyUpdatedServer.name);
8074
- * console.log("New tools:", fullyUpdatedServer.allowedTools);
8075
- * ```
8076
- *
8077
- * @throws {ValidationError} When the update parameters are invalid or malformed
8078
- * @throws {Error} When the server ID doesn't exist or update fails
8079
- *
8080
- * @note Only provided fields will be updated. Omitted fields will retain their current values.
8081
- * @note When updating toolkits, the entire toolkit configuration is replaced, not merged.
7976
+ };
7977
+
7978
+ //#endregion
7979
+ //#region src/lib/sessionConfigConflict.ts
7980
+ const SESSION_CONFIG_CONFLICT_MARKER = "sessionConfigConflict";
7981
+ /**
7982
+ * Adds the issue raised when a saved Session config (`experimental.sessionConfigId`)
7983
+ * is combined with inline access fields. `fields` lists every conflicting
7984
+ * field that was provided; nothing is added when it is empty.
7985
+ */
7986
+ const addSessionConfigConflictIssue = (ctx, fields) => {
7987
+ if (fields.length === 0) return;
7988
+ ctx.addIssue({
7989
+ code: z$1.ZodIssueCode.custom,
7990
+ message: `experimental.sessionConfigId cannot be combined with ${fields.join(", ")}. A saved Session config sets the session's toolkit, tool and tag access; remove ${fields.length === 1 ? "that field" : "those fields"} or sessionConfigId`,
7991
+ path: ["experimental", "sessionConfigId"],
7992
+ params: { [SESSION_CONFIG_CONFLICT_MARKER]: true }
7993
+ });
7994
+ };
7995
+ /**
7996
+ * Parses session create or update input. A saved Session config combined with
7997
+ * inline access fields throws `ValidationError`; any other failure rethrows the
7998
+ * original `ZodError`, as `schema.parse()` would.
7999
+ */
8000
+ const parseSessionConfigInput = (schema, input) => {
8001
+ const result = schema.safeParse(input);
8002
+ if (result.success) return result.data;
8003
+ if (result.error.issues.some((issue) => issue.code === z$1.ZodIssueCode.custom && issue.params?.[SESSION_CONFIG_CONFLICT_MARKER])) throw new ValidationError("Invalid session config", { cause: result.error });
8004
+ throw result.error;
8005
+ };
8006
+
8007
+ //#endregion
8008
+ //#region src/types/toolRouter.types.ts
8009
+ const SessionPreset = { DIRECT_TOOLS: "direct_tools" };
8010
+ const MCPServerTypeSchema = z.enum(["http", "sse"]);
8011
+ /**
8012
+ * Sandbox compute tier for the session sandbox.
8013
+ *
8014
+ * | Tier | vCPU | RAM |
8015
+ * | -------- | ---- | ----- |
8016
+ * | standard | 1 | 1 GB |
8017
+ * | medium | 2 | 2 GB |
8018
+ * | large | 4 | 4 GB |
8019
+ * | xlarge | 8 | 8 GB |
8020
+ *
8021
+ * Defaults to `standard` server-side when omitted.
8022
+ */
8023
+ const SandboxSizeSchema = z.enum([
8024
+ "standard",
8025
+ "medium",
8026
+ "large",
8027
+ "xlarge"
8028
+ ]);
8029
+ const ToolRouterSandboxConfigSchema = z.object({
8030
+ enable: z.boolean().default(true).describe("Whether to enable the sandbox entirely. Defaults to true. When set to false, no code execution tools (COMPOSIO_REMOTE_WORKBENCH, COMPOSIO_REMOTE_BASH_TOOL) are available in the session."),
8031
+ enableProxyExecution: z.boolean().optional().describe("Whether to enable proxy execution in the session sandbox"),
8032
+ autoOffloadThreshold: z.number().optional().describe("The auto offload threshold in characters for tool execution to move into the sandbox"),
8033
+ sandboxSize: SandboxSizeSchema.optional().describe("Sandbox compute tier. One of \"standard\" (1 vCPU / 1 GB), \"medium\" (2 vCPU / 2 GB), \"large\" (4 vCPU / 4 GB), or \"xlarge\" (8 vCPU / 8 GB). Defaults to \"standard\" server-side. Changing this on an existing session recreates the session sandbox on next access; the in-memory FS is lost, but /mnt/files/ persists.")
8034
+ });
8035
+ const ToolRouterConfigManageConnectionsSchema = z.object({
8036
+ enable: z.boolean().default(true).optional().describe("Whether to use tools to manage connections in the tool router session. Defaults to true, if set to false, you need to manage connections manually"),
8037
+ callbackUrl: z.string().optional().describe("The callback uri to use in the tool router session"),
8038
+ waitForConnections: z.boolean().optional().describe("Whether to wait for users to finish authenticating connections before proceeding to the next step. Defaults to false, if set to true, a wait for connections tool call will happen and finish when the connections are ready")
8039
+ }).strict();
8040
+ const ToolRouterToolkitsParamSchema = z.array(z.string()).describe("List of toolkits to enable in the tool router session");
8041
+ const ToolRouterToolkitsDisabledConfigSchema = z.object({ disable: ToolRouterToolkitsParamSchema.describe("List of toolkits to disable in the tool router session") }).strict();
8042
+ const ToolRouterToolkitsEnabledConfigSchema = z.object({ enable: ToolRouterToolkitsParamSchema.describe("List of toolkits to enable in the tool router session") }).strict();
8043
+ /**
8044
+ * Toolkits whose tools need the user's approval before they run. A call that
8045
+ * needs approval doesn't run: `session.execute()` throws
8046
+ * `ComposioToolInputRequiredError` with the question to show the user.
8047
+ * @experimental
8048
+ */
8049
+ const ToolRouterToolkitsRequireApprovalSchema = ToolRouterToolkitsParamSchema.describe("Experimental. Toolkits whose tools need the user approval before they run");
8050
+ /** Session toolkit policy: a list to enable, an enable/disable object, or only an approval list. */
8051
+ const ToolRouterSessionToolkitsSchema = z.union([
8052
+ ToolRouterToolkitsParamSchema,
8053
+ ToolRouterToolkitsDisabledConfigSchema.extend({ requireApproval: ToolRouterToolkitsRequireApprovalSchema.optional() }).strict(),
8054
+ ToolRouterToolkitsEnabledConfigSchema.extend({ requireApproval: ToolRouterToolkitsRequireApprovalSchema.optional() }).strict(),
8055
+ z.object({ requireApproval: ToolRouterToolkitsRequireApprovalSchema }).strict()
8056
+ ]);
8057
+ /**
8058
+ * What happens to a call that needs the user's approval when the session's MCP
8059
+ * client can't ask the user.
8060
+ * @experimental
8061
+ */
8062
+ const ToolRouterNoElicitationSupportFallbackSchema = z.enum(["deny", "allow"]).describe("Experimental. What happens to a call that needs approval when the MCP client cannot ask the user");
8063
+ /** Experimental Instant usage policy for a Session. */
8064
+ const ToolRouterInstantSchema = z.union([z.literal(false), z.object({
8065
+ toolkits: z.union([ToolRouterToolkitsEnabledConfigSchema, ToolRouterToolkitsDisabledConfigSchema]).optional(),
8066
+ tools: z.record(z.string(), z.union([z.object({ enable: z.array(z.string()) }).strict(), z.object({ disable: z.array(z.string()) }).strict()])).optional(),
8067
+ /**
8068
+ * Return the actual Instant charge in Session tool responses. Controls
8069
+ * visibility only; on update, any policy object still re-enables Instant
8070
+ * usage on a Session set to `false`.
8082
8071
  */
8083
- async update(serverId, config, requestOptions) {
8084
- const { data: params, error } = MCPUpdateParamsSchema.safeParse(config);
8085
- if (error) throw new ValidationError("Failed to validate update params", { cause: error });
8086
- const toolkits = [];
8087
- const auth_config_ids = [];
8088
- params.toolkits?.forEach((toolkit) => {
8089
- if (typeof toolkit === "string") toolkits.push(toolkit);
8090
- else {
8091
- if (toolkit.toolkit) toolkits.push(toolkit.toolkit);
8092
- if (toolkit.authConfigId) auth_config_ids.push(toolkit.authConfigId);
8093
- }
8094
- });
8095
- const updateBody = {
8096
- ...params.name !== void 0 ? { name: params.name } : {},
8097
- ...params.toolkits !== void 0 ? {
8098
- toolkits,
8099
- auth_config_ids
8100
- } : {},
8101
- ...params.allowedTools !== void 0 ? { allowed_tools: params.allowedTools } : {},
8102
- ...params.manuallyManageConnections !== void 0 ? { managed_auth_via_composio: !params.manuallyManageConnections } : {}
8103
- };
8104
- return transformMCPItemResponse(await withCancellation(() => this.client.mcp.update(serverId, updateBody, requestOptions), requestOptions?.signal));
8105
- }
8072
+ returnInstantCharge: z.boolean().optional(),
8106
8073
  /**
8107
- * Get server URLs for an existing MCP server.
8108
- * The response is wrapped according to the provider's specifications.
8109
- *
8110
- * @example
8111
- * ```typescript
8112
- * import { Composio } from "@composio/code";
8113
- *
8114
- * const composio = new Composio();
8115
- * const mcp = await composio.experimental.mcp.generate("default", "<mcp_config_id>");
8116
- * ```
8117
- *
8118
- * @param userId {string} external user id from your database for whom you want the server for
8119
- * @param mcpConfigId {string} config id of the MCPConfig for which you want to create a server for
8120
- * @param options {object} additional options
8121
- * @param options.isChatAuth {boolean} Authenticate the users via chat when they use the MCP Server
8074
+ * Experimental. Show each Instant tool's price in Session search
8075
+ * results, under `toolkitConnectionStatuses[].instantAccount.prices`.
8076
+ * Controls visibility only.
8122
8077
  */
8123
- async generate(userId, mcpConfigId, options, requestOptions) {
8124
- const server = await withCancellation(() => this.client.mcp.retrieve(mcpConfigId, requestOptions), requestOptions?.signal);
8125
- const params = MCPGetInstanceParamsSchema.safeParse(options ?? { manuallyManageConnections: false });
8126
- if (params.error) throw new ValidationError("Invalid params passed for Get Instance Params", { cause: params.error });
8127
- const urlBody = {
8128
- mcp_server_id: mcpConfigId,
8129
- user_ids: [userId],
8130
- managed_auth_by_composio: options?.manuallyManageConnections ? false : true
8131
- };
8132
- if (urlBody.managed_auth_by_composio && !_managedAuthDeprecationWarned) {
8133
- _managedAuthDeprecationWarned = true;
8134
- logger.warn(MANAGED_AUTH_DEPRECATION);
8135
- }
8136
- const userIdsURL = (await withCancellation(() => this.client.withOptions({ logLevel: "error" }).mcp.generate.url(urlBody, requestOptions), requestOptions?.signal)).user_ids_url[0];
8137
- const serverInstance = MCPServerInstanceSchema.safeParse({
8138
- id: server.id,
8139
- name: server.name,
8140
- type: "streamable_http",
8141
- url: userIdsURL,
8142
- userId,
8143
- allowedTools: server.allowed_tools,
8144
- authConfigs: server.auth_config_ids
8078
+ returnPricesInSearch: z.boolean().optional()
8079
+ }).strict()]);
8080
+ const ToolRouterManageConnectionsConfigSchema = z.object({
8081
+ enable: z.boolean().optional().describe("Whether to use tools to manage connections in the tool router session. Defaults to true, if set to false, you need to manage connections manually").default(true),
8082
+ callbackUrl: z.string().optional().describe("The callback url to use in the tool router session")
8083
+ });
8084
+ const ToolRouterTagsParamSchema = z.array(z.enum([
8085
+ "readOnlyHint",
8086
+ "createHint",
8087
+ "updateHint",
8088
+ "destructiveHint",
8089
+ "idempotentHint",
8090
+ "openWorldHint"
8091
+ ])).describe("The tags to filter the tools by");
8092
+ const ToolRouterTagsEnableDisableSchema = z.object({
8093
+ enable: ToolRouterTagsParamSchema.optional().describe("The tags to enable in the tool router session"),
8094
+ disable: ToolRouterTagsParamSchema.optional().describe("The tags to disable in the tool router session"),
8095
+ /**
8096
+ * Tools with any of these tags need the user's approval before they run.
8097
+ * @experimental
8098
+ */
8099
+ requireApproval: ToolRouterTagsParamSchema.optional().describe("Experimental. Tools with any of these tags need the user approval before they run")
8100
+ }).strict();
8101
+ const ToolRouterConfigTagsSchema = z.union([ToolRouterTagsParamSchema, ToolRouterTagsEnableDisableSchema]).describe("The tags to use in the tool router session");
8102
+ /**
8103
+ * Tools config - Configure tools per toolkit using toolkit slug as key
8104
+ * @example
8105
+ * ```typescript
8106
+ * {
8107
+ * gmail: {
8108
+ * enable: ['gmail_search', 'gmail_send']
8109
+ * },
8110
+ * slack: {
8111
+ * disable: ['slack_delete_message']
8112
+ * }
8113
+ * }
8114
+ * ```
8115
+ *
8116
+ * @example
8117
+ * ```typescript
8118
+ * {
8119
+ * gmail: ['gmail_search', 'gmail_send'],
8120
+ * slack: { tags: ['readOnlyHint'] }
8121
+ * }
8122
+ * ```
8123
+ */
8124
+ const ToolRouterToolsParamSchema = z.array(z.string()).describe("The tools to use in the tool router session");
8125
+ /**
8126
+ * Tools of the toolkit that need the user's approval before they run.
8127
+ * @experimental
8128
+ */
8129
+ const ToolRouterToolsRequireApprovalSchema = ToolRouterToolsParamSchema.describe("Experimental. Tools of this toolkit that need the user approval before they run");
8130
+ const ToolRouterConfigToolsSchema = z.union([
8131
+ ToolRouterToolsParamSchema,
8132
+ z.object({
8133
+ enable: ToolRouterToolsParamSchema.describe("The tools to enable in the tool router session"),
8134
+ requireApproval: ToolRouterToolsRequireApprovalSchema.optional()
8135
+ }).strict(),
8136
+ z.object({
8137
+ disable: ToolRouterToolsParamSchema.describe("The tools to disable in the tool router session"),
8138
+ requireApproval: ToolRouterToolsRequireApprovalSchema.optional()
8139
+ }).strict(),
8140
+ z.object({
8141
+ tags: ToolRouterConfigTagsSchema.describe("The tags to filter the tools by, this will override the global tags"),
8142
+ requireApproval: ToolRouterToolsRequireApprovalSchema.optional()
8143
+ }).strict(),
8144
+ z.object({ requireApproval: ToolRouterToolsRequireApprovalSchema }).strict()
8145
+ ]).superRefine((val, ctx) => {
8146
+ if (typeof val === "object" && !Array.isArray(val)) {
8147
+ const keys = Object.keys(val).filter((key) => key !== "requireApproval");
8148
+ if (keys.length > 1) ctx.addIssue({
8149
+ code: z.ZodIssueCode.custom,
8150
+ message: `Only one of 'enable', 'disable', or 'tags' can be specified, but found: ${keys.join(", ")}`,
8151
+ path: keys
8145
8152
  });
8146
- if (serverInstance.error) throw new ValidationError("Failed to parse MCP server instance", { cause: serverInstance.error });
8147
- return serverInstance.data;
8148
8153
  }
8154
+ });
8155
+ /**
8156
+ * Proxy execute settings for a session. `enable: true` exposes the
8157
+ * `COMPOSIO_PROXY_EXECUTE` meta tool and `enable: false` also turns off the
8158
+ * sandbox `proxy_execute()` helper. Leaving the block out keeps the meta tool
8159
+ * off while `sandbox.enableProxyExecution` controls the helper.
8160
+ */
8161
+ const ToolRouterProxyExecuteConfigSchema = z.object({ enable: z.boolean().describe("true exposes the COMPOSIO_PROXY_EXECUTE meta tool. false also turns off the sandbox proxy_execute() helper.") }).strict();
8162
+ /**
8163
+ * `proxyExecute` as accepted by `sessions.create()` and `session.update()`:
8164
+ * a boolean is shorthand for `{ enable: boolean }`.
8165
+ */
8166
+ const ToolRouterProxyExecuteSchema = z.union([z.boolean(), ToolRouterProxyExecuteConfigSchema]);
8167
+ /** Which tool calls a hook runs on: `'all'`, or only calls to the listed toolkits (including their proxy calls). */
8168
+ const ToolRouterHookAppliesToSchema = z.union([z.literal("all"), z.object({ toolkits: z.array(z.string()).describe("Toolkit slugs") }).strict()]);
8169
+ /** Blocks a call or result when it matches `condition`, a plain sentence describing what to block. */
8170
+ const ToolRouterHookConditionCheckHandlerSchema = z.object({
8171
+ type: z.literal("condition_check"),
8172
+ condition: z.string().describe("What to block, written as a plain sentence. For example: \"Sending email to anyone outside example.org\"."),
8173
+ action: z.literal("block")
8174
+ }).strict();
8175
+ /** A pre-defined check that blocks results with text that tries to give the agent instructions. */
8176
+ const ToolRouterHookPromptInjectionCheckHandlerSchema = z.object({
8177
+ type: z.literal("prompt_injection_check"),
8178
+ action: z.literal("block")
8179
+ }).strict();
8180
+ const toolRouterHookIdentityFields = {
8181
+ id: z.string().describe("Unique within the session. Shows up in results and logs."),
8182
+ name: z.string().optional().describe("A readable name. The agent sees it when this hook blocks a call."),
8183
+ appliesTo: ToolRouterHookAppliesToSchema
8184
+ };
8185
+ /**
8186
+ * A hook on a session's tool calls. A `before_execute` hook can block a call
8187
+ * before it runs; an `after_execute` hook can block its result before the
8188
+ * agent sees it.
8189
+ */
8190
+ const ToolRouterHookSchema = z.discriminatedUnion("type", [z.object({
8191
+ type: z.literal("before_execute"),
8192
+ ...toolRouterHookIdentityFields,
8193
+ handler: ToolRouterHookConditionCheckHandlerSchema
8194
+ }).strict(), z.object({
8195
+ type: z.literal("after_execute"),
8196
+ ...toolRouterHookIdentityFields,
8197
+ handler: z.discriminatedUnion("type", [ToolRouterHookConditionCheckHandlerSchema, ToolRouterHookPromptInjectionCheckHandlerSchema])
8198
+ }).strict()]);
8199
+ const ToolRouterCreateSessionConfigBaseSchema = z.object({
8200
+ sessionPreset: z.literal(SessionPreset.DIRECT_TOOLS).optional().describe("Shortcut to expose every tool allowed by the session filters directly in session.tools() and the MCP tool list. This disables meta tools by default (search, multi-execute, manage-connections, and workbench). Use when all tools are known upfront and helper/meta tools are not needed. Without this preset, ToolRouter uses its default configuration with meta tools enabled."),
8201
+ mcp: z.boolean().optional().describe("When true, the returned session surfaces its hosted MCP endpoint (`session.mcp.url` / `session.mcp.headers`) in the type, and an MCP URL that is not on the API base URL origin throws `ComposioMCPDestinationError` instead of leaving `session.mcp.headers` empty with a warning. The endpoint exists on every session at runtime regardless of this flag, but is only typed when `mcp: true` is passed. Default native tools (`session.tools()`) are unaffected. See https://docs.composio.dev/docs/sessions-via-mcp"),
8202
+ tools: z.record(z.string(), z.union([ToolRouterToolsParamSchema, ToolRouterConfigToolsSchema])).optional().describe("The tools to use in the tool router session"),
8203
+ tags: ToolRouterConfigTagsSchema.optional().describe("Global tags to filter the tools by"),
8204
+ toolkits: ToolRouterSessionToolkitsSchema.optional().describe("The toolkits to use in the tool router session"),
8205
+ instant: ToolRouterInstantSchema.optional().describe("Experimental Instant usage policy. Omission permits eligible tools when the project allows Instant usage; false disables it for this Session."),
8206
+ authConfigs: z.record(z.string(), z.string()).describe("The auth configs to use in the tool router session. The key is the toolkit slug, the value is the auth config id.").default({}),
8207
+ connectedAccounts: z.record(z.string(), z.union([z.string(), z.array(z.string())])).describe("The connected accounts to use in the tool router session. The key is the toolkit slug, the value is a connected account id or an array of ids. Only one account per toolkit is allowed when multi-account mode is disabled.").default({}),
8208
+ manageConnections: z.union([z.boolean(), ToolRouterConfigManageConnectionsSchema]).optional().default(true).describe("The config for the manage connections in the tool router session. Defaults to true, if set to false, you need to manage connections manually. If set to an object, you can configure the manage connections settings."),
8209
+ sandbox: ToolRouterSandboxConfigSchema.optional().describe("The sandbox config for this session. Prefer this over workbench."),
8210
+ workbench: ToolRouterSandboxConfigSchema.optional().describe("Deprecated alias for sandbox. Accepted for backwards compatibility."),
8211
+ multiAccount: z.object({
8212
+ enable: z.boolean().default(false).describe("When true, enables multi-account mode for this session. Defaults to false."),
8213
+ maxAccountsPerToolkit: z.number().int().min(2).max(10).optional().describe("Maximum number of connected accounts allowed per toolkit. Defaults to 5 when multi-account is enabled."),
8214
+ requireExplicitSelection: z.boolean().optional().describe("When true, require explicit account selection when multiple accounts are connected. When false (default), use the first/default account.")
8215
+ }).optional().describe("Multi-account configuration for this session"),
8216
+ proxyExecute: ToolRouterProxyExecuteSchema.optional().describe("Proxy execute configuration for this session; a boolean is shorthand for `{ enable }`. Rejected by the API when enable is false and sandbox.enableProxyExecution is true."),
8217
+ hooks: z.array(ToolRouterHookSchema).optional().describe("Hooks that run on this session's tool calls. A hook can block a call before it runs, or block its result before the agent sees it."),
8218
+ preload: z.object({ tools: z.union([z.array(z.string()), z.literal("all")]).optional().describe("Tool slugs to preload into session.tools() and the MCP tool list, or \"all\" to preload every app tool allowed by the session filters. \"all\" requires a positive filter such as toolkits, tools, or tags; the backend validates and caps the final tool set.") }).strict().optional().describe("Preload configuration for tools that should be exposed without search."),
8219
+ experimental: z.object({
8220
+ assistivePrompt: z.object({ userTimezone: z.string().optional().describe("IANA timezone identifier (e.g., \"America/New_York\", \"Europe/London\") for timezone-aware assistive prompts") }).optional().describe("Configuration for assistive prompt generation"),
8221
+ customTools: z.array(z.custom()).optional().describe("Custom tools to include in this session. Created via createCustomTool() from @composio/core/experimental."),
8222
+ customToolkits: z.array(z.custom()).optional().describe("Custom toolkits to include in this session. Created via createCustomToolkit() from @composio/core/experimental."),
8223
+ sessionConfigId: z.string().min(1).optional().describe("ID of a saved Session config (`sc_…`) to apply when the session is created. Cannot be combined with toolkits, tools, tags, customTools or customToolkits."),
8224
+ /**
8225
+ * What happens to a call that needs the user's approval when the
8226
+ * session's MCP client can't ask the user: `deny` (the default) or
8227
+ * `allow`.
8228
+ * @experimental
8229
+ */
8230
+ noElicitationSupportFallback: ToolRouterNoElicitationSupportFallbackSchema.optional()
8231
+ }).optional().describe("Experimental features configuration - not stable, may be modified or removed")
8232
+ }).partial().superRefine((config, ctx) => {
8233
+ if (config.experimental?.sessionConfigId !== void 0) addSessionConfigConflictIssue(ctx, [
8234
+ config.toolkits !== void 0 && "toolkits",
8235
+ config.tools !== void 0 && "tools",
8236
+ config.tags !== void 0 && "tags",
8237
+ config.hooks !== void 0 && "hooks",
8238
+ config.experimental.customTools !== void 0 && "experimental.customTools",
8239
+ config.experimental.customToolkits !== void 0 && "experimental.customToolkits"
8240
+ ].filter((field) => field !== false));
8241
+ if (config.sandbox !== void 0 && config.workbench !== void 0) ctx.addIssue({
8242
+ code: z.ZodIssueCode.custom,
8243
+ message: "Pass either sandbox or workbench, not both. workbench is a backwards-compatible alias for sandbox.",
8244
+ path: ["sandbox"]
8245
+ });
8246
+ }).describe("The config for the tool router session");
8247
+ const applyDirectToolsPresetDefaults = (value) => {
8248
+ if (!value || typeof value !== "object" || Array.isArray(value)) return value;
8249
+ const config = value;
8250
+ if (config.sessionPreset !== SessionPreset.DIRECT_TOOLS) return value;
8251
+ const hasSandboxConfig = config.sandbox !== void 0 || config.workbench !== void 0;
8252
+ return {
8253
+ ...config,
8254
+ manageConnections: config.manageConnections === void 0 ? false : config.manageConnections,
8255
+ ...hasSandboxConfig ? {} : { sandbox: { enable: false } },
8256
+ preload: config.preload === void 0 ? { tools: "all" } : config.preload
8257
+ };
8149
8258
  };
8150
-
8151
- //#endregion
8152
- //#region src/types/logs.types.ts
8259
+ const ToolRouterCreateSessionConfigSchema = z.preprocess(applyDirectToolsPresetDefaults, ToolRouterCreateSessionConfigBaseSchema).describe("The config for the tool router session");
8260
+ const ToolkitConnectionStateSchema = z.object({
8261
+ slug: z.string().describe("The slug of a toolkit"),
8262
+ name: z.string().describe("The name of a toolkit"),
8263
+ logo: z.string().optional().describe("The logo of a toolkit"),
8264
+ isNoAuth: z.boolean().default(false).describe("Whether the toolkit is no auth or not"),
8265
+ connection: z.object({
8266
+ isActive: z.boolean().describe("Whether the connection is active or not"),
8267
+ authConfig: z.object({
8268
+ id: z.string().describe("The id of the auth config"),
8269
+ mode: z.string().describe("The auth scheme used by the auth config"),
8270
+ isComposioManaged: z.boolean().describe("Whether the auth config is managed by Composio")
8271
+ }).nullish().describe("The auth config of a toolkit"),
8272
+ connectedAccount: z.object({
8273
+ id: z.string().describe("The id of the connected account"),
8274
+ status: z.string().describe("The status of the connected account")
8275
+ }).optional().describe("The connected account of a toolkit")
8276
+ }).optional().describe("The connection of a toolkit")
8277
+ }).describe("The connection state of a toolkit");
8278
+ const ToolkitConnectionsDetailsSchema = z.object({
8279
+ items: z.array(ToolkitConnectionStateSchema),
8280
+ cursor: z.string().optional(),
8281
+ totalPages: z.number()
8282
+ });
8283
+ const ToolRouterMCPServerConfigSchema = z.object({
8284
+ type: MCPServerTypeSchema,
8285
+ url: z.string(),
8286
+ headers: z.record(z.string(), z.string()).optional()
8287
+ });
8288
+ const ToolRouterToolkitsOptionsSchema = z.object({
8289
+ toolkits: z.array(z.string()).optional(),
8290
+ cursor: z.string().optional(),
8291
+ limit: z.number().optional(),
8292
+ isConnected: z.boolean().optional(),
8293
+ search: z.string().optional()
8294
+ });
8295
+ const ToolRouterSessionSearchResultReferenceWorkbenchSnippetSchema = z.object({
8296
+ code: z.string(),
8297
+ description: z.string()
8298
+ });
8299
+ const ToolRouterSessionSearchResultSchema = z.object({
8300
+ index: z.number(),
8301
+ useCase: z.string(),
8302
+ primaryToolSlugs: z.array(z.string()),
8303
+ relatedToolSlugs: z.array(z.string()),
8304
+ toolkits: z.array(z.string()),
8305
+ difficulty: z.string().optional(),
8306
+ error: z.string().nullable().optional(),
8307
+ executionGuidance: z.string().optional(),
8308
+ knownPitfalls: z.array(z.string()).optional(),
8309
+ memory: z.record(z.string(), z.array(z.string())).optional(),
8310
+ planId: z.string().optional(),
8311
+ recommendedPlanSteps: z.array(z.string()).optional(),
8312
+ referenceWorkbenchSnippets: z.array(ToolRouterSessionSearchResultReferenceWorkbenchSnippetSchema).optional()
8313
+ });
8314
+ const ToolRouterSessionSearchSessionSchema = z.object({
8315
+ id: z.string(),
8316
+ generateId: z.boolean(),
8317
+ instructions: z.string()
8318
+ });
8319
+ const ToolRouterSessionSearchTimeInfoSchema = z.object({
8320
+ currentTimeUtc: z.string(),
8321
+ currentTimeUtcEpochSeconds: z.number(),
8322
+ message: z.string()
8323
+ });
8324
+ const ToolRouterSessionSearchToolSchemasSchemaRefSchema = z.object({
8325
+ args: z.object({ toolSlugs: z.array(z.string()) }),
8326
+ message: z.string().optional(),
8327
+ tool: z.literal("COMPOSIO_GET_TOOL_SCHEMAS")
8328
+ });
8329
+ const ToolRouterSessionSearchToolSchemaSchema = z.object({
8330
+ toolSlug: z.string(),
8331
+ toolkit: z.string(),
8332
+ description: z.string().optional(),
8333
+ hasFullSchema: z.boolean().optional(),
8334
+ inputSchema: z.record(z.string(), z.unknown()).optional(),
8335
+ outputSchema: z.record(z.string(), z.unknown()).optional(),
8336
+ schemaRef: ToolRouterSessionSearchToolSchemasSchemaRefSchema.optional()
8337
+ });
8338
+ const ToolRouterSessionSearchToolkitConnectionStatusSchema = z.object({
8339
+ toolkit: z.string(),
8340
+ description: z.string(),
8341
+ hasActiveConnection: z.boolean(),
8342
+ statusMessage: z.string(),
8343
+ connectionDetails: z.record(z.string(), z.unknown()).optional(),
8344
+ currentUserInfo: z.record(z.string(), z.unknown()).optional(),
8345
+ /** Present when the toolkit runs on a Composio Instant account; only these tools run on it. */
8346
+ instantAccount: z.object({
8347
+ allowedToolSlugs: z.array(z.string()),
8348
+ /**
8349
+ * Price of each tool, keyed by tool slug. Present only when the Session
8350
+ * sets `instant.returnPricesInSearch`.
8351
+ */
8352
+ prices: z.record(z.string(), z.object({
8353
+ description: z.string().optional(),
8354
+ discount: z.string().nullable().optional()
8355
+ })).optional()
8356
+ }).optional()
8357
+ });
8358
+ const ToolRouterSessionSearchResponseSchema = z.object({
8359
+ success: z.boolean(),
8360
+ error: z.string().nullable(),
8361
+ results: z.array(ToolRouterSessionSearchResultSchema),
8362
+ toolSchemas: z.record(z.string(), ToolRouterSessionSearchToolSchemaSchema),
8363
+ toolkitConnectionStatuses: z.array(ToolRouterSessionSearchToolkitConnectionStatusSchema),
8364
+ nextStepsGuidance: z.array(z.string()),
8365
+ session: ToolRouterSessionSearchSessionSchema,
8366
+ timeInfo: ToolRouterSessionSearchTimeInfoSchema
8367
+ });
8153
8368
  /**
8154
- * Fields a tool-execution log search can filter on.
8369
+ * What one session hook decided about a call. `unavailable` means the hook
8370
+ * could not be evaluated (for example it timed out); it does not block the
8371
+ * call.
8155
8372
  */
8156
- const LogSearchFilterFieldSchema = z$1.enum([
8157
- "tool_slug",
8158
- "toolkit_slug",
8159
- "connected_account_id",
8160
- "auth_config_id",
8161
- "status",
8162
- "user_id",
8163
- "session_id",
8164
- "sandbox_id",
8165
- "request_id",
8166
- "log_id"
8167
- ]);
8168
- const LogSearchFilterOperatorSchema = z$1.enum([
8169
- "==",
8170
- "!=",
8171
- "contains",
8172
- "not_contains"
8173
- ]);
8174
- const LogSearchFilterSchema = z$1.object({
8175
- field: LogSearchFilterFieldSchema,
8176
- operator: LogSearchFilterOperatorSchema,
8177
- value: z$1.string()
8373
+ const ToolRouterHookResultSchema = z.discriminatedUnion("status", [z.object({
8374
+ id: z.string().describe("The hook id"),
8375
+ status: z.literal("evaluated"),
8376
+ outcome: z.enum(["continue", "block"]).describe("What the hook decided")
8377
+ }), z.object({
8378
+ id: z.string().describe("The hook id"),
8379
+ status: z.literal("unavailable")
8380
+ })]);
8381
+ /**
8382
+ * Why a session hook blocked a call. `request_blocked`: a `before_execute` hook
8383
+ * blocked it and the tool did not run. `response_blocked`: the tool ran and an
8384
+ * `after_execute` hook blocked its result.
8385
+ */
8386
+ const ToolRouterBlockReasonSchema = z.object({
8387
+ type: z.enum(["request_blocked", "response_blocked"]),
8388
+ hookId: z.string()
8178
8389
  });
8179
- const LogSearchTimeRangeSchema = z$1.object({
8180
- /** Start time in epoch milliseconds (inclusive). */
8181
- from: z$1.number(),
8182
- /** End time in epoch milliseconds. */
8183
- to: z$1.number()
8390
+ const ToolRouterSessionExecuteResponseSchema = z.object({
8391
+ data: z.record(z.string(), z.unknown()),
8392
+ error: z.string().nullable(),
8393
+ logId: z.string(),
8394
+ /**
8395
+ * Whether the tool ran and succeeded (`completed`), ran and failed
8396
+ * (`failed`), or was blocked by a session hook (`blocked`). A failed
8397
+ * execution can carry a `null` or empty `error`, so read this rather than
8398
+ * `error` to tell them apart. A blocked call has empty `data` and the
8399
+ * agent-facing message in `error`.
8400
+ */
8401
+ resultType: z.enum([
8402
+ "completed",
8403
+ "failed",
8404
+ "blocked"
8405
+ ]),
8406
+ /** Actual Instant usage charge when the Session opts into returning it. */
8407
+ instantCharge: z.unknown().optional(),
8408
+ /** Set when `resultType` is `blocked`: which hook blocked the call, and at which stage. */
8409
+ blockReason: ToolRouterBlockReasonSchema.optional(),
8410
+ /** Every session hook that applied to this call. Absent when none applied. */
8411
+ hookResults: z.array(ToolRouterHookResultSchema).optional()
8412
+ });
8413
+ const SessionProxyExecuteParamsSchema = z.object({
8414
+ /** The toolkit whose connected account to use for auth (e.g. 'gmail', 'github') */
8415
+ toolkit: z.string(),
8416
+ /** The API endpoint URL to call */
8417
+ endpoint: z.string(),
8418
+ /** HTTP method */
8419
+ method: z.enum([
8420
+ "GET",
8421
+ "POST",
8422
+ "PUT",
8423
+ "DELETE",
8424
+ "PATCH"
8425
+ ]),
8426
+ /** Request body (for POST/PUT/PATCH) */
8427
+ body: z.unknown().optional(),
8428
+ /** Query params or headers to include */
8429
+ parameters: z.array(z.object({
8430
+ in: z.enum(["query", "header"]),
8431
+ name: z.string(),
8432
+ value: z.union([z.string(), z.number()])
8433
+ })).optional()
8184
8434
  });
8185
8435
  /**
8186
- * Params for `composio.logs.search()`.
8436
+ * `manageConnections` shape accepted by `session.update()`. Unlike the create
8437
+ * schema, `callbackUrl: null` removes the stored callback URL while leaving
8438
+ * the sibling connection settings untouched.
8187
8439
  */
8188
- const LogSearchParamsSchema = z$1.object({
8189
- limit: z$1.number().optional(),
8190
- cursor: z$1.string().nullable().optional(),
8191
- filters: z$1.array(LogSearchFilterSchema).optional(),
8192
- timeRange: LogSearchTimeRangeSchema.optional()
8193
- });
8194
- const ToolExecutionLogStatusSchema = z$1.enum(["success", "failed"]);
8195
- const ToolExecutionLogLevelSchema = z$1.enum([
8196
- "info",
8197
- "error",
8198
- "warn"
8440
+ const ToolRouterUpdateManageConnectionsSchema = z.object({
8441
+ enable: z.boolean().optional().describe("Whether to use tools to manage connections in the tool router session. Defaults to true, if set to false, you need to manage connections manually"),
8442
+ callbackUrl: z.string().nullable().optional().describe("The callback url to use in the tool router session. `null` removes the stored callback url; sibling settings are untouched"),
8443
+ waitForConnections: z.boolean().optional().describe("Whether to wait for users to finish authenticating connections before proceeding to the next step. Defaults to false, if set to true, a wait for connections tool call will happen and finish when the connections are ready"),
8444
+ enableConnectionRemoval: z.boolean().nullable().optional().describe("Whether the session exposes the connection removal tool. `null` removes the stored override")
8445
+ }).strict();
8446
+ const ToolRouterElicitationDefaultSchema = z.enum([
8447
+ "allow_all",
8448
+ "ask_every_call",
8449
+ "ask_once_per_session"
8199
8450
  ]);
8200
- const ToolExecutionLogParentSchema = z$1.object({
8201
- logId: z$1.string(),
8202
- toolSlug: z$1.string()
8203
- }).nullable();
8204
- /** Tool log metadata, including the optional exact USD Instant charge. */
8205
- const ToolExecutionLogMetadataSchema = z$1.object({ instant_charge: z$1.string().optional() }).catchall(z$1.unknown());
8451
+ const ToolRouterElicitationOverrideSchema = z.enum([
8452
+ "always_allow",
8453
+ "always_deny",
8454
+ "ask_once",
8455
+ "ask_always"
8456
+ ]);
8457
+ /**
8458
+ * `experimental` block accepted by `session.update()`. Each leaf follows the
8459
+ * PATCH contract of the API: omit to keep the stored value, `null` to remove
8460
+ * it, a value to replace it.
8461
+ */
8462
+ const ToolRouterUpdateExperimentalSchema = z.object({
8463
+ permissions: z.object({
8464
+ default: ToolRouterElicitationDefaultSchema,
8465
+ overrides: z.record(z.string(), ToolRouterElicitationOverrideSchema).optional()
8466
+ }).strict().nullable().optional().describe("Per-tool elicitation permission config. `null` removes the stored block"),
8467
+ linkUrlOverwrite: z.string().nullable().optional().describe("Base URL override for connection link redirects. `null` removes the stored override"),
8468
+ fastMode: z.boolean().nullable().optional().describe("Fast search mode. `null` removes the stored override"),
8469
+ submitFeedback: z.object({ enable: z.boolean() }).strict().nullable().optional().describe("Exposes the COMPOSIO_SUBMIT_FEEDBACK helper tool. `null` removes the stored block"),
8470
+ /**
8471
+ * What happens to a call that needs the user's approval when the session's
8472
+ * MCP client can't ask the user: `deny` or `allow`.
8473
+ * @experimental
8474
+ */
8475
+ noElicitationSupportFallback: ToolRouterNoElicitationSupportFallbackSchema.optional(),
8476
+ sessionConfigId: z.string().min(1).optional().describe("Apply the latest active saved Session config (`sc_…`) from this project to this session. Replaces the session's toolkit, tool and tag access and cannot be combined with toolkits, tools or tags")
8477
+ }).strict();
8206
8478
  /**
8207
- * A tool-execution log entry as returned by `composio.logs.search()`.
8479
+ * Options for `session.update()`. For every policy block, omitting the key
8480
+ * preserves the stored value and `null` removes the stored override (which can
8481
+ * increase access: `toolkits: null` restores the unrestricted default, unlike
8482
+ * `toolkits: []`, which denies every app toolkit).
8208
8483
  */
8209
- const ToolExecutionLogSchema = z$1.object({
8210
- id: z$1.string(),
8211
- /** ISO 8601 timestamp. */
8212
- timestamp: z$1.string(),
8213
- /** Log event type, e.g. `tool.execution`. */
8214
- type: z$1.string(),
8215
- status: ToolExecutionLogStatusSchema,
8216
- level: ToolExecutionLogLevelSchema,
8217
- message: z$1.string().optional(),
8218
- metadata: ToolExecutionLogMetadataSchema,
8219
- metrics: z$1.record(z$1.string(), z$1.unknown()),
8220
- parent: ToolExecutionLogParentSchema
8484
+ const ToolRouterUpdateSessionConfigSchema = z.object({
8485
+ instant: ToolRouterInstantSchema.optional().describe("Experimental Instant usage policy. False disables it. Any supplied object, even one that only sets returnInstantCharge, re-enables it. Omitted subfields keep their stored values."),
8486
+ toolkits: ToolRouterSessionToolkitsSchema.nullable().optional().describe("Toolkit policy. An empty allowlist (`[]` or `{ enable: [] }`) is sent as-is and denies every app toolkit; `null` removes the stored policy and restores the unrestricted default"),
8487
+ tools: z.record(z.string(), z.union([ToolRouterToolsParamSchema, ToolRouterConfigToolsSchema])).nullable().optional().describe("Replaces the entire stored tools map; `null` removes the override"),
8488
+ tags: ToolRouterConfigTagsSchema.nullable().optional().describe("Replaces the global tag policy; `null` removes the override"),
8489
+ authConfigs: z.record(z.string(), z.string()).nullable().optional().describe("Replaces the entire stored auth config map; `null` removes the override"),
8490
+ connectedAccounts: z.record(z.string(), z.union([z.string(), z.array(z.string())])).transform((rec) => {
8491
+ const out = {};
8492
+ for (const [k, v] of Object.entries(rec)) out[k] = typeof v === "string" ? [v] : v;
8493
+ return out;
8494
+ }).nullable().optional().describe("Replaces the entire stored connected accounts map; `null` removes the override"),
8495
+ manageConnections: z.union([z.boolean(), ToolRouterUpdateManageConnectionsSchema]).nullable().optional(),
8496
+ sandbox: ToolRouterSandboxConfigSchema.partial().nullable().optional(),
8497
+ workbench: ToolRouterSandboxConfigSchema.partial().nullable().optional(),
8498
+ multiAccount: z.object({
8499
+ enable: z.boolean().optional(),
8500
+ maxAccountsPerToolkit: z.number().int().min(2).max(10).nullable().optional().describe("`null` removes the stored maximum so the default applies again"),
8501
+ requireExplicitSelection: z.boolean().optional()
8502
+ }).nullable().optional().describe("`null` removes the session override; the mode then resolves to disabled"),
8503
+ proxyExecute: ToolRouterProxyExecuteSchema.nullable().optional().describe("Replaces the proxy execute block; a boolean is shorthand for `{ enable }` and `null` removes it"),
8504
+ hooks: z.array(ToolRouterHookSchema).nullable().optional().describe("Replaces the whole list of hooks; `null` removes every hook"),
8505
+ preload: z.object({ tools: z.union([z.array(z.string()), z.literal("all")]).optional() }).strict().nullable().optional().describe("Replaces the stored preload; `null` removes it"),
8506
+ search: z.object({ enable: z.boolean().optional() }).strict().nullable().optional().describe("Replaces the search block; `null` removes it and restores the defaults"),
8507
+ execute: z.object({ enableMultiExecute: z.boolean().optional() }).strict().nullable().optional().describe("Replaces the execute block; `null` removes it and restores the defaults"),
8508
+ experimental: ToolRouterUpdateExperimentalSchema.nullable().optional().describe("Experimental settings; `null` removes the stored block"),
8509
+ expectedConfigVersion: z.union([z.number().int().positive(), z.literal(false)]).optional().describe("Precondition sent as `expected_config_version`. A positive integer (for example `session.configVersion`) makes the update conditional, so a concurrent change surfaces as ComposioSessionConfigConflictError instead of being overwritten; the API must support the field. Omitted or `false`: no precondition (last writer wins)")
8510
+ }).partial().superRefine((config, ctx) => {
8511
+ if (config.experimental?.sessionConfigId !== void 0) addSessionConfigConflictIssue(ctx, [
8512
+ config.toolkits !== void 0 && "toolkits",
8513
+ config.tools !== void 0 && "tools",
8514
+ config.tags !== void 0 && "tags",
8515
+ config.hooks !== void 0 && "hooks"
8516
+ ].filter((field) => field !== false));
8517
+ if (config.sandbox !== void 0 && config.workbench !== void 0) ctx.addIssue({
8518
+ code: z.ZodIssueCode.custom,
8519
+ message: "Pass either sandbox or workbench, not both. workbench is a backwards-compatible alias for sandbox.",
8520
+ path: ["sandbox"]
8521
+ });
8221
8522
  });
8222
- const LogSearchResponseSchema = z$1.object({
8223
- logs: z$1.array(ToolExecutionLogSchema),
8224
- nextCursor: z$1.string().nullable()
8523
+ const ToolRouterSessionDeleteResponseSchema = z.object({
8524
+ sessionId: z.string(),
8525
+ deleted: z.literal(true)
8225
8526
  });
8226
8527
  /**
8227
- * A single tool-execution log with its full detail, as returned by
8228
- * `composio.logs.get()`.
8528
+ * Options for `session.listConfigHistory()`.
8229
8529
  */
8230
- const ToolExecutionLogDetailSchema = ToolExecutionLogSchema.extend({
8231
- timings: z$1.object({
8232
- /** Epoch milliseconds. */
8233
- startTime: z$1.number(),
8234
- /** Epoch milliseconds. */
8235
- endTime: z$1.number()
8236
- }).optional(),
8237
- context: z$1.object({
8238
- sessionId: z$1.string().optional(),
8239
- traceId: z$1.string().optional(),
8240
- requestId: z$1.string().optional()
8241
- }),
8242
- source: z$1.object({
8243
- host: z$1.string().optional(),
8244
- framework: z$1.string().optional(),
8245
- language: z$1.string().optional()
8246
- }),
8247
- data: z$1.record(z$1.string(), z$1.unknown())
8530
+ const ToolRouterSessionListConfigHistoryOptionsSchema = z.object({
8531
+ /** Cursor from a previous response's `nextCursor`. */
8532
+ cursor: z.string().optional(),
8533
+ /** Number of items per page, max allowed is 100. */
8534
+ limit: z.number().optional()
8248
8535
  });
8249
-
8250
- //#endregion
8251
- //#region src/utils/transformers/logs.ts
8252
- const transformLogSearchParams = (params) => ({
8253
- limit: params.limit,
8254
- cursor: params.cursor,
8255
- filters: params.filters,
8256
- time_range: params.timeRange
8536
+ const ToolRouterSessionEnsureConnectedOptionsSchema = z.object({
8537
+ callbackUrl: z.string().optional(),
8538
+ alias: z.string().optional(),
8539
+ experimental: ConnectedAccountExperimentalSchema.optional(),
8540
+ /** Max time to wait for a newly-initiated connection to become active, in milliseconds. Defaults to 60000. */
8541
+ timeout: z.number().int().positive().optional()
8257
8542
  });
8258
- const transformToolExecutionLog = (response) => {
8259
- return transform(response).with(ToolExecutionLogSchema).using((response) => ({
8260
- id: response.id,
8261
- timestamp: response.timestamp,
8262
- type: response.type,
8263
- status: response.status,
8264
- level: response.level,
8265
- message: response.message,
8266
- metadata: ToolExecutionLogMetadataSchema.parse(response.metadata),
8267
- metrics: response.metrics,
8268
- parent: response.parent ? {
8269
- logId: response.parent.log_id,
8270
- toolSlug: response.parent.tool_slug
8271
- } : null
8272
- }));
8273
- };
8274
- const transformLogSearchResponse = (response) => {
8275
- return transform(response).with(LogSearchResponseSchema).using((response) => ({
8276
- logs: response.logs.map(transformToolExecutionLog),
8277
- nextCursor: response.next_cursor
8278
- }));
8279
- };
8280
- const transformToolExecutionLogDetail = (response) => {
8281
- return transform(response).with(ToolExecutionLogDetailSchema).using((response) => ({
8282
- id: response.id,
8283
- timestamp: response.timestamp,
8284
- type: response.type,
8285
- status: response.status,
8286
- level: response.level,
8287
- message: response.message,
8288
- metadata: ToolExecutionLogMetadataSchema.parse(response.metadata),
8289
- metrics: response.metrics,
8290
- parent: response.parent ? {
8291
- logId: response.parent.log_id,
8292
- toolSlug: response.parent.tool_slug
8293
- } : null,
8294
- timings: response.timings ? {
8295
- startTime: response.timings.start_time,
8296
- endTime: response.timings.end_time
8297
- } : void 0,
8298
- context: {
8299
- sessionId: response.context.session_id,
8300
- traceId: response.context.trace_id,
8301
- requestId: response.context.request_id
8302
- },
8303
- source: {
8304
- host: response.source.host,
8305
- framework: response.source.framework,
8306
- language: response.source.language
8307
- },
8308
- data: response.data
8309
- }));
8310
- };
8311
-
8312
- //#endregion
8313
- //#region src/models/Logs.ts
8314
- /**
8315
- * `composio.logs` — tool-execution logs.
8316
- *
8317
- * @example
8318
- * ```typescript
8319
- * const { logs, nextCursor } = await composio.logs.search({
8320
- * filters: [{ field: 'toolkit_slug', operator: '==', value: 'github' }],
8321
- * limit: 20,
8322
- * });
8323
- * const detail = await composio.logs.get(logs[0].id);
8324
- * ```
8325
- */
8326
- var Logs = class {
8327
- client;
8328
- constructor(client) {
8329
- this.client = client;
8330
- telemetry.instrument(this, "Logs");
8331
- }
8332
- /**
8333
- * Search tool-execution logs with filters, a time range and cursor
8334
- * pagination.
8335
- *
8336
- * @param {LogSearchParams} [params] - Filters, `timeRange`, `limit` and `cursor`
8337
- * @returns {Promise<LogSearchResponse>} Matching logs and the next cursor. Charged calls include `metadata.instant_charge` as an exact USD string.
8338
- * @throws {ValidationError} If the params fail validation
8339
- *
8340
- * @example
8341
- * ```typescript
8342
- * const { logs } = await composio.logs.search({
8343
- * filters: [
8344
- * { field: 'status', operator: '==', value: 'failed' },
8345
- * { field: 'user_id', operator: '==', value: 'user_123' },
8346
- * ],
8347
- * timeRange: { from: Date.now() - 24 * 60 * 60 * 1000, to: Date.now() },
8348
- * });
8349
- * ```
8350
- */
8351
- async search(params, requestOptions) {
8352
- const parsedParams = LogSearchParamsSchema.safeParse(params ?? {});
8353
- if (!parsedParams.success) throw new ValidationError("Failed to parse log search params", { cause: parsedParams.error });
8354
- const body = transformLogSearchParams(parsedParams.data);
8355
- const result = await withCancellation(() => this.client.logs.createToolExecution(body, requestOptions), requestOptions?.signal);
8356
- return transformLogSearchResponse(result);
8357
- }
8358
- /**
8359
- * Retrieve one tool-execution log with its full detail (timings, context,
8360
- * source and raw `data`).
8361
- *
8362
- * @param {string} id - The log id
8363
- * @returns {Promise<ToolExecutionLogDetail>} The log detail, with an optional exact USD charge in `metadata.instant_charge`
8364
- *
8365
- * @example
8366
- * ```typescript
8367
- * const log = await composio.logs.get('log_abc123');
8368
- * console.log(log.status, log.timings?.endTime);
8369
- * ```
8370
- */
8371
- async get(id, requestOptions) {
8372
- const result = await withCancellation(() => this.client.logs.retrieveToolExecution(id, requestOptions), requestOptions?.signal);
8373
- return transformToolExecutionLogDetail(result);
8374
- }
8375
- };
8376
8543
 
8377
8544
  //#endregion
8378
8545
  //#region src/types/sessionConfigs.types.ts
@@ -8381,7 +8548,10 @@ var Logs = class {
8381
8548
  * active configs only, 20 per page, at most 100.
8382
8549
  */
8383
8550
  const SessionConfigListParamsSchema = z$1.object({
8384
- /** Case-insensitive substring match against the config name. */
8551
+ /**
8552
+ * @deprecated The Composio API no longer accepts this field. It is ignored
8553
+ * and `list()` logs a warning when it is set; filter `items` by name instead.
8554
+ */
8385
8555
  search: z$1.string().optional(),
8386
8556
  /** `true` returns only archived configs. Omitted returns active configs. */
8387
8557
  archived: z$1.boolean().optional(),
@@ -8411,20 +8581,45 @@ const SessionConfigListResponseSchema = z$1.object({
8411
8581
  });
8412
8582
  const SessionConfigTagPolicySchema = z$1.object({
8413
8583
  enable: z$1.array(ToolRouterTagsParamSchema.element).optional(),
8414
- disable: z$1.array(ToolRouterTagsParamSchema.element).optional()
8584
+ disable: z$1.array(ToolRouterTagsParamSchema.element).optional(),
8585
+ /** Tags whose tools need the user's approval before they run. */
8586
+ require_approval: z$1.array(ToolRouterTagsParamSchema.element).optional()
8415
8587
  });
8588
+ /** What in a policy entry needs the user's approval before it runs. */
8589
+ const requireApproval = { require_approval: z$1.array(z$1.string()).optional() };
8590
+ const ApprovalOnlyPolicySchema = z$1.object({ require_approval: z$1.array(z$1.string()) });
8416
8591
  /**
8417
8592
  * The access policy stored in a saved Session config, in the backend's
8418
- * `enable`/`disable` shape. Toolkit slug keys and tag names are kept exactly
8419
- * as the backend sends them.
8593
+ * `enable`/`disable`/`require_approval` shape. Toolkit slug keys and tag names
8594
+ * are kept exactly as the backend sends them.
8420
8595
  */
8421
8596
  const SessionConfigPolicySchema = z$1.object({
8422
- toolkits: z$1.union([z$1.object({ enable: z$1.array(z$1.string()) }), z$1.object({ disable: z$1.array(z$1.string()) })]).optional(),
8597
+ toolkits: z$1.union([
8598
+ z$1.object({
8599
+ enable: z$1.array(z$1.string()),
8600
+ ...requireApproval
8601
+ }),
8602
+ z$1.object({
8603
+ disable: z$1.array(z$1.string()),
8604
+ ...requireApproval
8605
+ }),
8606
+ ApprovalOnlyPolicySchema
8607
+ ]).optional(),
8423
8608
  /** Per-toolkit tool policy, keyed by toolkit slug. */
8424
8609
  tools: z$1.record(z$1.string(), z$1.union([
8425
- z$1.object({ enable: z$1.array(z$1.string()) }),
8426
- z$1.object({ disable: z$1.array(z$1.string()) }),
8427
- z$1.object({ tags: SessionConfigTagPolicySchema })
8610
+ z$1.object({
8611
+ enable: z$1.array(z$1.string()),
8612
+ ...requireApproval
8613
+ }),
8614
+ z$1.object({
8615
+ disable: z$1.array(z$1.string()),
8616
+ ...requireApproval
8617
+ }),
8618
+ z$1.object({
8619
+ tags: SessionConfigTagPolicySchema,
8620
+ ...requireApproval
8621
+ }),
8622
+ ApprovalOnlyPolicySchema
8428
8623
  ])).optional(),
8429
8624
  /** Global tag policy. */
8430
8625
  tags: SessionConfigTagPolicySchema.optional()
@@ -8482,7 +8677,7 @@ const transformSessionConfig = (response) => {
8482
8677
  *
8483
8678
  * @example
8484
8679
  * ```typescript
8485
- * const { items } = await composio.sessionConfigs.list({ search: 'support' });
8680
+ * const { items } = await composio.sessionConfigs.list();
8486
8681
  * const sessionConfig = await composio.sessionConfigs.get(items[0].id);
8487
8682
  * const session = await composio.sessions.create('user_123', {
8488
8683
  * experimental: { sessionConfigId: sessionConfig.id },
@@ -8503,7 +8698,8 @@ var SessionConfigs = class {
8503
8698
  *
8504
8699
  * Requires Session configs to be enabled for the project.
8505
8700
  *
8506
- * @param {SessionConfigListParams} [params] - `search`, `archived`, `limit` and `cursor`
8701
+ * @param {SessionConfigListParams} [params] - `archived`, `limit` and `cursor`; the
8702
+ * deprecated `search` is ignored
8507
8703
  * @returns {Promise<SessionConfigListResponse>} Config summaries and the next cursor
8508
8704
  * @throws {ValidationError} If the params fail validation
8509
8705
  *
@@ -8520,7 +8716,9 @@ var SessionConfigs = class {
8520
8716
  async list(params, requestOptions) {
8521
8717
  const parsedParams = SessionConfigListParamsSchema.safeParse(params ?? {});
8522
8718
  if (!parsedParams.success) throw new ValidationError("Failed to parse session config list params", { cause: parsedParams.error });
8523
- const result = await withCancellation(() => this.client.sessionConfigs.list(parsedParams.data, requestOptions), requestOptions?.signal);
8719
+ const { search, ...query } = parsedParams.data;
8720
+ if (search !== void 0) logger.warn("sessionConfigs.list(): the Composio API no longer accepts `search`; the option is ignored.");
8721
+ const result = await withCancellation(() => this.client.sessionConfigs.list(query, requestOptions), requestOptions?.signal);
8524
8722
  return transformSessionConfigListResponse(result);
8525
8723
  }
8526
8724
  /**
@@ -8946,7 +9144,7 @@ var OpenAIProvider = class extends BaseNonAgenticProvider {
8946
9144
 
8947
9145
  //#endregion
8948
9146
  //#region package.json
8949
- var version = "0.27.0";
9147
+ var version = "0.28.0";
8950
9148
 
8951
9149
  //#endregion
8952
9150
  //#region src/utils/session.ts
@@ -9063,7 +9261,10 @@ const transformToolRouterSandboxParams = (params) => {
9063
9261
  sandbox_size: params.sandboxSize
9064
9262
  };
9065
9263
  };
9066
- /** `hooks` as sent on create and update: `appliesTo` becomes `applies_to`. */
9264
+ /**
9265
+ * `hooks` as sent on create and update: `appliesTo` becomes `applies_to`.
9266
+ * Create and patch take the same hook shape.
9267
+ */
9067
9268
  const transformToolRouterHooksParams = (hooks) => hooks.map(({ appliesTo, ...hook }) => ({
9068
9269
  ...hook,
9069
9270
  applies_to: appliesTo
@@ -9683,77 +9884,6 @@ var RemoteFile = class RemoteFile {
9683
9884
  }
9684
9885
  };
9685
9886
 
9686
- //#endregion
9687
- //#region src/utils/mime.ts
9688
- /**
9689
- * Maps MIME types to file extensions.
9690
- * Used when deriving filenames from content-type headers (e.g. for URLs without path segments).
9691
- */
9692
- function getExtensionFromMimeType(mimeType) {
9693
- const mimeToExt = {
9694
- "text/plain": "txt",
9695
- "text/html": "html",
9696
- "text/css": "css",
9697
- "text/javascript": "js",
9698
- "application/json": "json",
9699
- "application/xml": "xml",
9700
- "application/pdf": "pdf",
9701
- "application/zip": "zip",
9702
- "application/x-zip-compressed": "zip",
9703
- "application/gzip": "gz",
9704
- "application/octet-stream": "bin",
9705
- "application/x-tar": "tar",
9706
- "application/msword": "doc",
9707
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
9708
- "application/vnd.ms-excel": "xls",
9709
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
9710
- "application/vnd.ms-powerpoint": "ppt",
9711
- "application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx",
9712
- "image/jpeg": "jpg",
9713
- "image/jpg": "jpg",
9714
- "image/png": "png",
9715
- "image/gif": "gif",
9716
- "image/svg+xml": "svg",
9717
- "image/webp": "webp",
9718
- "image/bmp": "bmp",
9719
- "image/tiff": "tiff",
9720
- "audio/mpeg": "mp3",
9721
- "audio/wav": "wav",
9722
- "audio/ogg": "ogg",
9723
- "video/mp4": "mp4",
9724
- "video/mpeg": "mpeg",
9725
- "video/quicktime": "mov",
9726
- "video/x-msvideo": "avi",
9727
- "video/webm": "webm"
9728
- };
9729
- const cleanMimeType = mimeType.split(";")[0].toLowerCase().trim();
9730
- if (mimeToExt[cleanMimeType]) return mimeToExt[cleanMimeType];
9731
- const parts = cleanMimeType.split("/");
9732
- if (parts.length === 2) {
9733
- const subtype = parts[1].toLowerCase();
9734
- if (subtype.includes("+")) {
9735
- const plusParts = subtype.split("+");
9736
- const prefix = plusParts[0];
9737
- const suffix = plusParts[plusParts.length - 1];
9738
- if ([
9739
- "svg",
9740
- "atom",
9741
- "rss"
9742
- ].includes(prefix)) return prefix;
9743
- if ([
9744
- "json",
9745
- "xml",
9746
- "yaml",
9747
- "zip",
9748
- "gzip"
9749
- ].includes(suffix)) return suffix;
9750
- return suffix;
9751
- }
9752
- return subtype || "txt";
9753
- }
9754
- return "bin";
9755
- }
9756
-
9757
9887
  //#endregion
9758
9888
  //#region src/models/ToolRouterSessionFileMount.ts
9759
9889
  /**
@@ -10172,7 +10302,7 @@ var SessionContextImpl = class {
10172
10302
  //#endregion
10173
10303
  //#region src/lib/toolRouterSessionDelete.ts
10174
10304
  async function deleteToolRouterSession(client, sessionId, requestOptions) {
10175
- const response = await withCancellation(() => client.delete(`/api/v3.1/tool_router/session/${encodeURIComponent(sessionId)}`, requestOptions), requestOptions?.signal);
10305
+ const response = await withCancellation(() => client.toolRouter.session.delete(sessionId, requestOptions), requestOptions?.signal);
10176
10306
  return ToolRouterSessionDeleteResponseSchema.parse({
10177
10307
  sessionId: response.session_id,
10178
10308
  deleted: response.deleted
@@ -12474,4 +12604,4 @@ const ComposioMcpUpdateResponseSchema = z$1.object({
12474
12604
  });
12475
12605
 
12476
12606
  //#endregion
12477
- export { AuthConfigCreationToolAccessConfigSchema, AuthConfigErrorCodes, AuthConfigListParamsSchema, AuthConfigListResponseSchema, AuthConfigRetrieveResponseSchema, AuthConfigToolAccessConfigSchema, AuthConfigTypes, AuthConfigUpdateParamsSchema, AuthCustomConfigUpdateParamsSchema, AuthDefaultConfigUpdateParamsSchema, AuthScheme, AuthSchemeEnum, AuthSchemeTypes, BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS, BaseAgenticProvider, BaseNonAgenticProvider, BillcomAuthConnectionDataSchema, Composio, ComposioAPIKeyKindError, ComposioAclOnlyForSharedError, ComposioAuthConfigNotFoundError, ComposioBlockedInternalUrlError, ComposioConnectedAccountNotFoundError, ComposioConnectedAccountNotRevokableError, ComposioConnectedAccountRevocationNotSupportedError, ComposioCustomCreateResponseSchema, ComposioError, ComposioFailedToCreateConnectedAccountLink, ComposioFailedToCreatePusherClientError, ComposioFailedToGetSDKRealtimeCredentialsError, ComposioFailedToSubscribeToPusherChannelError, ComposioFailedToUnsubscribeFromPusherChannelError, ComposioFileNotFoundError, ComposioFileUploadAbortedError, ComposioFileUploadError, ComposioFileUploadPathNotAllowedError, ComposioGenerateURLParamsSchema, ComposioGenerateURLResponseSchema, ComposioGlobalExecuteToolFnNotSetError, ComposioInvalidExecuteFunctionError, ComposioInvalidModifierError, ComposioInvalidToolArgumentsError, ComposioLegacyConnectedAccountsEndpointRetiredError, ComposioMCPDestinationError, ComposioMcpDeleteResponseSchema, ComposioMcpListResponseSchema, ComposioMcpRetrieveResponseSchema, ComposioMcpUpdateResponseSchema, ComposioMultipleConnectedAccountsError, ComposioNoAPIKeyError, ComposioProvider, ComposioProviderNotDefinedError, ComposioRequestCancelledError, ComposioScopeConfigError, ComposioSensitiveFilePathBlockedError, ComposioSessionConfigConflictError, ComposioSharedAccessDeniedError, ComposioSharedConnectionNotAccessibleError, ComposioToolExecutionError, ComposioToolFetchError, ComposioToolInputRequiredError, ComposioToolNotFoundError, ComposioToolVersionRequiredError, ComposioToolkitFetchError, ComposioToolkitNotFoundError, ComposioTriggerTypeNotFoundError, ComposioWebhookPayloadError, ComposioWebhookSignatureVerificationError, ConnectedAccountAclConfigResponseSchema, ConnectedAccountAclConfigSchema, ConnectedAccountAuthConfigSchema, ConnectedAccountCompleteAuthParamsSchema, ConnectedAccountCompleteAuthResponseSchema, ConnectedAccountErrorCodes, ConnectedAccountExperimentalResponseSchema, ConnectedAccountExperimentalSchema, ConnectedAccountListParamsSchema, ConnectedAccountListResponseSchema, ConnectedAccountRefreshOptionsSchema, ConnectedAccountRetrieveResponseSchema, ConnectedAccountRevokeResponseSchema, ConnectedAccountRevokedTokenSchema, ConnectedAccountStatusSchema, ConnectedAccountStatuses, ConnectedAccountTypeSchema, ConnectedAccountTypes, ConnectionDataSchema, ConnectionExpiredEventSchema, ConnectionRequestErrorCodes, ConnectionRequestFailedError, ConnectionRequestTimeoutError, ConnectionStatus, ConnectionStatuses, CreateAuthConfigParamsSchema, CreateAuthConfigResponseSchema, CreateComposioManagedAuthConfigParamsSchema, CreateConnectedAccountLinkOptionsSchema, CreateConnectedAccountLinkResponseSchema, CreateConnectedAccountOptionsSchema, CreateConnectedAccountParamsSchema, CreateConnectedAccountResponseSchema, CreateCustomAuthConfigParamsSchema, CreateCustomToolBaseSchema, CreateCustomToolkitBaseSchema, CustomAuthParamsSchema, CustomConnectionDataSchema, CustomCreateResponseSchema, CustomOauth1ConnectionDataSchema, CustomOauth2ConnectionDataSchema, CustomToolSlugSchema, CustomToolkitAuthSchemeSchema, CustomToolkitDeleteResponseSchema, CustomToolkitSyncParamsSchema, CustomToolkitSyncResponseSchema, CustomToolkitUpsertParamsSchema, CustomToolkitUpsertResponseSchema, CustomToolkits, DefaultCreateConnectedAccountParamsSchema, DefaultWebhookSubscriptionEvents, Experimental, FileDeleteResponseSchema, FileListResponseSchema, FileModifierErrorCodes, GenerateURLParamsSchema, GenerateURLResponseSchema, IncomingTriggerPayloadSchema, JSONSchemaPropertySchema, JsonSchemaRefResolutionError, JsonSchemaToZodError, Keyring, KeyringTransferKeySchema, KeyringTransferKeysResponseSchema, LogSearchFilterFieldSchema, LogSearchFilterOperatorSchema, LogSearchFilterSchema, LogSearchParamsSchema, LogSearchResponseSchema, LogSearchTimeRangeSchema, Logs, MAX_URL_UPLOAD_SIZE_BYTES, MCP, MCPAuthOptionsSchema, MCPGenerateURLParamsSchema, MCPGetServerParamsSchema, MCPMultiAppServerSchema, MCPServerCreateResponseSchema, MCPServerListResponseSchema, MCPServerSchema, MCPServerTypeSchema, MCPServerUpdateParamsSchema, MCPSingleAppServerSchema, MCPToolkitConfigSchema, MCPToolkitConfigsArraySchema, McpDeleteResponseSchema, McpListResponseSchema, McpRetrieveResponseSchema, McpUpdateResponseSchema, Oauth1ActiveConnectionDataSchema, Oauth1ConnectionDataSchema, Oauth1ExpiredConnectionDataSchema, Oauth1FailedConnectionDataSchema, Oauth1InactiveConnectionDataSchema, Oauth1InitiatedConnectionDataSchema, Oauth1InitiatingConnectionDataSchema, Oauth2ActiveConnectionDataSchema, Oauth2ConnectionDataSchema, Oauth2ExpiredConnectionDataSchema, Oauth2FailedConnectionDataSchema, Oauth2InactiveConnectionDataSchema, Oauth2InitiatedConnectionDataSchema, Oauth2InitiatingConnectionDataSchema, Oauth2RevokedConnectionDataSchema, OpenAIProvider, RedirectableAuthSchemeSchema, RemoteFile, RemoteFileDataSchema, RemoteFileDownloadError, RemoteFileErrorCodes, SDKErrorCodes, SandboxSizeSchema, SessionConfigListParamsSchema, SessionConfigListResponseSchema, SessionConfigPolicySchema, SessionConfigSchema, SessionConfigSummarySchema, SessionConfigs, SessionPreset, SessionProxyExecuteParamsSchema, Sessions, SetWebhookSubscriptionParamsSchema, SingleConnectedAccountDetailedResponseSchema, SsrfErrorCodes, ToolErrorCodes, ToolExecuteMetaParamsSchema, ToolExecuteParamsSchema, ToolExecuteResponseSchema, ToolExecutionLogDetailSchema, ToolExecutionLogLevelSchema, ToolExecutionLogMetadataSchema, ToolExecutionLogParentSchema, ToolExecutionLogSchema, ToolExecutionLogStatusSchema, ToolKitItemSchema, ToolKitListResponseSchema, ToolKitMetaSchema, ToolListParamsSchema, ToolListResponseSchema, ToolProxyParamsSchema, ToolRouterBlockReasonSchema, ToolRouterConfigManageConnectionsSchema, ToolRouterConfigTagsSchema, ToolRouterConfigToolsSchema, ToolRouterCreateSessionConfigSchema, ToolRouterErrorCodes, ToolRouterHookAppliesToSchema, ToolRouterHookConditionCheckHandlerSchema, ToolRouterHookPromptInjectionCheckHandlerSchema, ToolRouterHookResultSchema, ToolRouterHookSchema, ToolRouterInstantSchema, ToolRouterMCPServerConfigSchema, ToolRouterManageConnectionsConfigSchema, ToolRouterProxyExecuteConfigSchema, ToolRouterProxyExecuteSchema, ToolRouterSandboxConfigSchema, ToolRouterSession, ToolRouterSessionDeleteResponseSchema, ToolRouterSessionEnsureConnectedOptionsSchema, ToolRouterSessionExecuteResponseSchema, ToolRouterSessionFilesMountDeleteOptionsSchema, ToolRouterSessionFilesMountDownloadOptionsSchema, ToolRouterSessionFilesMountListOptionsSchema, ToolRouterSessionFilesMountUploadOptionsSchema, ToolRouterSessionListConfigHistoryOptionsSchema, ToolRouterSessionSearchResponseSchema, ToolRouterTagsEnableDisableSchema, ToolRouterTagsParamSchema, ToolRouterToolkitsDisabledConfigSchema, ToolRouterToolkitsEnabledConfigSchema, ToolRouterToolkitsOptionsSchema, ToolRouterToolkitsParamSchema, ToolRouterToolsParamSchema, ToolRouterUpdateExperimentalSchema, ToolRouterUpdateManageConnectionsSchema, ToolRouterUpdateSessionConfigSchema, ToolSchema, ToolkitAuthConfigDetailsSchema, ToolkitAuthFieldSchema, ToolkitAuthFieldsResponseSchema, ToolkitCategorySchema, ToolkitChangelogItemSchema, ToolkitChangelogResponseSchema, ToolkitConditionalScopeSchema, ToolkitConnectionStateSchema, ToolkitConnectionsDetailsSchema, ToolkitErrorCodes, ToolkitGetManySlugsSchema, ToolkitGrantContextDimensionSchema, ToolkitLatestVersionSchema, ToolkitListGrantContextsParamsSchema, ToolkitListGrantContextsResponseSchema, ToolkitMangedByEnumSchema, ToolkitRecommendScopesParamsSchema, ToolkitRecommendScopesResponseSchema, ToolkitRetrieveCategoriesResponseSchema, ToolkitRetrieveResponseSchema, ToolkitSchema, ToolkitSortByEnumSchema, ToolkitVersionChangelogSchema, ToolkitVersionParamSchema, ToolkitVersionSchema, ToolkitVersionsSchema, ToolkitsGetManyParamsSchema, ToolkitsListParamsSchema, TriggerErrorCodes, TriggerInstanceListActiveParamsSchema, TriggerInstanceListActiveResponseItemSchema, TriggerInstanceListActiveResponseSchema, TriggerInstanceManageDeleteResponseSchema, TriggerInstanceManageUpdateParamsSchema, TriggerInstanceManageUpdateResponseSchema, TriggerInstanceUpsertParamsSchema, TriggerInstanceUpsertResponseSchema, TriggerStatusEnum, TriggerStatuses, TriggerSubscribeParamSchema, TriggerTypeSchema, TriggersTypeListParamsSchema, TriggersTypeListResponseSchema, UpdateConnectedAccountAclParamsSchema, UpdateConnectedAccountParamsSchema, Usage, UsageBreakdownGroupSchema, UsageBreakdownParamsSchema, UsageBreakdownResponseSchema, UsageEntitySummarySchema, UsageFiltersSchema, UsageOrderBySchema, UsageOrderDirectionSchema, UsageSummaryParamsSchema, UsageSummaryResponseSchema, ValidationError, ValidationErrorCodes, VerifyWebhookParamsSchema, WebhookConnectedAccountAuthConfigSchema, WebhookConnectionMetadataSchema, WebhookConnectionStateSchema, WebhookEndpointCreateParamsSchema, WebhookEndpointListItemSchema, WebhookEndpointListParamsSchema, WebhookEndpointListResponseSchema, WebhookEndpointReplaceParamsSchema, WebhookEndpointSchema, WebhookEndpointUpdateParamsSchema, WebhookEndpoints, WebhookEventSchema, WebhookEventTypes, WebhookPayloadSchema, WebhookPayloadV1Schema, WebhookPayloadV2Schema, WebhookPayloadV3Schema, WebhookSubscriptionDeleteResponseSchema, WebhookSubscriptionEventTypeSchema, WebhookSubscriptionEventTypesResponseSchema, WebhookSubscriptionListParamsSchema, WebhookSubscriptionListResponseSchema, WebhookSubscriptionRotateSecretResponseSchema, WebhookSubscriptionSchema, WebhookSubscriptionSetParamsSchema, WebhookSubscriptionUpdateParamsSchema, WebhookSubscriptions, WebhookTriggerPayloadV3Schema, WebhookVersionSchema, WebhookVersions, Webhooks, assertSafeFileUploadPath, constants_exports as constants, createConnectionRequest, deduplicateJsonSchemaRequiredArrays, dereferenceJsonSchema, ensureObjectTypeOnProperties, createCustomTool as experimental_createTool, createCustomToolkit as experimental_createToolkit, getExtensionFromMimeType, handleToolExecutionError, isBlockedSensitiveFileUploadPath, isRequestAbortError, jsonSchemaToZodSchema, logger, mappingHasRenames, normalizeToolArguments, omitNullToolArguments, readResponseBodyWithLimit, removeNonRequiredProperties, restoreOriginalKeys, sanitizeSchemaPropertyKeys, telemetry, toStrictJsonSchema };
12607
+ export { AuthConfigCreationToolAccessConfigSchema, AuthConfigErrorCodes, AuthConfigListParamsSchema, AuthConfigListResponseSchema, AuthConfigRetrieveResponseSchema, AuthConfigToolAccessConfigSchema, AuthConfigTypes, AuthConfigUpdateParamsSchema, AuthCustomConfigUpdateParamsSchema, AuthDefaultConfigUpdateParamsSchema, AuthScheme, AuthSchemeEnum, AuthSchemeTypes, BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS, BaseAgenticProvider, BaseNonAgenticProvider, BillcomAuthConnectionDataSchema, Composio, ComposioAPIKeyKindError, ComposioAclOnlyForSharedError, ComposioAuthConfigNotFoundError, ComposioBlockedInternalUrlError, ComposioConnectedAccountNotFoundError, ComposioConnectedAccountNotRevokableError, ComposioConnectedAccountRevocationNotSupportedError, ComposioCustomCreateResponseSchema, ComposioError, ComposioFailedToCreateConnectedAccountLink, ComposioFailedToCreatePusherClientError, ComposioFailedToGetSDKRealtimeCredentialsError, ComposioFailedToSubscribeToPusherChannelError, ComposioFailedToUnsubscribeFromPusherChannelError, ComposioFileNotFoundError, ComposioFileUploadAbortedError, ComposioFileUploadError, ComposioFileUploadPathNotAllowedError, ComposioGenerateURLParamsSchema, ComposioGenerateURLResponseSchema, ComposioGlobalExecuteToolFnNotSetError, ComposioInvalidExecuteFunctionError, ComposioInvalidModifierError, ComposioInvalidToolArgumentsError, ComposioLegacyConnectedAccountsEndpointRetiredError, ComposioMCPDestinationError, ComposioMcpDeleteResponseSchema, ComposioMcpListResponseSchema, ComposioMcpRetrieveResponseSchema, ComposioMcpUpdateResponseSchema, ComposioMultipleConnectedAccountsError, ComposioNoAPIKeyError, ComposioProvider, ComposioProviderNotDefinedError, ComposioRequestCancelledError, ComposioScopeConfigError, ComposioSensitiveFilePathBlockedError, ComposioSessionConfigConflictError, ComposioSharedAccessDeniedError, ComposioSharedConnectionNotAccessibleError, ComposioToolExecutionError, ComposioToolFetchError, ComposioToolInputRequiredError, ComposioToolNotFoundError, ComposioToolVersionRequiredError, ComposioToolkitFetchError, ComposioToolkitNotFoundError, ComposioTriggerTypeNotFoundError, ComposioWebhookPayloadError, ComposioWebhookSignatureVerificationError, ConnectedAccountAclConfigResponseSchema, ConnectedAccountAclConfigSchema, ConnectedAccountAuthConfigSchema, ConnectedAccountCompleteAuthParamsSchema, ConnectedAccountCompleteAuthResponseSchema, ConnectedAccountErrorCodes, ConnectedAccountExperimentalResponseSchema, ConnectedAccountExperimentalSchema, ConnectedAccountListParamsSchema, ConnectedAccountListResponseSchema, ConnectedAccountRefreshOptionsSchema, ConnectedAccountRetrieveResponseSchema, ConnectedAccountRevokeResponseSchema, ConnectedAccountRevokedTokenSchema, ConnectedAccountStatusSchema, ConnectedAccountStatuses, ConnectedAccountTypeSchema, ConnectedAccountTypes, ConnectionDataSchema, ConnectionExpiredEventSchema, ConnectionRequestErrorCodes, ConnectionRequestFailedError, ConnectionRequestTimeoutError, ConnectionStatus, ConnectionStatuses, CreateAuthConfigParamsSchema, CreateAuthConfigResponseSchema, CreateComposioManagedAuthConfigParamsSchema, CreateConnectedAccountLinkOptionsSchema, CreateConnectedAccountLinkResponseSchema, CreateConnectedAccountOptionsSchema, CreateConnectedAccountParamsSchema, CreateConnectedAccountResponseSchema, CreateCustomAuthConfigParamsSchema, CreateCustomToolBaseSchema, CreateCustomToolkitBaseSchema, CustomAuthParamsSchema, CustomConnectionDataSchema, CustomCreateResponseSchema, CustomOauth1ConnectionDataSchema, CustomOauth2ConnectionDataSchema, CustomToolSlugSchema, CustomToolkitAuthSchemeSchema, CustomToolkitCreateParamsSchema, CustomToolkitCreateResponseSchema, CustomToolkitDeleteResponseSchema, CustomToolkitSyncParamsSchema, CustomToolkitSyncResponseSchema, CustomToolkitUpdateParamsSchema, CustomToolkitUpdateResponseSchema, CustomToolkitUpsertParamsSchema, CustomToolkitUpsertResponseSchema, CustomToolkits, DefaultCreateConnectedAccountParamsSchema, DefaultWebhookSubscriptionEvents, Experimental, FileDeleteResponseSchema, FileListResponseSchema, FileModifierErrorCodes, GenerateURLParamsSchema, GenerateURLResponseSchema, IncomingTriggerPayloadSchema, JSONSchemaPropertySchema, JsonSchemaRefResolutionError, JsonSchemaToZodError, Keyring, KeyringTransferKeySchema, KeyringTransferKeysResponseSchema, LogSearchFilterFieldSchema, LogSearchFilterOperatorSchema, LogSearchFilterSchema, LogSearchParamsSchema, LogSearchResponseSchema, LogSearchTimeRangeSchema, Logs, MAX_URL_UPLOAD_SIZE_BYTES, MCP, MCPAuthOptionsSchema, MCPGenerateURLParamsSchema, MCPGetServerParamsSchema, MCPMultiAppServerSchema, MCPServerCreateResponseSchema, MCPServerListResponseSchema, MCPServerSchema, MCPServerTypeSchema, MCPServerUpdateParamsSchema, MCPSingleAppServerSchema, MCPToolkitConfigSchema, MCPToolkitConfigsArraySchema, McpDeleteResponseSchema, McpListResponseSchema, McpRetrieveResponseSchema, McpUpdateResponseSchema, Oauth1ActiveConnectionDataSchema, Oauth1ConnectionDataSchema, Oauth1ExpiredConnectionDataSchema, Oauth1FailedConnectionDataSchema, Oauth1InactiveConnectionDataSchema, Oauth1InitiatedConnectionDataSchema, Oauth1InitiatingConnectionDataSchema, Oauth2ActiveConnectionDataSchema, Oauth2ConnectionDataSchema, Oauth2ExpiredConnectionDataSchema, Oauth2FailedConnectionDataSchema, Oauth2InactiveConnectionDataSchema, Oauth2InitiatedConnectionDataSchema, Oauth2InitiatingConnectionDataSchema, Oauth2RevokedConnectionDataSchema, OpenAIProvider, RedirectableAuthSchemeSchema, RemoteFile, RemoteFileDataSchema, RemoteFileDownloadError, RemoteFileErrorCodes, SDKErrorCodes, SandboxSizeSchema, SessionConfigListParamsSchema, SessionConfigListResponseSchema, SessionConfigPolicySchema, SessionConfigSchema, SessionConfigSummarySchema, SessionConfigs, SessionPreset, SessionProxyExecuteParamsSchema, Sessions, SetWebhookSubscriptionParamsSchema, SingleConnectedAccountDetailedResponseSchema, SsrfErrorCodes, ToolErrorCodes, ToolExecuteMetaParamsSchema, ToolExecuteParamsSchema, ToolExecuteResponseSchema, ToolExecutionLogDetailSchema, ToolExecutionLogLevelSchema, ToolExecutionLogMetadataSchema, ToolExecutionLogParentSchema, ToolExecutionLogSchema, ToolExecutionLogStatusSchema, ToolKitItemSchema, ToolKitListResponseSchema, ToolKitMetaSchema, ToolListParamsSchema, ToolListResponseSchema, ToolProxyParamsSchema, ToolRouterBlockReasonSchema, ToolRouterConfigManageConnectionsSchema, ToolRouterConfigTagsSchema, ToolRouterConfigToolsSchema, ToolRouterCreateSessionConfigSchema, ToolRouterErrorCodes, ToolRouterHookAppliesToSchema, ToolRouterHookConditionCheckHandlerSchema, ToolRouterHookPromptInjectionCheckHandlerSchema, ToolRouterHookResultSchema, ToolRouterHookSchema, ToolRouterInstantSchema, ToolRouterMCPServerConfigSchema, ToolRouterManageConnectionsConfigSchema, ToolRouterProxyExecuteConfigSchema, ToolRouterProxyExecuteSchema, ToolRouterSandboxConfigSchema, ToolRouterSession, ToolRouterSessionDeleteResponseSchema, ToolRouterSessionEnsureConnectedOptionsSchema, ToolRouterSessionExecuteResponseSchema, ToolRouterSessionFilesMountDeleteOptionsSchema, ToolRouterSessionFilesMountDownloadOptionsSchema, ToolRouterSessionFilesMountListOptionsSchema, ToolRouterSessionFilesMountUploadOptionsSchema, ToolRouterSessionListConfigHistoryOptionsSchema, ToolRouterSessionSearchResponseSchema, ToolRouterTagsEnableDisableSchema, ToolRouterTagsParamSchema, ToolRouterToolkitsDisabledConfigSchema, ToolRouterToolkitsEnabledConfigSchema, ToolRouterToolkitsOptionsSchema, ToolRouterToolkitsParamSchema, ToolRouterToolsParamSchema, ToolRouterUpdateExperimentalSchema, ToolRouterUpdateManageConnectionsSchema, ToolRouterUpdateSessionConfigSchema, ToolSchema, ToolkitAuthConfigDetailsSchema, ToolkitAuthFieldSchema, ToolkitAuthFieldsResponseSchema, ToolkitCategorySchema, ToolkitChangelogItemSchema, ToolkitChangelogResponseSchema, ToolkitConditionalScopeSchema, ToolkitConnectionStateSchema, ToolkitConnectionsDetailsSchema, ToolkitErrorCodes, ToolkitGetManySlugsSchema, ToolkitGrantContextDimensionSchema, ToolkitLatestVersionSchema, ToolkitListGrantContextsParamsSchema, ToolkitListGrantContextsResponseSchema, ToolkitMangedByEnumSchema, ToolkitRecommendScopesParamsSchema, ToolkitRecommendScopesResponseSchema, ToolkitRetrieveCategoriesResponseSchema, ToolkitRetrieveResponseSchema, ToolkitSchema, ToolkitSortByEnumSchema, ToolkitVersionChangelogSchema, ToolkitVersionParamSchema, ToolkitVersionSchema, ToolkitVersionsSchema, ToolkitsGetManyParamsSchema, ToolkitsListParamsSchema, TriggerErrorCodes, TriggerInstanceListActiveParamsSchema, TriggerInstanceListActiveResponseItemSchema, TriggerInstanceListActiveResponseSchema, TriggerInstanceManageDeleteResponseSchema, TriggerInstanceManageUpdateParamsSchema, TriggerInstanceManageUpdateResponseSchema, TriggerInstanceTypeSchema, TriggerInstanceUpsertParamsSchema, TriggerInstanceUpsertResponseSchema, TriggerStatusEnum, TriggerStatuses, TriggerSubscribeParamSchema, TriggerTypeSchema, TriggersTypeListParamsSchema, TriggersTypeListResponseSchema, UpdateConnectedAccountAclParamsSchema, UpdateConnectedAccountParamsSchema, Usage, UsageBreakdownGroupSchema, UsageBreakdownParamsSchema, UsageBreakdownResponseSchema, UsageEntitySummarySchema, UsageFiltersSchema, UsageOrderBySchema, UsageOrderDirectionSchema, UsageSummaryParamsSchema, UsageSummaryResponseSchema, ValidationError, ValidationErrorCodes, VerifyWebhookParamsSchema, WebhookConnectedAccountAuthConfigSchema, WebhookConnectionMetadataSchema, WebhookConnectionStateSchema, WebhookEndpointCreateParamsSchema, WebhookEndpointListItemSchema, WebhookEndpointListParamsSchema, WebhookEndpointListResponseSchema, WebhookEndpointReplaceParamsSchema, WebhookEndpointSchema, WebhookEndpointUpdateParamsSchema, WebhookEndpoints, WebhookEventSchema, WebhookEventTypes, WebhookPayloadSchema, WebhookPayloadV1Schema, WebhookPayloadV2Schema, WebhookPayloadV3Schema, WebhookSubscriptionDeleteResponseSchema, WebhookSubscriptionEventTypeSchema, WebhookSubscriptionEventTypesResponseSchema, WebhookSubscriptionListParamsSchema, WebhookSubscriptionListResponseSchema, WebhookSubscriptionRotateSecretResponseSchema, WebhookSubscriptionSchema, WebhookSubscriptionSetParamsSchema, WebhookSubscriptionUpdateParamsSchema, WebhookSubscriptions, WebhookTriggerPayloadV3Schema, WebhookVersionSchema, WebhookVersions, Webhooks, assertSafeFileUploadPath, constants_exports as constants, createConnectionRequest, deduplicateJsonSchemaRequiredArrays, dereferenceJsonSchema, ensureObjectTypeOnProperties, createCustomTool as experimental_createTool, createCustomToolkit as experimental_createToolkit, getExtensionFromMimeType, handleToolExecutionError, isBlockedSensitiveFileUploadPath, isRequestAbortError, jsonSchemaToZodSchema, logger, mappingHasRenames, normalizeToolArguments, omitNullToolArguments, readResponseBodyWithLimit, removeNonRequiredProperties, restoreOriginalKeys, sanitizeSchemaPropertyKeys, telemetry, toStrictJsonSchema };