@composio/core 0.3.4 → 0.4.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.
package/dist/index.cjs CHANGED
@@ -3040,6 +3040,37 @@ var Tools = class {
3040
3040
  return modifiedTools;
3041
3041
  }
3042
3042
  /**
3043
+ * Fetches the meta tools for a tool router session.
3044
+ * This method fetches the meta tools from the Composio API and transforms them to the expected format.
3045
+ * It provides access to the underlying meta tool data without provider-specific wrapping.
3046
+ *
3047
+ * @param sessionId {string} The session id to get the meta tools for
3048
+ * @param options {SchemaModifierOptions} Optional configuration for tool retrieval
3049
+ * @param {TransformToolSchemaModifier} [options.modifySchema] - Function to transform the tool schema
3050
+ * @returns {Promise<ToolList>} The list of meta tools
3051
+ *
3052
+ * @example
3053
+ * ```typescript
3054
+ * const metaTools = await composio.tools.getRawToolRouterMetaTools('session_123');
3055
+ * console.log(metaTools);
3056
+ * ```
3057
+ */
3058
+ async getRawToolRouterMetaTools(sessionId, options) {
3059
+ let modifiedTools = (await this.client.toolRouter.session.tools(sessionId)).items.map((tool) => this.transformToolCases(tool));
3060
+ if (options?.modifySchema) {
3061
+ const modifier = options.modifySchema;
3062
+ if (typeof modifier === "function") {
3063
+ const modifiedPromises = modifiedTools.map((tool) => modifier({
3064
+ toolSlug: tool.slug,
3065
+ toolkitSlug: tool.toolkit?.slug ?? "unknown",
3066
+ schema: tool
3067
+ }));
3068
+ modifiedTools = await Promise.all(modifiedPromises);
3069
+ } else throw new ComposioInvalidModifierError("Invalid schema modifier. Not a function.");
3070
+ }
3071
+ return modifiedTools;
3072
+ }
3073
+ /**
3043
3074
  * Retrieves a specific tool by its slug from the Composio API.
3044
3075
  *
3045
3076
  * This method fetches a single tool in raw format without provider-specific wrapping,
@@ -3167,7 +3198,7 @@ var Tools = class {
3167
3198
  *
3168
3199
  * @param {string} sessionId - The session id to execute the tool for
3169
3200
  * @param {Tool[]} tools - The tools to wrap
3170
- * @param {ExecuteToolModifiers} modifiers - The modifiers to apply to the tool
3201
+ * @param {SessionExecuteMetaModifiers} modifiers - The modifiers to apply to the tool
3171
3202
  * @returns {Tool[]} The wrapped tools
3172
3203
  */
