@composio/core 0.3.3 → 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.3";
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,31 +6873,19 @@ 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);
6831
6880
  this.files = new Files(this.client);
6832
6881
  this.connectedAccounts = new ConnectedAccounts(this.client);
6833
6882
  this.toolRouter = new ToolRouter(this.client, this.config);
6834
- this.toolRouter.create.bind(this.toolRouter);
6835
- this.toolRouter.use.bind(this.toolRouter);
6836
6883
  /**
6837
6884
  * Initialize tool router methods
6885
+ * Properly bind the methods to maintain the correct 'this' context
6838
6886
  */
6839
- this.create = this.toolRouter.create;
6840
- this.use = this.toolRouter.use;
6841
- /**
6842
- * Initialize Experimental features
6843
- */
6844
- this.experimental = {
6845
- create: async (userId, routerConfig) => {
6846
- return this.toolRouter.create(userId, routerConfig);
6847
- },
6848
- use: async (id) => {
6849
- return this.toolRouter.use(id);
6850
- }
6851
- };
6887
+ this.create = this.toolRouter.create.bind(this.toolRouter);
6888
+ this.use = this.toolRouter.use.bind(this.toolRouter);
6852
6889
  /**
6853
6890
  * Initialize the client telemetry.
6854
6891
  */
@@ -7339,628 +7376,6 @@ const ComposioMcpUpdateResponseSchema = zod_v3.z.object({
7339
7376
  tools: zod_v3.z.array(zod_v3.z.string()).optional()
7340
7377
  });
7341
7378
 
7342
- //#endregion
7343
- //#region src/utils/transformers/mcp.ts
7344
- /**
7345
- * Transform MCP create response from snake_case to camelCase
7346
- */
7347
- function transformMcpCreateResponse(response) {
7348
- const result = CustomCreateResponseSchema.safeParse({
7349
- id: response.id,
7350
- name: response.name,
7351
- createdAt: response.created_at,
7352
- updatedAt: response.updated_at,
7353
- status: response.status
7354
- });
7355
- if (!result.success) throw new ValidationError("Failed to parse MCP create response", { cause: result.error });
7356
- return result.data;
7357
- }
7358
- /**
7359
- * Transform MCP list response from snake_case to camelCase
7360
- */
7361
- function transformMcpListResponse(response) {
7362
- const transformedItems = response.items?.map((item) => ({
7363
- id: item.id,
7364
- name: item.name,
7365
- createdAt: item.created_at,
7366
- updatedAt: item.updated_at,
7367
- status: item.status
7368
- }));
7369
- const result = McpListResponseSchema.safeParse({ items: transformedItems });
7370
- if (!result.success) throw new ValidationError("Failed to parse MCP list response", { cause: result.error });
7371
- return result.data;
7372
- }
7373
- /**
7374
- * Transform MCP retrieve response from snake_case to camelCase
7375
- */
7376
- function transformMcpRetrieveResponse(response) {
7377
- const result = McpRetrieveResponseSchema.safeParse({
7378
- id: response.id,
7379
- name: response.name,
7380
- createdAt: response.created_at,
7381
- updatedAt: response.updated_at,
7382
- status: response.status,
7383
- toolkits: response.toolkits,
7384
- tools: response.allowed_tools,
7385
- managedAuthViaComposio: response.managed_auth_via_composio,
7386
- authConfigIds: response.auth_config_ids,
7387
- mcpUrl: response.mcp_url,
7388
- commands: response.commands
7389
- });
7390
- if (!result.success) throw new ValidationError("Failed to parse MCP retrieve response", { cause: result.error });
7391
- return result.data;
7392
- }
7393
- /**
7394
- * Transform MCP delete response from snake_case to camelCase
7395
- */
7396
- function transformMcpDeleteResponse(response) {
7397
- const result = McpDeleteResponseSchema.safeParse({
7398
- id: response.id,
7399
- deleted: response.deleted,
7400
- message: response.message
7401
- });
7402
- if (!result.success) throw new ValidationError("Failed to parse MCP delete response", { cause: result.error });
7403
- return result.data;
7404
- }
7405
- /**
7406
- * Transform MCP update response from snake_case to camelCase
7407
- */
7408
- function transformMcpUpdateResponse(response) {
7409
- const result = McpUpdateResponseSchema.safeParse({
7410
- id: response.id,
7411
- name: response.name,
7412
- createdAt: response.created_at,
7413
- updatedAt: response.updated_at,
7414
- status: response.status,
7415
- toolkits: response.toolkits,
7416
- tools: response.tools
7417
- });
7418
- if (!result.success) throw new ValidationError("Failed to parse MCP update response", { cause: result.error });
7419
- return result.data;
7420
- }
7421
- /**
7422
- * Transform MCP generate URL response from snake_case to camelCase
7423
- */
7424
- function transformMcpGenerateUrlResponse(response) {
7425
- const result = GenerateURLResponseSchema.safeParse({
7426
- connectedAccountUrls: response.connected_account_urls,
7427
- userIdsUrl: response.user_ids_url,
7428
- mcpUrl: response.mcp_url
7429
- });
7430
- if (!result.success) throw new ValidationError("Failed to parse MCP generate URL response", { cause: result.error });
7431
- return result.data;
7432
- }
7433
-
7434
- //#endregion
7435
- //#region src/models/MCP.ts
7436
- /**
7437
- * MCP (Model Control Protocol) class
7438
- * Handles MCP server operations
7439
- */
7440
- var MCP = class {
7441
- client;
7442
- toolkits;
7443
- provider;
7444
- constructor(client, provider) {
7445
- this.client = client;
7446
- this.provider = provider;
7447
- this.toolkits = new Toolkits(client);
7448
- telemetry.instrument(this, "MCP");
7449
- }
7450
- /**
7451
- * Validates toolkit configurations using Zod schema
7452
- * @private
7453
- * @param {MCPToolkitConfig[]} toolkitConfigs - Array of toolkit configurations to validate
7454
- * @param {MCPAuthOptions} [authOptions] - Authentication options to validate
7455
- * @throws {ValidationError} If validation fails
7456
- */
7457
- validateInputs(toolkitConfigs, authOptions) {
7458
- const toolkitConfigsResult = MCPToolkitConfigsArraySchema.safeParse(toolkitConfigs);
7459
- if (toolkitConfigsResult.error) throw new ValidationError("Failed to parse toolkit configurations", { cause: toolkitConfigsResult.error });
7460
- if (authOptions !== void 0) {
7461
- const authOptionsResult = MCPAuthOptionsSchema.safeParse(authOptions);
7462
- if (authOptionsResult.error) throw new ValidationError("Failed to parse auth options", { cause: authOptionsResult.error });
7463
- }
7464
- }
7465
- /**
7466
- * Create a new MCP server
7467
- * @param {Object} params - Parameters for creating the MCP server
7468
- * @param {Array} params.authConfig - Array of auth configurations with id and allowed tools
7469
- * @param {Object} params.options - Server creation options
7470
- * @param {string} params.options.name - Unique name for the MCP server
7471
- * @param {boolean} [params.options.isChatAuth] - Whether to use chat-based authentication
7472
- * @returns {Promise<McpServerCreateResponse<TMcpResponse>>} Created server details with instance getter
7473
- *
7474
- * @example
7475
- * ```typescript
7476
- * const server = await composio.mcp.create("personal-mcp-server", [
7477
- * {
7478
- * authConfigId: "ac_xyz",
7479
- * allowedTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"]
7480
- * }
7481
- * ],
7482
- * {
7483
- * isChatAuth: true
7484
- * }
7485
- * });
7486
- *
7487
- * // Use convenience method on response
7488
- * const urls = await server.getServer({
7489
- * userId: "user123"
7490
- * });
7491
- * ```
7492
- */
7493
- async create(name, serverConfig, options) {
7494
- if (!serverConfig || serverConfig.length === 0) throw new ValidationError("At least one auth config is required", {});
7495
- if (!name) throw new ValidationError("Server name is required", {});
7496
- try {
7497
- const mcpServer = await this.getByName(name);
7498
- const authConfigs = mcpServer.authConfigIds?.sort();
7499
- const sortedCurrentAuthConfigs = serverConfig.map((config) => config.authConfigId).sort();
7500
- 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 } });
7501
- const tools = mcpServer.tools?.sort();
7502
- const sortedCurrentTools = serverConfig.flatMap((config) => config.allowedTools).sort();
7503
- 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 } });
7504
- const toolkits$1 = (await Promise.all(serverConfig.map((config) => this.client.authConfigs.retrieve(config.authConfigId)))).map((config) => config.toolkit.slug);
7505
- const camelCaseResponse$1 = transformMcpCreateResponse({
7506
- id: mcpServer.id,
7507
- name: mcpServer.name,
7508
- auth_config_ids: serverConfig.map((config) => config.authConfigId),
7509
- allowed_tools: serverConfig.flatMap((config) => config.allowedTools),
7510
- managed_auth_via_composio: options.isChatAuth || false,
7511
- commands: mcpServer.commands,
7512
- created_at: mcpServer.createdAt,
7513
- updated_at: mcpServer.updatedAt,
7514
- mcp_url: mcpServer.mcpUrl
7515
- });
7516
- return {
7517
- ...camelCaseResponse$1,
7518
- toolkits: toolkits$1,
7519
- getServer: async (params) => {
7520
- return this.getServer(camelCaseResponse$1.id, params.userId || "", { isChatAuth: options.isChatAuth });
7521
- }
7522
- };
7523
- } catch (error) {
7524
- if (error instanceof ValidationError && !error.message.includes("not found")) throw error;
7525
- }
7526
- const toolkits = (await Promise.all(serverConfig.map((config) => this.client.authConfigs.retrieve(config.authConfigId)))).map((config) => config.toolkit.slug);
7527
- let mcpServerCreatedResponse;
7528
- try {
7529
- mcpServerCreatedResponse = await this.client.mcp.custom.create({
7530
- name,
7531
- toolkits,
7532
- custom_tools: serverConfig.flatMap((config) => config.allowedTools),
7533
- managed_auth_via_composio: options.isChatAuth || false,
7534
- auth_config_ids: serverConfig.map((config) => config.authConfigId)
7535
- });
7536
- } catch (error) {
7537
- throw new ValidationError("Failed to create MCP server", { cause: error });
7538
- }
7539
- const serverResponseResult = ComposioCustomCreateResponseSchema.safeParse(mcpServerCreatedResponse);
7540
- if (serverResponseResult.error) throw new ValidationError("Failed to parse MCP server creation response", { cause: serverResponseResult.error });
7541
- const camelCaseResponse = transformMcpCreateResponse(mcpServerCreatedResponse);
7542
- return {
7543
- ...camelCaseResponse,
7544
- toolkits,
7545
- getServer: async (params) => {
7546
- return this.getServer(camelCaseResponse.id, params.userId || "", { isChatAuth: options.isChatAuth });
7547
- }
7548
- };
7549
- }
7550
- /**
7551
- * Get the connection status of a user for an MCP server
7552
- *
7553
- * Checks whether a user has the necessary connected accounts to use all toolkits
7554
- * configured in the specified MCP server. Returns both overall connection status
7555
- * and individual status for each toolkit.
7556
- *
7557
- * @param {Object} params - Parameters for checking connection status
7558
- * @param {string} params.id - The UUID of the MCP server to check
7559
- * @param {string} params.userId - The ID of the user to check connection status for
7560
- * @returns {Promise<McpUserConnectionStatus>} Complete connection status including:
7561
- * - `type`: Overall status (CONNECTED if all toolkits are connected, DISCONNECTED otherwise)
7562
- * - `connected`: Boolean indicating if user can use the MCP server
7563
- * - `connectedToolkits`: Record mapping each toolkit name to its individual connection status
7564
- *
7565
- * @throws {ValidationError} When MCP server has no toolkits configured
7566
- * @throws {ValidationError} When MCP server retrieval fails
7567
- *
7568
- * @example
7569
- * ```typescript
7570
- * // Check if user can access an MCP server with Gmail and Slack toolkits
7571
- * const connectionStatus = await composio.mcp.getUserConnectionStatus('user123', 'mcp-server-uuid');
7572
- *
7573
- * if (connectionStatus.connected) {
7574
- * console.log('User can access all required toolkits');
7575
- * // connectionStatus.type === ConnectionStatus.CONNECTED
7576
- * } else {
7577
- * console.log('User is missing some toolkit connections');
7578
- * // Check individual toolkit statuses
7579
- * Object.entries(connectionStatus.connectedToolkits).forEach(([toolkit, status]) => {
7580
- * if (!status.connected) {
7581
- * console.log(`Missing connection for toolkit: ${toolkit}`);
7582
- * }
7583
- * });
7584
- * }
7585
- * ```
7586
- *
7587
- * @example
7588
- * ```typescript
7589
- * // Example response when user has Gmail connected but missing Slack
7590
- * {
7591
- * type: ConnectionStatus.DISCONNECTED,
7592
- * connected: false,
7593
- * connectedToolkits: {
7594
- * GMAIL: {
7595
- * type: ConnectionStatus.CONNECTED,
7596
- * connected: true,
7597
- * toolkit: 'GMAIL',
7598
- * connectedAccountId: 'conn_gmail_123'
7599
- * },
7600
- * SLACK: {
7601
- * type: ConnectionStatus.DISCONNECTED,
7602
- * connected: false,
7603
- * toolkit: 'SLACK'
7604
- * }
7605
- * }
7606
- * }
7607
- * ```
7608
- */
7609
- async getUserConnectionStatus(userId, serverId) {
7610
- const serverDetails = await this.get(serverId);
7611
- if (!serverDetails.toolkits || serverDetails.toolkits.length === 0) throw new ValidationError("MCP server has no toolkits configured", { meta: { serverId } });
7612
- const connectedAccounts = await this.client.connectedAccounts.list({
7613
- user_ids: [userId],
7614
- toolkit_slugs: serverDetails.toolkits.map((toolkit) => toolkit.toLowerCase()),
7615
- statuses: ["ACTIVE"]
7616
- });
7617
- const connectedAccountsByToolkit = /* @__PURE__ */ new Map();
7618
- connectedAccounts.items?.forEach((account) => {
7619
- connectedAccountsByToolkit.set(account.toolkit.slug.toLowerCase(), account.id);
7620
- });
7621
- const connectedToolkits = {};
7622
- let allToolkitsConnected = true;
7623
- for (const toolkit of serverDetails.toolkits) {
7624
- const connectedAccountId = connectedAccountsByToolkit.get(toolkit.toLowerCase());
7625
- if (connectedAccountId) connectedToolkits[toolkit] = {
7626
- type: ConnectionStatus.CONNECTED,
7627
- connected: true,
7628
- toolkit,
7629
- connectedAccountId
7630
- };
7631
- else {
7632
- connectedToolkits[toolkit] = {
7633
- type: ConnectionStatus.DISCONNECTED,
7634
- connected: false,
7635
- toolkit
7636
- };
7637
- allToolkitsConnected = false;
7638
- }
7639
- }
7640
- if (allToolkitsConnected) return {
7641
- type: ConnectionStatus.CONNECTED,
7642
- connected: true,
7643
- connectedToolkits
7644
- };
7645
- else return {
7646
- type: ConnectionStatus.DISCONNECTED,
7647
- connected: false,
7648
- connectedToolkits
7649
- };
7650
- }
7651
- /**
7652
- * Get the connection parameters for a toolkit
7653
- * @param {string} serverId - The UUID of the MCP server
7654
- * @param {string} toolkit - The toolkit to get connection parameters for
7655
- * @returns {Promise<ToolkitAuthFieldsResponse>} Connection parameters for the toolkit
7656
- */
7657
- async getConnectionParams(serverId, toolkit) {
7658
- const mcpServerDetails = await this.get(serverId);
7659
- const authConfig = (mcpServerDetails.authConfigIds ? await Promise.all(mcpServerDetails.authConfigIds.map((id) => this.client.authConfigs.retrieve(id))) : []).find((config) => config.toolkit.slug === toolkit);
7660
- if (!authConfig) throw new ValidationError("Auth config not found", { meta: {
7661
- serverId,
7662
- toolkit
7663
- } });
7664
- return await this.toolkits.getConnectedAccountInitiationFields(toolkit, authConfig.auth_scheme);
7665
- }
7666
- /**
7667
- * Authorize a user for a toolkit
7668
- * @param {string} serverId - The UUID of the MCP server
7669
- * @param {string} userId - The ID of the user to authorize
7670
- * @param {string} toolkit - The toolkit to authorize
7671
- * @returns {Promise<ConnectionRequest>} Connection request for the toolkit
7672
- */
7673
- async authorize(userId, serverId, toolkit) {
7674
- const authConfigId = (await this.get(serverId)).authConfigIds?.[0];
7675
- return this.toolkits.authorize(userId, toolkit, authConfigId);
7676
- }
7677
- /**
7678
- * Get server URLs for an existing MCP server
7679
- * @param {string} serverId - Server UUID
7680
- * @param {string} userId - User ID to get server URLs for
7681
- * @param {Object} [options] - Additional options for server configuration
7682
- * @param {string[]} [options.limitTools] - Subset of tools to limit (from MCP config)
7683
- * @param {boolean} [options.isChatAuth] - Whether to use chat-based authentication
7684
- * @returns {Promise<TMcpResponse>} Transformed server URLs in provider-specific format
7685
- *
7686
- * @example
7687
- * ```typescript
7688
- * // Get URLs for an existing server with basic user ID
7689
- * const urls = await composio.mcp.getServer("mcp_xyz", "hey@example.com");
7690
- *
7691
- * // Get URLs with additional options
7692
- * const urls = await composio.mcp.getServer("mcp_xyz", "hey@example.com", {
7693
- * limitTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"],
7694
- * isChatAuth: true
7695
- * });
7696
- * ```
7697
- *
7698
- */
7699
- async getServer(serverId, userId, options) {
7700
- const serverDetails = await this.get(serverId);
7701
- if (!userId) throw new ValidationError("User ID is required", {});
7702
- const toolkits = serverDetails.toolkits || [];
7703
- const connectedAccountIds = (await Promise.all(toolkits.map((toolkit) => this.client.connectedAccounts.list({
7704
- user_ids: [userId],
7705
- toolkit_slugs: [toolkit],
7706
- statuses: ["ACTIVE"]
7707
- }).then((res) => res.items?.[0]?.id)))).filter(Boolean);
7708
- let data;
7709
- try {
7710
- data = await this.client.mcp.generate.url({
7711
- user_ids: [userId],
7712
- connected_account_ids: [],
7713
- mcp_server_id: serverId,
7714
- managed_auth_by_composio: options?.isChatAuth ?? serverDetails.managedAuthViaComposio ?? false
7715
- });
7716
- } catch (error) {
7717
- throw new ValidationError("Failed to generate MCP server URL", { cause: error });
7718
- }
7719
- const urlResponseResult = ComposioGenerateURLResponseSchema.safeParse(data);
7720
- if (urlResponseResult.error) throw new ValidationError("Failed to parse MCP URL generation response", { cause: urlResponseResult.error });
7721
- const camelCaseData = transformMcpGenerateUrlResponse(data);
7722
- return this.wrapMcpServerResponse(camelCaseData, serverDetails.name, connectedAccountIds, [userId], toolkits);
7723
- }
7724
- /**
7725
- * List MCP server configurations with filtering options
7726
- * @param {Object} options - Filtering and pagination options
7727
- * @param {number} [options.page] - Page number for pagination
7728
- * @param {number} [options.limit] - Number of items per page
7729
- * @param {string[]} [options.toolkits] - Filter servers by toolkit names
7730
- * @param {string[]} [options.authConfigs] - Filter servers by auth config IDs
7731
- * @param {string} [options.name] - Filter servers by name
7732
- * @param {string} [options.user] - Filter servers by user ID
7733
- * @returns {Promise<McpListResponse>} List of MCP servers matching the filters
7734
- *
7735
- * @example
7736
- * ```typescript
7737
- * // List all servers with pagination
7738
- * const servers = await composio.mcp.list({
7739
- * page: 1,
7740
- * limit: 10
7741
- * });
7742
- *
7743
- * // List Gmail and Supabase servers
7744
- * const filteredServers = await composio.mcp.list({
7745
- * toolkits: ['GMAIL', 'SUPABASE'],
7746
- * authConfigIds: ['auth_123', 'auth_456']
7747
- * });
7748
- * ```
7749
- */
7750
- async list(options) {
7751
- let listResponse;
7752
- try {
7753
- listResponse = await this.client.mcp.list({
7754
- page_no: options.page || 1,
7755
- limit: options.limit || 10,
7756
- toolkits: options?.toolkits?.join(",") || void 0,
7757
- auth_config_ids: options?.authConfigs?.join(",") || void 0,
7758
- name: options?.name
7759
- });
7760
- } catch (error) {
7761
- throw new ValidationError("Failed to list MCP servers", { cause: error });
7762
- }
7763
- const listResponseResult = ComposioMcpListResponseSchema.safeParse(listResponse);
7764
- if (listResponseResult.error) throw new ValidationError("Failed to parse MCP server list response", { cause: listResponseResult.error });
7765
- return transformMcpListResponse(listResponse);
7766
- }
7767
- /**
7768
- * Get details of a specific MCP server
7769
- * @param {string} serverId - Server UUID
7770
- * @returns {Promise<McpRetrieveResponse>} Server details
7771
- *
7772
- * @example
7773
- * ```typescript
7774
- * const serverDetails = await composio.mcp.get('server-uuid');
7775
- * ```
7776
- */
7777
- async get(serverId) {
7778
- let retrieveResponse;
7779
- try {
7780
- retrieveResponse = await this.client.mcp.retrieve(serverId);
7781
- } catch (error) {
7782
- throw new ValidationError("Failed to retrieve MCP server", { cause: error });
7783
- }
7784
- const retrieveResponseResult = McpRetrieveResponseSchema.safeParse({
7785
- ...retrieveResponse,
7786
- mcpUrl: retrieveResponse.mcp_url
7787
- });
7788
- if (retrieveResponseResult.error) throw new ValidationError("Failed to parse MCP server retrieve response", { cause: retrieveResponseResult.error });
7789
- return transformMcpRetrieveResponse(retrieveResponse);
7790
- }
7791
- /**
7792
- * Delete an MCP server
7793
- * @param {string} serverId - Server UUID
7794
- * @returns {Promise<McpDeleteResponse>} Deletion response
7795
- *
7796
- * @example
7797
- * ```typescript
7798
- * const result = await composio.mcp.delete('server-uuid');
7799
- * ```
7800
- */
7801
- async delete(serverId) {
7802
- let deleteResponse;
7803
- try {
7804
- deleteResponse = await this.client.mcp.delete(serverId);
7805
- } catch (error) {
7806
- throw new ValidationError("Failed to delete MCP server", { cause: error });
7807
- }
7808
- const deleteResponseResult = ComposioMcpDeleteResponseSchema.safeParse(deleteResponse);
7809
- if (deleteResponseResult.error) throw new ValidationError("Failed to parse MCP server delete response", { cause: deleteResponseResult.error });
7810
- return transformMcpDeleteResponse(deleteResponse);
7811
- }
7812
- /**
7813
- * Update an MCP server configuration
7814
- * @param {string} id - Server UUID
7815
- * @param {string} name - New unique name for the server
7816
- * @param {MCPToolkitConfig[]} toolkitConfigs - Array of toolkit configurations
7817
- * @param {MCPAuthOptions} [authOptions] - Updated authentication options
7818
- * @returns {Promise<McpUpdateResponse>} Updated server details
7819
- *
7820
- * @example
7821
- * ```typescript
7822
- * const updatedServer = await composio.mcp.update(
7823
- * "server-uuid",
7824
- * "my-updated-server",
7825
- * [
7826
- * {
7827
- * toolkit: "GMAIL",
7828
- * authConfigId: "ac_sdhkjfhjksdk",
7829
- * allowedTools: ["GMAIL_FETCH_EMAILS"],
7830
- * },
7831
- * ],
7832
- * {
7833
- * isChatAuth: true,
7834
- * }
7835
- * );
7836
- * ```
7837
- */
7838
- async update(serverId, name, toolkitConfigs, authOptions) {
7839
- this.validateInputs(toolkitConfigs, authOptions);
7840
- const toolkits = toolkitConfigs.map((config) => config.toolkit);
7841
- let updateResponse;
7842
- try {
7843
- updateResponse = await this.client.mcp.update(serverId, {
7844
- name,
7845
- toolkits,
7846
- allowed_tools: toolkitConfigs.flatMap((config) => config.allowedTools),
7847
- managed_auth_via_composio: authOptions?.isChatAuth || false
7848
- });
7849
- } catch (error) {
7850
- throw new ValidationError("Failed to update MCP server", { cause: error });
7851
- }
7852
- const updateResponseResult = ComposioMcpUpdateResponseSchema.safeParse(updateResponse);
7853
- if (updateResponseResult.error) throw new ValidationError("Failed to parse MCP server update response", { cause: updateResponseResult.error });
7854
- return transformMcpUpdateResponse(updateResponse);
7855
- }
7856
- /**
7857
- * Generate URL for an MCP server
7858
- * @param {string} serverId - Server UUID
7859
- * @param {GenerateURLParams} params - Parameters for URL generation
7860
- * @returns {Promise<GenerateURLResponse>} Generated URL response
7861
- *
7862
- * @example
7863
- * ```typescript
7864
- * const urlResponse = await composio.mcp.generateUrl('server-uuid', {
7865
- * userIds: ['user123'],
7866
- * connectedAccountIds: ['account456'],
7867
- * isChatAuth: true
7868
- * });
7869
- * ```
7870
- */
7871
- async generateUrl(serverId, params) {
7872
- const paramsResult = GenerateURLParamsSchema.safeParse(params);
7873
- if (paramsResult.error) throw new ValidationError("Failed to parse generateUrl parameters", { cause: paramsResult.error });
7874
- let urlResponse;
7875
- try {
7876
- urlResponse = await this.client.mcp.generate.url({
7877
- mcp_server_id: serverId,
7878
- user_ids: params.userIds,
7879
- connected_account_ids: params.connectedAccountIds,
7880
- managed_auth_by_composio: params.composioManagedAuth
7881
- });
7882
- } catch (error) {
7883
- throw new ValidationError("Failed to generate MCP URL", { cause: error });
7884
- }
7885
- const responseResult = ComposioGenerateURLResponseSchema.safeParse(urlResponse);
7886
- if (responseResult.error) throw new ValidationError("Failed to parse MCP URL generation response", { cause: responseResult.error });
7887
- return transformMcpGenerateUrlResponse(urlResponse);
7888
- }
7889
- /**
7890
- * Transform MCP URL response into the appropriate format.
7891
- * If the provider has a custom transform method, use it.
7892
- * Otherwise, use the default transformation.
7893
- *
7894
- * @param data - The MCP URL response data (in camelCase)
7895
- * @param serverName - Name of the MCP server
7896
-
7897
- * @returns Transformed response in appropriate format
7898
- * @deprecated
7899
- */
7900
- wrapMcpServerResponse(data, serverName, connectedAccountIds, userIds, toolkits) {
7901
- if (this.provider && typeof this.provider.wrapMcpServerResponse === "function") {
7902
- let snakeCaseData;
7903
- if (data.connectedAccountUrls?.length) snakeCaseData = data.connectedAccountUrls.map((url, index) => ({
7904
- name: serverName + "-" + connectedAccountIds?.[index],
7905
- url
7906
- }));
7907
- else if (data.userIdsUrl?.length) snakeCaseData = data.userIdsUrl.map((url, index) => ({
7908
- name: serverName + "-" + userIds?.[index],
7909
- url
7910
- }));
7911
- else snakeCaseData = [{
7912
- name: serverName,
7913
- url: data.mcpUrl
7914
- }];
7915
- return this.provider.wrapMcpServerResponse(snakeCaseData);
7916
- }
7917
- if (connectedAccountIds?.length && data.connectedAccountUrls) return data.connectedAccountUrls.map((url, index) => ({
7918
- url: new URL(url),
7919
- name: `${serverName}-${connectedAccountIds[index]}`,
7920
- toolkit: toolkits?.[index]
7921
- }));
7922
- else if (userIds?.length && data.userIdsUrl) return data.userIdsUrl.map((url, index) => ({
7923
- url: new URL(url),
7924
- name: `${serverName}-${userIds[index]}`,
7925
- toolkit: toolkits?.[index]
7926
- }));
7927
- return {
7928
- url: new URL(data.mcpUrl),
7929
- name: serverName
7930
- };
7931
- }
7932
- /**
7933
- * Get details of a specific MCP server by name
7934
- * @param {string} name - Server name
7935
- * @returns {Promise<McpRetrieveResponse>} Server details
7936
- * @throws {ValidationError} If no server found with the given name
7937
- * @throws {ValidationError} If multiple servers found with the same name
7938
- *
7939
- * @example
7940
- * ```typescript
7941
- * const serverDetails = await composio.mcp.getByName('my-gmail-server');
7942
- * ```
7943
- */
7944
- async getByName(serverName) {
7945
- if (!serverName) throw new ValidationError("Server name is required", {});
7946
- let listResponse;
7947
- try {
7948
- listResponse = await this.client.mcp.list({
7949
- name: serverName,
7950
- limit: 10
7951
- });
7952
- } catch (error) {
7953
- logger_default.error(error);
7954
- throw new ValidationError("Failed to search MCP servers by name", { cause: error });
7955
- }
7956
- const listResponseResult = ComposioMcpListResponseSchema.safeParse(listResponse);
7957
- if (listResponseResult.error) throw new ValidationError("Failed to parse MCP server list response", { cause: listResponseResult.error });
7958
- const servers = listResponse.items || [];
7959
- if (servers.length === 0) throw new ValidationError(`MCP server with name '${serverName}' not found`, { meta: { serverName } });
7960
- return this.get(servers[0].id);
7961
- }
7962
- };
7963
-
7964
7379
  //#endregion
7965
7380
  exports.AuthConfigCreationToolAccessConfigSchema = AuthConfigCreationToolAccessConfigSchema;
7966
7381
  exports.AuthConfigErrorCodes = AuthConfigErrorCodes;