3173
3204
  wrapToolsForToolRouter(sessionId, tools, modifiers) {
@@ -3199,7 +3230,7 @@ var Tools = class {
3199
3230
  * Creates a function that executes a tool for a tool router session
3200
3231
  *
3201
3232
  * @param {string} sessionId - The session id to execute the tool for
3202
- * @param {ExecuteToolModifiers} modifiers - The modifiers to apply to the tool
3233
+ * @param {SessionExecuteMetaModifiers} modifiers - The modifiers to apply to the tool
3203
3234
  * @returns {ExecuteToolFn} The execute tool function
3204
3235
  */
3205
3236
  createExecuteToolFnForToolRouter(sessionId, modifiers) {
@@ -3337,36 +3368,36 @@ var Tools = class {
3337
3368
  * @param {ToolExecuteMetaParams} body - The execution parameters
3338
3369
  * @param {string} body.sessionId - The session id to execute the tool for
3339
3370
  * @param {Record<string, unknown>} body.arguments - The input to pass to the tool
3340
- * @param {ExecuteToolModifiers} modifiers - The modifiers to apply to the tool
3371
+ * @param {SessionExecuteMetaModifiers} modifiers - The modifiers to apply to the tool
3341
3372
  * @returns {Promise<ToolExecuteResponse>} The response from the tool execution
3342
3373
  */
3343
3374
  async executeMetaTool(toolSlug, body, modifiers) {
3344
3375
  const executeMetaParams = ToolExecuteMetaParamsSchema.safeParse(body);
3345
3376
  if (!executeMetaParams.success) throw new ValidationError("Invalid tool execute meta parameters", { cause: executeMetaParams.error });
3346
- const tool = await this.getRawComposioToolBySlug(toolSlug);
3347
- if (!tool) throw new ComposioToolNotFoundError(`Tool ${toolSlug} not found`, { meta: {
3348
- slug: toolSlug,
3349
- sessionId: body.sessionId
3350
- } });
3351
- const params = await this.applyBeforeExecuteModifiers(tool, {
3377
+ let modifiedParams = body.arguments ?? {};
3378
+ if (modifiers?.beforeExecute) modifiedParams = await modifiers.beforeExecute({
3352
3379
  toolSlug,
3353
- toolkitSlug: tool.toolkit?.slug ?? "unknown",
3354
- params: body.arguments ?? {}
3355
- }, modifiers?.beforeExecute);
3380
+ toolkitSlug: "composio",
3381
+ sessionId: body.sessionId,
3382
+ params: modifiedParams
3383
+ });
3356
3384
  const response = await this.client.toolRouter.session.executeMeta(body.sessionId, {
3357
3385
  slug: toolSlug,
3358
- arguments: params
3386
+ arguments: modifiedParams
3359
3387
  });
3360
- return await this.applyAfterExecuteModifiers(tool, {
3388
+ let result = {
3389
+ data: response.data,
3390
+ error: response.error,
3391
+ successful: !response.error,
3392
+ logId: response.log_id
3393
+ };
3394
+ if (modifiers?.afterExecute) result = await modifiers.afterExecute({
3361
3395
  toolSlug,
3362
- toolkitSlug: tool.toolkit?.slug ?? "unknown",
3363
- result: {
3364
- data: response.data,
3365
- error: response.error,
3366
- successful: !response.error,
3367
- logId: response.log_id
3368
- }
3369
- }, modifiers?.afterExecute);
3396
+ toolkitSlug: "composio",
3397
+ sessionId: body.sessionId,
3398
+ result
3399
+ });
3400
+ return result;
3370
3401
  }
3371
3402
  /**
3372
3403
  * Fetches the list of all available tools in the Composio SDK.
@@ -5369,7 +5400,7 @@ const MCPServerConnectedAccountsSchema = zod_v3.default.record(zod_v3.default.st
5369
5400
  })));
5370
5401
 
5371
5402
  //#endregion
5372
- //#region src/models/MCP.experimental.ts
5403
+ //#region src/models/MCP.ts
5373
5404
  function transformMCPItemResponse(response) {
5374
5405
  return transform(response).with(MCPItemSchema).using((raw) => ({
5375
5406
  name: raw.name,
@@ -5388,7 +5419,7 @@ function transformMCPItemResponse(response) {
5388
5419
  * Handles MCP server operations.
5389
5420
  * When `config.experimental.mcp` is enabled, this class augments the features of `composio.mcp`.
5390
5421
  */
5391
- var MCP$1 = class {
5422
+ var MCP = class {
5392
5423
  client;
5393
5424
  constructor(client) {
5394
5425
  this.client = client;
@@ -6271,7 +6302,7 @@ var OpenAIProvider = class extends BaseNonAgenticProvider {
6271
6302
 
6272
6303
  //#endregion
6273
6304
  //#region package.json
6274
- var version = "0.3.4";
6305
+ var version = "0.4.0";
6275
6306
 
6276
6307
  //#endregion
6277
6308
  //#region src/models/Files.ts
@@ -6352,7 +6383,8 @@ const getDefaultHeaders = (headers, provider) => {
6352
6383
  const MCPServerTypeSchema = zod_v3.default.enum(["http", "sse"]);
6353
6384
  const ToolRouterConfigManageConnectionsSchema = zod_v3.default.object({
6354
6385
  enable: zod_v3.default.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"),
6355
- callbackUrl: zod_v3.default.string().optional().describe("The callback uri to use in the tool router session")
6386
+ callbackUrl: zod_v3.default.string().optional().describe("The callback uri to use in the tool router session"),
6387
+ waitForConnections: zod_v3.default.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")
6356
6388
  }).strict();
6357
6389
  const ToolRouterToolkitsParamSchema = zod_v3.default.array(zod_v3.default.string()).describe("List of toolkits to enable in the tool router session");
6358
6390
  const ToolRouterToolkitsDisabledConfigSchema = zod_v3.default.object({ disable: ToolRouterToolkitsParamSchema.describe("List of toolkits to disable in the tool router session") }).strict();
@@ -6492,6 +6524,30 @@ const transformToolRouterTagsParams = (params) => {
6492
6524
  disable: params.disable
6493
6525
  };
6494
6526
  };
6527
+ const transformToolRouterManageConnectionsParams = (params) => {
6528
+ if (params === void 0) return { enable: true };
6529
+ if (typeof params === "boolean") return { enable: params };
6530
+ const parsedResult = ToolRouterConfigManageConnectionsSchema.safeParse(params);
6531
+ if (!parsedResult.success) throw new ValidationError("Failed to parse manage connections config", { cause: parsedResult.error });
6532
+ const config = parsedResult.data;
6533
+ return {
6534
+ enable: config.enable ?? true,
6535
+ callback_url: config.callbackUrl,
6536
+ enable_wait_for_connections: config.waitForConnections
6537
+ };
6538
+ };
6539
+ const transformToolRouterWorkbenchParams = (params) => {
6540
+ if (!params) return;
6541
+ return {
6542
+ enable_proxy_execution: params.enableProxyExecution,
6543
+ auto_offload_threshold: params.autoOffloadThreshold
6544
+ };
6545
+ };
6546
+ const transformToolRouterToolkitsParams = (params) => {
6547
+ if (!params) return;
6548
+ if (Array.isArray(params)) return { enable: params };
6549
+ return params;
6550
+ };
6495
6551
 
6496
6552
  //#endregion
6497
6553
  //#region src/models/ToolRouter.ts
@@ -6576,14 +6632,13 @@ var ToolRouter = class {
6576
6632
  * Creates a function that wraps the tools based on the provider.
6577
6633
  * The returned tools will be of the type the frameworks expects.
6578
6634
  *
6579
- * @param userId - The user id to get the tools for
6580
- * @param tools - The tools to wrap
6581
- * @returns A function that wraps the tools based on the provider.
6635
+ * @param sessionId - The session id to get the tools for
6636
+ * @returns A function that wraps the tools based on the provider with session-specific modifiers.
6582
6637
  */
6583
- createToolsFn = (sessionId, toolSlugs) => {
6638
+ createToolsFn = (sessionId) => {
6584
6639
  return async (modifiers) => {
6585
6640
  const ToolsModel = new Tools(this.client, this.config);
6586
- const tools = await ToolsModel.getRawComposioTools({ tools: toolSlugs }, modifiers?.modifySchema ? { modifySchema: modifiers?.modifySchema } : void 0);
6641
+ const tools = await ToolsModel.getRawToolRouterMetaTools(sessionId, modifiers?.modifySchema ? { modifySchema: modifiers?.modifySchema } : void 0);
6587
6642
  return ToolsModel.wrapToolsForToolRouter(sessionId, tools, modifiers);
6588
6643
  };
6589
6644
  };
@@ -6637,31 +6692,21 @@ var ToolRouter = class {
6637
6692
  */
6638
6693
  async create(userId, config) {
6639
6694
  const routerConfig = ToolRouterCreateSessionConfigSchema.parse(config ?? {});
6640
- const manageConnectedAccounts = typeof routerConfig.manageConnections === "boolean" ? routerConfig.manageConnections : routerConfig.manageConnections?.enable ?? true;
6641
- const toolkits = Array.isArray(routerConfig.toolkits) ? { enable: routerConfig.toolkits } : routerConfig.toolkits;
6642
- const tags = transformToolRouterTagsParams(routerConfig.tags);
6643
- const tools = transformToolRouterToolsParams(routerConfig.tools);
6644
6695
  const payload = {
6645
6696
  user_id: userId,
6646
- toolkits,
6647
6697
  auth_configs: routerConfig.authConfigs,
6648
6698
  connected_accounts: routerConfig.connectedAccounts,
6649
- tools,
6650
- tags,
6651
- manage_connections: {
6652
- enable: manageConnectedAccounts,
6653
- callback_url: typeof routerConfig.manageConnections === "object" ? routerConfig.manageConnections.callbackUrl : void 0
6654
- },
6655
- workbench: routerConfig.workbench ? {
6656
- enable_proxy_execution: routerConfig.workbench?.enableProxyExecution,
6657
- auto_offload_threshold: routerConfig.workbench?.autoOffloadThreshold
6658
- } : void 0
6699
+ toolkits: transformToolRouterToolkitsParams(routerConfig.toolkits),
6700
+ tools: transformToolRouterToolsParams(routerConfig.tools),
6701
+ tags: transformToolRouterTagsParams(routerConfig.tags),
6702
+ manage_connections: transformToolRouterManageConnectionsParams(routerConfig.manageConnections),
6703
+ workbench: transformToolRouterWorkbenchParams(routerConfig.workbench)
6659
6704
  };
6660
6705
  const session = await this.client.toolRouter.session.create(payload);
6661
6706
  return {
6662
6707
  sessionId: session.session_id,
6663
6708
  mcp: this.createMCPServerConfig(session.mcp),
6664
- tools: this.createToolsFn(session.session_id, session.tool_router_tools),
6709
+ tools: this.createToolsFn(session.session_id),
6665
6710
  authorize: this.createAuthorizeFn(session.session_id),
6666
6711
  toolkits: this.createToolkitsFn(session.session_id)
6667
6712
  };
@@ -6688,7 +6733,7 @@ var ToolRouter = class {
6688
6733
  return {
6689
6734
  sessionId: session.session_id,
6690
6735
  mcp: this.createMCPServerConfig(session.mcp),
6691
- tools: this.createToolsFn(session.session_id, session.tool_router_tools),
6736
+ tools: this.createToolsFn(session.session_id),
6692
6737
  authorize: this.createAuthorizeFn(session.session_id),
6693
6738
  toolkits: this.createToolkitsFn(session.session_id)
6694
6739
  };
@@ -6715,13 +6760,21 @@ var Composio = class Composio {
6715
6760
  /**
6716
6761
  * Core models for Composio.
6717
6762
  */
6763
+ /** List, retrieve, and execute tools */
6718
6764
  tools;
6765
+ /** Retrieve toolkit metadata and authorize user connections */
6719
6766
  toolkits;
6767
+ /** Manage webhook triggers and event subscriptions */
6720
6768
  triggers;
6769
+ /** The tool provider instance used for wrapping tools in framework-specific formats */
6721
6770
  provider;
6771
+ /** Upload and download files */
6722
6772
  files;
6773
+ /** Manage authentication configurations for toolkits */
6723
6774
  authConfigs;
6775
+ /** Manage authenticated connections */
6724
6776
  connectedAccounts;
6777
+ /** Model Context Protocol server management */
6725
6778
  mcp;
6726
6779
  /**
6727
6780
  * Experimental feature, use with caution
@@ -6760,10 +6813,6 @@ var Composio = class Composio {
6760
6813
  */
6761
6814
  use;
6762
6815
  /**
6763
- * Experimental features
6764
- */
6765
- experimental;
6766
- /**
6767
6816
  * Creates a new instance of the Composio SDK.
6768
6817
  *
6769
6818
  * The constructor initializes the SDK with the provided configuration options,
@@ -6824,7 +6873,7 @@ var Composio = class Composio {
6824
6873
  logLevel: COMPOSIO_LOG_LEVEL
6825
6874
  });
6826
6875
  this.tools = new Tools(this.client, this.config);
6827
- this.mcp = new MCP$1(this.client);
6876
+ this.mcp = new MCP(this.client);
6828
6877
  this.toolkits = new Toolkits(this.client);
6829
6878
  this.triggers = new Triggers(this.client, this.config);
6830
6879
  this.authConfigs = new AuthConfigs(this.client);
@@ -6838,17 +6887,6 @@ var Composio = class Composio {
6838
6887
  this.create = this.toolRouter.create.bind(this.toolRouter);
6839
6888
  this.use = this.toolRouter.use.bind(this.toolRouter);
6840
6889
  /**
6841
- * Initialize Experimental features
6842
- */
6843
- this.experimental = {
6844
- create: async (userId, routerConfig) => {
6845
- return this.toolRouter.create(userId, routerConfig);
6846
- },
6847
- use: async (id) => {
6848
- return this.toolRouter.use(id);
6849
- }
6850
- };
6851
- /**
6852
6890
  * Initialize the client telemetry.
6853
6891
  */
6854
6892
  if (this.config.allowTracking) telemetry.setup({
@@ -7338,628 +7376,6 @@ const ComposioMcpUpdateResponseSchema = zod_v3.z.object({
7338
7376
  tools: zod_v3.z.array(zod_v3.z.string()).optional()
7339
7377
  });
7340
7378
 
7341
- //#endregion
7342
- //#region src/utils/transformers/mcp.ts
7343
- /**
7344
- * Transform MCP create response from snake_case to camelCase
7345
- */
7346
- function transformMcpCreateResponse(response) {
7347
- const result = CustomCreateResponseSchema.safeParse({
7348
- id: response.id,
7349
- name: response.name,
7350
- createdAt: response.created_at,
7351
- updatedAt: response.updated_at,
7352
- status: response.status
7353
- });
7354
- if (!result.success) throw new ValidationError("Failed to parse MCP create response", { cause: result.error });
7355
- return result.data;
7356
- }
7357
- /**
7358
- * Transform MCP list response from snake_case to camelCase
7359
- */
7360
- function transformMcpListResponse(response) {
7361
- const transformedItems = response.items?.map((item) => ({
7362
- id: item.id,
7363
- name: item.name,
7364
- createdAt: item.created_at,
7365
- updatedAt: item.updated_at,
7366
- status: item.status
7367
- }));
7368
- const result = McpListResponseSchema.safeParse({ items: transformedItems });
7369
- if (!result.success) throw new ValidationError("Failed to parse MCP list response", { cause: result.error });
7370
- return result.data;
7371
- }
7372
- /**
7373
- * Transform MCP retrieve response from snake_case to camelCase
7374
- */
7375
- function transformMcpRetrieveResponse(response) {
7376
- const result = McpRetrieveResponseSchema.safeParse({
7377
- id: response.id,
7378
- name: response.name,
7379
- createdAt: response.created_at,
7380
- updatedAt: response.updated_at,
7381
- status: response.status,
7382
- toolkits: response.toolkits,
7383
- tools: response.allowed_tools,
7384
- managedAuthViaComposio: response.managed_auth_via_composio,
7385
- authConfigIds: response.auth_config_ids,
7386
- mcpUrl: response.mcp_url,
7387
- commands: response.commands
7388
- });
7389
- if (!result.success) throw new ValidationError("Failed to parse MCP retrieve response", { cause: result.error });
7390
- return result.data;
7391
- }
7392
- /**
7393
- * Transform MCP delete response from snake_case to camelCase
7394
- */
7395
- function transformMcpDeleteResponse(response) {
7396
- const result = McpDeleteResponseSchema.safeParse({
7397
- id: response.id,
7398
- deleted: response.deleted,
7399
- message: response.message
7400
- });
7401
- if (!result.success) throw new ValidationError("Failed to parse MCP delete response", { cause: result.error });
7402
- return result.data;
7403
- }
7404
- /**
7405
- * Transform MCP update response from snake_case to camelCase
7406
- */
7407
- function transformMcpUpdateResponse(response) {
7408
- const result = McpUpdateResponseSchema.safeParse({
7409
- id: response.id,
7410
- name: response.name,
7411
- createdAt: response.created_at,
7412
- updatedAt: response.updated_at,
7413
- status: response.status,
7414
- toolkits: response.toolkits,
7415
- tools: response.tools
7416
- });
7417
- if (!result.success) throw new ValidationError("Failed to parse MCP update response", { cause: result.error });
7418
- return result.data;
7419
- }
7420
- /**
7421
- * Transform MCP generate URL response from snake_case to camelCase
7422
- */
7423
- function transformMcpGenerateUrlResponse(response) {
7424
- const result = GenerateURLResponseSchema.safeParse({
7425
- connectedAccountUrls: response.connected_account_urls,
7426
- userIdsUrl: response.user_ids_url,
7427
- mcpUrl: response.mcp_url
7428
- });
7429
- if (!result.success) throw new ValidationError("Failed to parse MCP generate URL response", { cause: result.error });
7430
- return result.data;
7431
- }
7432
-
7433
- //#endregion
7434
- //#region src/models/MCP.ts
7435
- /**
7436
- * MCP (Model Control Protocol) class
7437
- * Handles MCP server operations
7438
- */
7439
- var MCP = class {
7440
- client;
7441
- toolkits;
7442
- provider;
7443
- constructor(client, provider) {
7444
- this.client = client;
7445
- this.provider = provider;
7446
- this.toolkits = new Toolkits(client);
7447
- telemetry.instrument(this, "MCP");
7448
- }
7449
- /**
7450
- * Validates toolkit configurations using Zod schema
7451
- * @private
7452
- * @param {MCPToolkitConfig[]} toolkitConfigs - Array of toolkit configurations to validate
7453
- * @param {MCPAuthOptions} [authOptions] - Authentication options to validate
7454
- * @throws {ValidationError} If validation fails
7455
- */
7456
- validateInputs(toolkitConfigs, authOptions) {
7457
- const toolkitConfigsResult = MCPToolkitConfigsArraySchema.safeParse(toolkitConfigs);
7458
- if (toolkitConfigsResult.error) throw new ValidationError("Failed to parse toolkit configurations", { cause: toolkitConfigsResult.error });
7459
- if (authOptions !== void 0) {
7460
- const authOptionsResult = MCPAuthOptionsSchema.safeParse(authOptions);
7461
- if (authOptionsResult.error) throw new ValidationError("Failed to parse auth options", { cause: authOptionsResult.error });
7462
- }
7463
- }
7464
- /**
7465
- * Create a new MCP server
7466
- * @param {Object} params - Parameters for creating the MCP server
7467
- * @param {Array} params.authConfig - Array of auth configurations with id and allowed tools
7468
- * @param {Object} params.options - Server creation options
7469
- * @param {string} params.options.name - Unique name for the MCP server
7470
- * @param {boolean} [params.options.isChatAuth] - Whether to use chat-based authentication
7471
- * @returns {Promise<McpServerCreateResponse<TMcpResponse>>} Created server details with instance getter
7472
- *
7473
- * @example
7474
- * ```typescript
7475
- * const server = await composio.mcp.create("personal-mcp-server", [
7476
- * {
7477
- * authConfigId: "ac_xyz",
7478
- * allowedTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"]
7479
- * }
7480
- * ],
7481
- * {
7482
- * isChatAuth: true
7483
- * }
7484
- * });
7485
- *
7486
- * // Use convenience method on response
7487
- * const urls = await server.getServer({
7488
- * userId: "user123"
7489
- * });
7490
- * ```
7491
- */
7492
- async create(name, serverConfig, options) {
7493
- if (!serverConfig || serverConfig.length === 0) throw new ValidationError("At least one auth config is required", {});
7494
- if (!name) throw new ValidationError("Server name is required", {});
7495
- try {
7496
- const mcpServer = await this.getByName(name);
7497
- const authConfigs = mcpServer.authConfigIds?.sort();
7498
- const sortedCurrentAuthConfigs = serverConfig.map((config) => config.authConfigId).sort();
7499
- if (authConfigs.length > 0 && !authConfigs.every((config, index) => config === sortedCurrentAuthConfigs[index])) throw new ValidationError("MCP server with this name already exists with different auth configs", { meta: { serverName: name } });
7500
- const tools = mcpServer.tools?.sort();
7501
- const sortedCurrentTools = serverConfig.flatMap((config) => config.allowedTools).sort();
7502
- if (tools?.length > 0 && !tools.every((tool, index) => tool === sortedCurrentTools[index])) throw new ValidationError("MCP server with this name already exists with different tools", { meta: { serverName: name } });
7503
- const toolkits$1 = (await Promise.all(serverConfig.map((config) => this.client.authConfigs.retrieve(config.authConfigId)))).map((config) => config.toolkit.slug);
7504
- const camelCaseResponse$1 = transformMcpCreateResponse({
7505
- id: mcpServer.id,
7506
- name: mcpServer.name,
7507
- auth_config_ids: serverConfig.map((config) => config.authConfigId),
7508
- allowed_tools: serverConfig.flatMap((config) => config.allowedTools),
7509
- managed_auth_via_composio: options.isChatAuth || false,
7510
- commands: mcpServer.commands,
7511
- created_at: mcpServer.createdAt,
7512
- updated_at: mcpServer.updatedAt,
7513
- mcp_url: mcpServer.mcpUrl
7514
- });
7515
- return {
7516
- ...camelCaseResponse$1,
7517
- toolkits: toolkits$1,
7518
- getServer: async (params) => {
7519
- return this.getServer(camelCaseResponse$1.id, params.userId || "", { isChatAuth: options.isChatAuth });
7520
- }
7521
- };
7522
- } catch (error) {
7523
- if (error instanceof ValidationError && !error.message.includes("not found")) throw error;
7524
- }
7525
- const toolkits = (await Promise.all(serverConfig.map((config) => this.client.authConfigs.retrieve(config.authConfigId)))).map((config) => config.toolkit.slug);
7526
- let mcpServerCreatedResponse;
7527
- try {
7528
- mcpServerCreatedResponse = await this.client.mcp.custom.create({
7529
- name,
7530
- toolkits,
7531
- custom_tools: serverConfig.flatMap((config) => config.allowedTools),
7532
- managed_auth_via_composio: options.isChatAuth || false,
7533
- auth_config_ids: serverConfig.map((config) => config.authConfigId)
7534
- });
7535
- } catch (error) {
7536
- throw new ValidationError("Failed to create MCP server", { cause: error });
7537
- }
7538
- const serverResponseResult = ComposioCustomCreateResponseSchema.safeParse(mcpServerCreatedResponse);
7539
- if (serverResponseResult.error) throw new ValidationError("Failed to parse MCP server creation response", { cause: serverResponseResult.error });
7540
- const camelCaseResponse = transformMcpCreateResponse(mcpServerCreatedResponse);
7541
- return {
7542
- ...camelCaseResponse,
7543
- toolkits,
7544
- getServer: async (params) => {
7545
- return this.getServer(camelCaseResponse.id, params.userId || "", { isChatAuth: options.isChatAuth });
7546
- }
7547
- };
7548
- }
7549
- /**
7550
- * Get the connection status of a user for an MCP server
7551
- *
7552
- * Checks whether a user has the necessary connected accounts to use all toolkits
7553
- * configured in the specified MCP server. Returns both overall connection status
7554
- * and individual status for each toolkit.
7555
- *
7556
- * @param {Object} params - Parameters for checking connection status
7557
- * @param {string} params.id - The UUID of the MCP server to check
7558
- * @param {string} params.userId - The ID of the user to check connection status for
7559
- * @returns {Promise<McpUserConnectionStatus>} Complete connection status including:
7560
- * - `type`: Overall status (CONNECTED if all toolkits are connected, DISCONNECTED otherwise)
7561
- * - `connected`: Boolean indicating if user can use the MCP server
7562
- * - `connectedToolkits`: Record mapping each toolkit name to its individual connection status
7563
- *
7564
- * @throws {ValidationError} When MCP server has no toolkits configured
7565
- * @throws {ValidationError} When MCP server retrieval fails
7566
- *
7567
- * @example
7568
- * ```typescript
7569
- * // Check if user can access an MCP server with Gmail and Slack toolkits
7570
- * const connectionStatus = await composio.mcp.getUserConnectionStatus('user123', 'mcp-server-uuid');
7571
- *
7572
- * if (connectionStatus.connected) {
7573
- * console.log('User can access all required toolkits');
7574
- * // connectionStatus.type === ConnectionStatus.CONNECTED
7575
- * } else {
7576
- * console.log('User is missing some toolkit connections');
7577
- * // Check individual toolkit statuses
7578
- * Object.entries(connectionStatus.connectedToolkits).forEach(([toolkit, status]) => {
7579
- * if (!status.connected) {
7580
- * console.log(`Missing connection for toolkit: ${toolkit}`);
7581
- * }
7582
- * });
7583
- * }
7584
- * ```
7585
- *
7586
- * @example
7587
- * ```typescript
7588
- * // Example response when user has Gmail connected but missing Slack
7589
- * {
7590
- * type: ConnectionStatus.DISCONNECTED,
7591
- * connected: false,
7592
- * connectedToolkits: {
7593
- * GMAIL: {
7594
- * type: ConnectionStatus.CONNECTED,
7595
- * connected: true,
7596
- * toolkit: 'GMAIL',
7597
- * connectedAccountId: 'conn_gmail_123'
7598
- * },
7599
- * SLACK: {
7600
- * type: ConnectionStatus.DISCONNECTED,
7601
- * connected: false,
7602
- * toolkit: 'SLACK'
7603
- * }
7604
- * }
7605
- * }
7606
- * ```
7607
- */
7608
- async getUserConnectionStatus(userId, serverId) {
7609
- const serverDetails = await this.get(serverId);
7610
- if (!serverDetails.toolkits || serverDetails.toolkits.length === 0) throw new ValidationError("MCP server has no toolkits configured", { meta: { serverId } });
7611
- const connectedAccounts = await this.client.connectedAccounts.list({
7612
- user_ids: [userId],
7613
- toolkit_slugs: serverDetails.toolkits.map((toolkit) => toolkit.toLowerCase()),
7614
- statuses: ["ACTIVE"]
7615
- });
7616
- const connectedAccountsByToolkit = /* @__PURE__ */ new Map();
7617
- connectedAccounts.items?.forEach((account) => {
7618
- connectedAccountsByToolkit.set(account.toolkit.slug.toLowerCase(), account.id);
7619
- });
7620
- const connectedToolkits = {};
7621
- let allToolkitsConnected = true;
7622
- for (const toolkit of serverDetails.toolkits) {
7623
- const connectedAccountId = connectedAccountsByToolkit.get(toolkit.toLowerCase());
7624
- if (connectedAccountId) connectedToolkits[toolkit] = {
7625
- type: ConnectionStatus.CONNECTED,
7626
- connected: true,
7627
- toolkit,
7628
- connectedAccountId
7629
- };
7630
- else {
7631
- connectedToolkits[toolkit] = {
7632
- type: ConnectionStatus.DISCONNECTED,
7633
- connected: false,
7634
- toolkit
7635
- };
7636
- allToolkitsConnected = false;
7637
- }
7638
- }
7639
- if (allToolkitsConnected) return {
7640
- type: ConnectionStatus.CONNECTED,
7641
- connected: true,
7642
- connectedToolkits
7643
- };
7644
- else return {
7645
- type: ConnectionStatus.DISCONNECTED,
7646
- connected: false,
7647
- connectedToolkits
7648
- };
7649
- }
7650
- /**
7651
- * Get the connection parameters for a toolkit
7652
- * @param {string} serverId - The UUID of the MCP server
7653
- * @param {string} toolkit - The toolkit to get connection parameters for
7654
- * @returns {Promise<ToolkitAuthFieldsResponse>} Connection parameters for the toolkit
7655
- */
7656
- async getConnectionParams(serverId, toolkit) {
7657
- const mcpServerDetails = await this.get(serverId);
7658
- const authConfig = (mcpServerDetails.authConfigIds ? await Promise.all(mcpServerDetails.authConfigIds.map((id) => this.client.authConfigs.retrieve(id))) : []).find((config) => config.toolkit.slug === toolkit);
7659
- if (!authConfig) throw new ValidationError("Auth config not found", { meta: {
7660
- serverId,
7661
- toolkit
7662
- } });
7663
- return await this.toolkits.getConnectedAccountInitiationFields(toolkit, authConfig.auth_scheme);
7664
- }
7665
- /**
7666
- * Authorize a user for a toolkit
7667
- * @param {string} serverId - The UUID of the MCP server
7668
- * @param {string} userId - The ID of the user to authorize
7669
- * @param {string} toolkit - The toolkit to authorize
7670
- * @returns {Promise<ConnectionRequest>} Connection request for the toolkit
7671
- */
7672
- async authorize(userId, serverId, toolkit) {
7673
- const authConfigId = (await this.get(serverId)).authConfigIds?.[0];
7674
- return this.toolkits.authorize(userId, toolkit, authConfigId);
7675
- }
7676
- /**
7677
- * Get server URLs for an existing MCP server
7678
- * @param {string} serverId - Server UUID
7679
- * @param {string} userId - User ID to get server URLs for
7680
- * @param {Object} [options] - Additional options for server configuration
7681
- * @param {string[]} [options.limitTools] - Subset of tools to limit (from MCP config)
7682
- * @param {boolean} [options.isChatAuth] - Whether to use chat-based authentication
7683
- * @returns {Promise<TMcpResponse>} Transformed server URLs in provider-specific format
7684
- *
7685
- * @example
7686
- * ```typescript
7687
- * // Get URLs for an existing server with basic user ID
7688
- * const urls = await composio.mcp.getServer("mcp_xyz", "hey@example.com");
7689
- *
7690
- * // Get URLs with additional options
7691
- * const urls = await composio.mcp.getServer("mcp_xyz", "hey@example.com", {
7692
- * limitTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"],
7693
- * isChatAuth: true
7694
- * });
7695
- * ```
7696
- *
7697
- */
7698
- async getServer(serverId, userId, options) {
7699
- const serverDetails = await this.get(serverId);
7700
- if (!userId) throw new ValidationError("User ID is required", {});
7701
- const toolkits = serverDetails.toolkits || [];
7702
- const connectedAccountIds = (await Promise.all(toolkits.map((toolkit) => this.client.connectedAccounts.list({
7703
- user_ids: [userId],
7704
- toolkit_slugs: [toolkit],
7705
- statuses: ["ACTIVE"]
7706
- }).then((res) => res.items?.[0]?.id)))).filter(Boolean);
7707
- let data;
7708
- try {
7709
- data = await this.client.mcp.generate.url({
7710
- user_ids: [userId],
7711
- connected_account_ids: [],
7712
- mcp_server_id: serverId,
7713
- managed_auth_by_composio: options?.isChatAuth ?? serverDetails.managedAuthViaComposio ?? false
7714
- });
7715
- } catch (error) {
7716
- throw new ValidationError("Failed to generate MCP server URL", { cause: error });
7717
- }
7718
- const urlResponseResult = ComposioGenerateURLResponseSchema.safeParse(data);
7719
- if (urlResponseResult.error) throw new ValidationError("Failed to parse MCP URL generation response", { cause: urlResponseResult.error });
7720
- const camelCaseData = transformMcpGenerateUrlResponse(data);
7721
- return this.wrapMcpServerResponse(camelCaseData, serverDetails.name, connectedAccountIds, [userId], toolkits);
7722
- }
7723
- /**
7724
- * List MCP server configurations with filtering options
7725
- * @param {Object} options - Filtering and pagination options
7726
- * @param {number} [options.page] - Page number for pagination
7727
- * @param {number} [options.limit] - Number of items per page
7728
- * @param {string[]} [options.toolkits] - Filter servers by toolkit names
7729
- * @param {string[]} [options.authConfigs] - Filter servers by auth config IDs
7730
- * @param {string} [options.name] - Filter servers by name
7731
- * @param {string} [options.user] - Filter servers by user ID
7732
- * @returns {Promise<McpListResponse>} List of MCP servers matching the filters
7733
- *
7734
- * @example
7735
- * ```typescript
7736
- * // List all servers with pagination
7737
- * const servers = await composio.mcp.list({
7738
- * page: 1,
7739
- * limit: 10
7740
- * });
7741
- *
7742
- * // List Gmail and Supabase servers
7743
- * const filteredServers = await composio.mcp.list({
7744
- * toolkits: ['GMAIL', 'SUPABASE'],
7745
- * authConfigIds: ['auth_123', 'auth_456']
7746
- * });
7747
- * ```
7748
- */
7749
- async list(options) {
7750
- let listResponse;
7751
- try {
7752
- listResponse = await this.client.mcp.list({
7753
- page_no: options.page || 1,
7754
- limit: options.limit || 10,
7755
- toolkits: options?.toolkits?.join(",") || void 0,
7756
- auth_config_ids: options?.authConfigs?.join(",") || void 0,
7757
- name: options?.name
7758
- });
7759
- } catch (error) {
7760
- throw new ValidationError("Failed to list MCP servers", { cause: error });
7761
- }
7762
- const listResponseResult = ComposioMcpListResponseSchema.safeParse(listResponse);
7763
- if (listResponseResult.error) throw new ValidationError("Failed to parse MCP server list response", { cause: listResponseResult.error });
7764
- return transformMcpListResponse(listResponse);
7765
- }
7766
- /**
7767
- * Get details of a specific MCP server
7768
- * @param {string} serverId - Server UUID
7769
- * @returns {Promise<McpRetrieveResponse>} Server details
7770
- *
7771
- * @example
7772
- * ```typescript
7773
- * const serverDetails = await composio.mcp.get('server-uuid');
7774
- * ```
7775
- */
7776
- async get(serverId) {
7777
- let retrieveResponse;
7778
- try {
7779
- retrieveResponse = await this.client.mcp.retrieve(serverId);
7780
- } catch (error) {
7781
- throw new ValidationError("Failed to retrieve MCP server", { cause: error });
7782
- }
7783
- const retrieveResponseResult = McpRetrieveResponseSchema.safeParse({
7784
- ...retrieveResponse,
7785
- mcpUrl: retrieveResponse.mcp_url
7786
- });
7787
- if (retrieveResponseResult.error) throw new ValidationError("Failed to parse MCP server retrieve response", { cause: retrieveResponseResult.error });
7788
- return transformMcpRetrieveResponse(retrieveResponse);
7789
- }
7790
- /**
7791
- * Delete an MCP server
7792
- * @param {string} serverId - Server UUID
7793
- * @returns {Promise<McpDeleteResponse>} Deletion response
7794
- *
7795
- * @example
7796
- * ```typescript
7797
- * const result = await composio.mcp.delete('server-uuid');
7798
- * ```
7799
- */
7800
- async delete(serverId) {
7801
- let deleteResponse;
7802
- try {
7803
- deleteResponse = await this.client.mcp.delete(serverId);
7804
- } catch (error) {
7805
- throw new ValidationError("Failed to delete MCP server", { cause: error });
7806
- }
7807
- const deleteResponseResult = ComposioMcpDeleteResponseSchema.safeParse(deleteResponse);
7808
- if (deleteResponseResult.error) throw new ValidationError("Failed to parse MCP server delete response", { cause: deleteResponseResult.error });
7809
- return transformMcpDeleteResponse(deleteResponse);
7810
- }
7811
- /**
7812
- * Update an MCP server configuration
7813
- * @param {string} id - Server UUID
7814
- * @param {string} name - New unique name for the server
7815
- * @param {MCPToolkitConfig[]} toolkitConfigs - Array of toolkit configurations
7816
- * @param {MCPAuthOptions} [authOptions] - Updated authentication options
7817
- * @returns {Promise<McpUpdateResponse>} Updated server details
7818
- *
7819
- * @example
7820
- * ```typescript
7821
- * const updatedServer = await composio.mcp.update(
7822
- * "server-uuid",
7823
- * "my-updated-server",
7824
- * [
7825
- * {
7826
- * toolkit: "GMAIL",
7827
- * authConfigId: "ac_sdhkjfhjksdk",
7828
- * allowedTools: ["GMAIL_FETCH_EMAILS"],
7829
- * },
7830
- * ],
7831
- * {
7832
- * isChatAuth: true,
7833
- * }
7834
- * );
7835
- * ```
7836
- */
7837
- async update(serverId, name, toolkitConfigs, authOptions) {
7838
- this.validateInputs(toolkitConfigs, authOptions);
7839
- const toolkits = toolkitConfigs.map((config) => config.toolkit);
7840
- let updateResponse;
7841
- try {
7842
- updateResponse = await this.client.mcp.update(serverId, {
7843
- name,
7844
- toolkits,
7845
- allowed_tools: toolkitConfigs.flatMap((config) => config.allowedTools),
7846
- managed_auth_via_composio: authOptions?.isChatAuth || false
7847
- });
7848
- } catch (error) {
7849
- throw new ValidationError("Failed to update MCP server", { cause: error });
7850
- }
7851
- const updateResponseResult = ComposioMcpUpdateResponseSchema.safeParse(updateResponse);
7852
- if (updateResponseResult.error) throw new ValidationError("Failed to parse MCP server update response", { cause: updateResponseResult.error });
7853
- return transformMcpUpdateResponse(updateResponse);
7854
- }
7855
- /**
7856
- * Generate URL for an MCP server
7857
- * @param {string} serverId - Server UUID
7858
- * @param {GenerateURLParams} params - Parameters for URL generation
7859
- * @returns {Promise<GenerateURLResponse>} Generated URL response
7860
- *
7861
- * @example
7862
- * ```typescript
7863
- * const urlResponse = await composio.mcp.generateUrl('server-uuid', {
7864
- * userIds: ['user123'],
7865
- * connectedAccountIds: ['account456'],
7866
- * isChatAuth: true
7867
- * });
7868
- * ```
7869
- */
7870
- async generateUrl(serverId, params) {
7871
- const paramsResult = GenerateURLParamsSchema.safeParse(params);
7872
- if (paramsResult.error) throw new ValidationError("Failed to parse generateUrl parameters", { cause: paramsResult.error });
7873
- let urlResponse;
7874
- try {
7875
- urlResponse = await this.client.mcp.generate.url({
7876
- mcp_server_id: serverId,
7877
- user_ids: params.userIds,
7878
- connected_account_ids: params.connectedAccountIds,
7879
- managed_auth_by_composio: params.composioManagedAuth
7880
- });
7881
- } catch (error) {
7882
- throw new ValidationError("Failed to generate MCP URL", { cause: error });
7883
- }
7884
- const responseResult = ComposioGenerateURLResponseSchema.safeParse(urlResponse);
7885
- if (responseResult.error) throw new ValidationError("Failed to parse MCP URL generation response", { cause: responseResult.error });
7886
- return transformMcpGenerateUrlResponse(urlResponse);
7887
- }
7888
- /**
7889
- * Transform MCP URL response into the appropriate format.
7890
- * If the provider has a custom transform method, use it.
7891
- * Otherwise, use the default transformation.
7892
- *
7893
- * @param data - The MCP URL response data (in camelCase)
7894
- * @param serverName - Name of the MCP server
7895
-
7896
- * @returns Transformed response in appropriate format
7897
- * @deprecated
7898
- */
7899
- wrapMcpServerResponse(data, serverName, connectedAccountIds, userIds, toolkits) {
7900
- if (this.provider && typeof this.provider.wrapMcpServerResponse === "function") {
7901
- let snakeCaseData;
7902
- if (data.connectedAccountUrls?.length) snakeCaseData = data.connectedAccountUrls.map((url, index) => ({
7903
- name: serverName + "-" + connectedAccountIds?.[index],
7904
- url
7905
- }));
7906
- else if (data.userIdsUrl?.length) snakeCaseData = data.userIdsUrl.map((url, index) => ({
7907
- name: serverName + "-" + userIds?.[index],
7908
- url
7909
- }));
7910
- else snakeCaseData = [{
7911
- name: serverName,
7912
- url: data.mcpUrl
7913
- }];
7914
- return this.provider.wrapMcpServerResponse(snakeCaseData);
7915
- }
7916
- if (connectedAccountIds?.length && data.connectedAccountUrls) return data.connectedAccountUrls.map((url, index) => ({
7917
- url: new URL(url),
7918
- name: `${serverName}-${connectedAccountIds[index]}`,
7919
- toolkit: toolkits?.[index]
7920
- }));
7921
- else if (userIds?.length && data.userIdsUrl) return data.userIdsUrl.map((url, index) => ({
7922
- url: new URL(url),
7923
- name: `${serverName}-${userIds[index]}`,
7924
- toolkit: toolkits?.[index]
7925
- }));
7926
- return {
7927
- url: new URL(data.mcpUrl),
7928
- name: serverName
7929
- };
7930
- }
7931
- /**
7932
- * Get details of a specific MCP server by name
7933
- * @param {string} name - Server name
7934
- * @returns {Promise<McpRetrieveResponse>} Server details
7935
- * @throws {ValidationError} If no server found with the given name
7936
- * @throws {ValidationError} If multiple servers found with the same name
7937
- *
7938
- * @example
7939
- * ```typescript
7940
- * const serverDetails = await composio.mcp.getByName('my-gmail-server');
7941
- * ```
7942
- */
7943
- async getByName(serverName) {
7944
- if (!serverName) throw new ValidationError("Server name is required", {});
7945
- let listResponse;
7946
- try {
7947
- listResponse = await this.client.mcp.list({
7948
- name: serverName,
7949
- limit: 10
7950
- });
7951
- } catch (error) {
7952
- logger_default.error(error);
7953
- throw new ValidationError("Failed to search MCP servers by name", { cause: error });
7954
- }
7955
- const listResponseResult = ComposioMcpListResponseSchema.safeParse(listResponse);
7956
- if (listResponseResult.error) throw new ValidationError("Failed to parse MCP server list response", { cause: listResponseResult.error });
7957
- const servers = listResponse.items || [];
7958
- if (servers.length === 0) throw new ValidationError(`MCP server with name '${serverName}' not found`, { meta: { serverName } });
7959
- return this.get(servers[0].id);
7960
- }
7961
- };
7962
-
7963
7379
  //#endregion
7964
7380
  exports.AuthConfigCreationToolAccessConfigSchema = AuthConfigCreationToolAccessConfigSchema;
7965
7381
  exports.AuthConfigErrorCodes = AuthConfigErrorCodes;