Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Fix type issues

haxzie9f716864ea78
diff --git a/packages/core/src/errors/ValidationError.ts b/packages/core/src/errors/ValidationError.ts
index 93f337e41..5b51374fe 100644
--- a/packages/core/src/errors/ValidationError.ts
+++ b/packages/core/src/errors/ValidationError.ts
@@ -41,5 +41,6 @@ export class ValidationError extends ComposioError {
cause: zodErrorInstance,
});
this.zodError = zodErrorInstance;
+ this.name = 'ValidationError';
}
}
diff --git a/packages/core/src/models/AuthConfigs.ts b/packages/core/src/models/AuthConfigs.ts
index cbf760948..4e18f9af8 100644
--- a/packages/core/src/models/AuthConfigs.ts
+++ b/packages/core/src/models/AuthConfigs.ts
@@ -50,6 +50,18 @@ export class AuthConfigs {
return this.client;
}
+ /**
+ * Transforms an auth config response from API format to SDK format.
+ *
+ * This method converts property names from snake_case to camelCase and reorganizes
+ * the data structure to match the SDK's standardized format for auth configurations.
+ *
+ * @param {ComposioAuthConfigRetrieveResponse} authConfig - The raw API response to transform
+ * @returns {AuthConfigRetrieveResponse} The transformed auth config data
+ * @throws {ValidationError} If the response fails validation against the expected schema
+ *
+ * @private
+ */
private parseAuthConfigRetrieveResponse(
authConfig: ComposioAuthConfigRetrieveResponse
): AuthConfigRetrieveResponse {
@@ -78,10 +90,30 @@ export class AuthConfigs {
}
/**
- * List all auth configs
- * @param {AuthConfigListParams} query - Query parameters for filtering auth configs
- * @param {RequestOptions} options - Request options
- * @returns {Promise<AuthConfigListResponse>} List of auth configs
+ * Lists authentication configurations based on provided filter criteria.
+ *
+ * This method retrieves auth configs from the Composio API, transforms them to the SDK format,
+ * and supports filtering by various parameters.
+ *
+ * @param {AuthConfigListParams} [query] - Optional query parameters for filtering auth configs
+ * @returns {Promise<AuthConfigListResponse>} A paginated list of auth configurations
+ * @throws {ValidationError} If the query parameters or response fail validation
+ *
+ * @example
+ * ```typescript
+ * // List all auth configs
+ * const allConfigs = await composio.authConfigs.list();
+ *
+ * // List auth configs for a specific toolkit
+ * const githubConfigs = await composio.authConfigs.list({
+ * toolkitSlug: 'github'
+ * });
+ *
+ * // List Composio-managed auth configs
+ * const managedConfigs = await composio.authConfigs.list({
+ * isComposioManaged: true
+ * });
+ * ```
*/
async list(query?: AuthConfigListParams): Promise<AuthConfigListResponse> {
const parsedQuery = query ? AuthConfigListParamsSchema.parse(query) : undefined;
@@ -147,10 +179,23 @@ export class AuthConfigs {
}
/**
- * Get an auth config by nanoid
- * @param {string} nanoid - Unique identifier of the auth config
- * @param {RequestOptions} options - Request options
- * @returns {Promise<AuthConfigRetrieveResponse>} Auth config details
+ * Retrieves a specific authentication configuration by its ID.
+ *
+ * This method fetches detailed information about a single auth config
+ * and transforms the response to the SDK's standardized format.
+ *
+ * @param {string} nanoid - The unique identifier of the auth config to retrieve
+ * @returns {Promise<AuthConfigRetrieveResponse>} The auth config details
+ * @throws {Error} If the auth config cannot be found or an API error occurs
+ * @throws {ValidationError} If the response fails validation
+ *
+ * @example
+ * ```typescript
+ * // Get an auth config by ID
+ * const authConfig = await composio.authConfigs.get('auth_abc123');
+ * console.log(authConfig.name); // e.g., 'GitHub Auth'
+ * console.log(authConfig.toolkit.slug); // e.g., 'github'
+ * ```
*/
async get(nanoid: string): Promise<AuthConfigRetrieveResponse> {
const result = await this.client.authConfigs.retrieve(nanoid);
@@ -158,11 +203,34 @@ export class AuthConfigs {
}
/**
- * Update an auth config
- * @param {string} nanoid - Unique identifier of the auth config to update
- * @param {AuthConfigUpdateParams} data - Data to update
- * @param {RequestOptions} options - Request options
- * @returns {Promise<AuthConfigUpdateResponse>} Updated auth config
+ * Updates an existing authentication configuration.
+ *
+ * This method allows you to modify properties of an auth config such as credentials,
+ * scopes, or tool restrictions. The update type (custom or default) determines which
+ * fields can be updated.
+ *
+ * @param {string} nanoid - The unique identifier of the auth config to update
+ * @param {AuthConfigUpdateParams} data - The data to update, which can be either custom or default type
+ * @returns {Promise<AuthConfigUpdateResponse>} The updated auth config
+ * @throws {ValidationError} If the update parameters are invalid
+ * @throws {Error} If the auth config cannot be found or updated
+ *
+ * @example
+ * ```typescript
+ * // Update a custom auth config with new credentials
+ * const updatedConfig = await composio.authConfigs.update('auth_abc123', {
+ * type: 'custom',
+ * credentials: {
+ * apiKey: 'new-api-key-value'
+ * }
+ * });
+ *
+ * // Update a default auth config with new scopes
+ * const updatedConfig = await composio.authConfigs.update('auth_abc123', {
+ * type: 'default',
+ * scopes: ['read:user', 'repo']
+ * });
+ * ```
*/
async update(nanoid: string, data: AuthConfigUpdateParams): Promise<AuthConfigUpdateResponse> {
const parsedData = AuthConfigUpdateParamsSchema.safeParse(data);
@@ -186,21 +254,46 @@ export class AuthConfigs {
}
/**
- * Delete an auth config
- * @param {string} nanoid - Unique identifier of the auth config to delete
- * @param {RequestOptions} options - Request options
- * @returns {Promise<AuthConfigDeleteResponse>} Response from deletion
+ * Deletes an authentication configuration.
+ *
+ * This method permanently removes an auth config from the Composio platform.
+ * This action cannot be undone and will prevent any connected accounts that use
+ * this auth config from functioning.
+ *
+ * @param {string} nanoid - The unique identifier of the auth config to delete
+ * @returns {Promise<AuthConfigDeleteResponse>} The deletion response
+ * @throws {Error} If the auth config doesn't exist or cannot be deleted
+ *
+ * @example
+ * ```typescript
+ * // Delete an auth config
+ * await composio.authConfigs.delete('auth_abc123');
+ * ```
*/
async delete(nanoid: string): Promise<AuthConfigDeleteResponse> {
return this.client.authConfigs.delete(nanoid);
}
/**
- * Update the status of an auth config
- * @param {string} status - The status to update the auth config to
- * @param {string} nanoid - Unique identifier of the auth config
- * @param {RequestOptions} options - Request options
- * @returns {Promise<AuthConfigUpdateStatusResponse>} Updated auth config details
+ * Updates the status of an authentication configuration.
+ *
+ * This method allows you to enable or disable an auth config. When disabled,
+ * the auth config cannot be used to create new connected accounts or authenticate
+ * with third-party services.
+ *
+ * @param {string} status - The status to set ('ENABLED' or 'DISABLED')
+ * @param {string} nanoid - The unique identifier of the auth config
+ * @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
+ * @throws {Error} If the auth config cannot be found or the status cannot be updated
+ *
+ * @example
+ * ```typescript
+ * // Disable an auth config
+ * await composio.authConfigs.updateStatus('DISABLED', 'auth_abc123');
+ *
+ * // Enable an auth config
+ * await composio.authConfigs.updateStatus('ENABLED', 'auth_abc123');
+ * ```
*/
async updateStatus(
status: 'ENABLED' | 'DISABLED',
@@ -210,20 +303,42 @@ export class AuthConfigs {
}
/**
- * Enable an auth config
- * @param {string} nanoid - Unique identifier of the auth config
- * @param {RequestOptions} options - Request options
- * @returns {Promise<AuthConfigUpdateStatusResponse>} Updated auth config details
+ * Enables an authentication configuration.
+ *
+ * This is a convenience method that calls updateStatus with 'ENABLED'.
+ * When enabled, the auth config can be used to create new connected accounts
+ * and authenticate with third-party services.
+ *
+ * @param {string} nanoid - The unique identifier of the auth config to enable
+ * @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
+ * @throws {Error} If the auth config cannot be found or enabled
+ *
+ * @example
+ * ```typescript
+ * // Enable an auth config
+ * await composio.authConfigs.enable('auth_abc123');
+ * ```
*/
async enable(nanoid: string): Promise<AuthConfigUpdateStatusResponse> {
return this.client.authConfigs.updateStatus('ENABLED', { nanoid });
}
/**
- * Disable an auth config
- * @param {string} nanoid - Unique identifier of the auth config
- * @param {RequestOptions} options - Request options
- * @returns {Promise<AuthConfigUpdateStatusResponse>} Updated auth config details
+ * Disables an authentication configuration.
+ *
+ * This is a convenience method that calls updateStatus with 'DISABLED'.
+ * When disabled, the auth config cannot be used to create new connected accounts
+ * or authenticate with third-party services, but existing connections may continue to work.
+ *
+ * @param {string} nanoid - The unique identifier of the auth config to disable
+ * @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
+ * @throws {Error} If the auth config cannot be found or disabled
+ *
+ * @example
+ * ```typescript
+ * // Disable an auth config
+ * await composio.authConfigs.disable('auth_abc123');
+ * ```
*/
async disable(nanoid: string): Promise<AuthConfigUpdateStatusResponse> {
return this.client.authConfigs.updateStatus('DISABLED', { nanoid });
diff --git a/packages/core/src/models/ConnectedAccounts.ts b/packages/core/src/models/ConnectedAccounts.ts
index 39dec20c9..f9236afe6 100644
--- a/packages/core/src/models/ConnectedAccounts.ts
+++ b/packages/core/src/models/ConnectedAccounts.ts
@@ -7,18 +7,22 @@
*/
import ComposioClient from '@composio/client';
import {
- ConnectedAccountListParams,
- ConnectedAccountListResponse,
ConnectedAccountDeleteResponse,
ConnectedAccountRefreshResponse,
ConnectedAccountUpdateStatusParams,
ConnectedAccountUpdateStatusResponse,
+ ConnectedAccountListParams as ConnectedAccountListParamsRaw,
ConnectedAccountRetrieveResponse as ConnectedAccountRetrieveResponseRaw,
+ ConnectedAccountListResponse as ConnectedAccountListResponseRaw,
} from '@composio/client/resources/connected-accounts';
import {
CreateConnectedAccountOptions,
ConnectedAccountRetrieveResponse,
ConnectedAccountRetrieveResponseSchema,
+ ConnectedAccountListParams,
+ ConnectedAccountListParamsSchema,
+ ConnectedAccountListResponse,
+ ConnectedAccountListResponseSchema,
} from '../types/connectedAccounts.types';
import { ConnectionRequest } from './ConnectionRequest';
import { ValidationError } from '../errors/ValidationError';
@@ -36,23 +40,8 @@ export class ConnectedAccounts {
this.client = client;
}
- /**
- * List all connected accounts
- * @param {ConnectedAccountListParams} query - Query parameters for filtering connected accounts
- * @param {RequestOptions} options - Request options
- * @returns {Promise<ConnectedAccountListResponse>} List of connected accounts
- */
- async list(query?: ConnectedAccountListParams): Promise<ConnectedAccountListResponse> {
- return this.client.connectedAccounts.list(query);
- }
-
- /**
- * Transform the raw response from the API to the expected format
- * @param {ConnectedAccountRetrieveResponseRaw} response - Raw response from the API
- * @returns {ConnectedAccountRetrieveResponse} Transformed response
- */
- transformConnectedAccountResponse(
- response: ConnectedAccountRetrieveResponseRaw
+ transformConnectedAccountRetrieveResponse(
+ response: ConnectedAccountRetrieveResponseRaw | ConnectedAccountListResponseRaw['items'][0]
): ConnectedAccountRetrieveResponse {
const result = ConnectedAccountRetrieveResponseSchema.safeParse({
...response,
@@ -69,12 +58,87 @@ export class ConnectedAccounts {
updatedAt: response.updated_at,
testRequestEndpoint: response.test_request_endpoint,
});
- if (result.error) {
+ if (!result.success) {
throw new ValidationError(result.error);
}
return result.data;
}
+ /**
+ * Lists all connected accounts based on provided filter criteria.
+ *
+ * This method retrieves connected accounts from the Composio API with optional filtering.
+ *
+ * @param {ConnectedAccountListParams} [query] - Optional query parameters for filtering connected accounts
+ * @returns {Promise<ConnectedAccountListResponse>} A paginated list of connected accounts
+ * @throws {ValidationError} If the query fails validation against the expected schema
+ * @example
+ * ```typescript
+ * // List all connected accounts
+ * const allAccounts = await composio.connectedAccounts.list();
+ *
+ * // List accounts for a specific user
+ * const userAccounts = await composio.connectedAccounts.list({
+ * userIds: ['user123']
+ * });
+ *
+ * // List accounts for a specific toolkit
+ * const githubAccounts = await composio.connectedAccounts.list({
+ * toolkitSlugs: ['github']
+ * });
+ * ```
+ */
+ async list(query?: ConnectedAccountListParams): Promise<ConnectedAccountListResponse> {
+ let rawQuery: ConnectedAccountListParamsRaw | undefined = undefined;
+
+ if (query) {
+ const parsedQuery = ConnectedAccountListParamsSchema.safeParse(query);
+ if (!parsedQuery.success) {
+ throw new ValidationError(parsedQuery.error);
+ }
+ rawQuery = {
+ auth_config_ids: parsedQuery.data.authConfigIds,
+ cursor: parsedQuery.data.cursor,
+ labels: parsedQuery.data.labels,
+ limit: parsedQuery.data.limit,
+ order_by: parsedQuery.data.orderBy,
+ statuses: parsedQuery.data.statuses,
+ toolkit_slugs: parsedQuery.data.toolkitSlugs,
+ user_ids: parsedQuery.data.userIds,
+ };
+ }
+
+ const result = await this.client.connectedAccounts.list(rawQuery);
+
+ const parsedResponse = ConnectedAccountListResponseSchema.safeParse({
+ items: result.items.map(this.transformConnectedAccountRetrieveResponse),
+ nextCursor: result.next_cursor,
+ totalPages: result.total_pages,
+ });
+ if (!parsedResponse.success) {
+ throw new ValidationError(parsedResponse.error);
+ }
+ return parsedResponse.data;
+ }
+
+ /**
+ * Transforms connected account data from API format to SDK format.
+ *
+ * This method converts property names from snake_case to camelCase and reorganizes
+ * the data structure to match the SDK's standardized format for connected accounts.
+ *
+ * @param {ConnectedAccountRetrieveResponseRaw} response - The raw API response to transform
+ * @returns {ConnectedAccountRetrieveResponse} The transformed connected account data
+ * @throws {ValidationError} If the response fails validation against the expected schema
+ *
+ * @private
+ */
+ transformConnectedAccountResponse(
+ response: ConnectedAccountRetrieveResponseRaw
+ ): ConnectedAccountRetrieveResponse {
+ return this.transformConnectedAccountRetrieveResponse(response);
+ }
+
/**
* Compound function to create a new connected account.
* This function creates a new connected account and returns a connection request.
@@ -111,6 +175,28 @@ export class ConnectedAccounts {
return new ConnectionRequest(this.client, response.id, response.status, response.redirect_uri);
}
+ /**
+ * Waits for a connection request to complete and become active.
+ *
+ * This method continuously polls the Composio API to check the status of a connection
+ * until it either becomes active, enters a terminal error state, or times out.
+ *
+ * @param {string} connectedAccountId - The ID of the connected account to wait for
+ * @param {number} [timeout=60000] - Maximum time to wait in milliseconds (default: 60 seconds)
+ * @returns {Promise<ConnectedAccountRetrieveResponse>} The finalized connected account data
+ * @throws {ComposioConnectedAccountNotFoundError} If the connected account cannot be found
+ * @throws {ConnectionRequestFailedError} If the connection enters a failed, expired, or deleted state
+ * @throws {ConnectionRequestTimeoutError} If the connection does not complete within the timeout period
+ *
+ * @example
+ * ```typescript
+ * // Wait for a connection to complete with default timeout
+ * const connectedAccount = await composio.connectedAccounts.waitForConnection('conn_123abc');
+ *
+ * // Wait with a custom timeout of 2 minutes
+ * const connectedAccount = await composio.connectedAccounts.waitForConnection('conn_123abc', 120000);
+ * ```
+ */
async waitForConnection(
connectedAccountId: string,
timeout: number = 60000
@@ -120,10 +206,22 @@ export class ConnectedAccounts {
}
/**
- * Get a connected account by nanoid
- * @param {string} nanoid - Unique identifier of the connected account
- * @param {RequestOptions} options - Request options
- * @returns {Promise<ConnectedAccountRetrieveResponse>} Connected account details
+ * Retrieves a specific connected account by its ID.
+ *
+ * This method fetches detailed information about a single connected account
+ * and transforms the response to the SDK's standardized format.
+ *
+ * @param {string} nanoid - The unique identifier of the connected account
+ * @returns {Promise<ConnectedAccountRetrieveResponse>} The connected account details
+ * @throws {Error} If the connected account cannot be found or an API error occurs
+ *
+ * @example
+ * ```typescript
+ * // Get a connected account by ID
+ * const account = await composio.connectedAccounts.get('conn_abc123');
+ * console.log(account.status); // e.g., 'ACTIVE'
+ * console.log(account.toolkit.slug); // e.g., 'github'
+ * ```
*/
async get(nanoid: string): Promise<ConnectedAccountRetrieveResponse> {
const response = await this.client.connectedAccounts.retrieve(nanoid);
@@ -131,20 +229,40 @@ export class ConnectedAccounts {
}
/**
- * Delete a connected account
- * @param {string} nanoid - Unique identifier of the connected account to delete
- * @param {RequestOptions} options - Request options
- * @returns {Promise<ConnectedAccountDeleteResponse>} Response from deletion
+ * Deletes a connected account.
+ *
+ * This method permanently removes a connected account from the Composio platform.
+ * This action cannot be undone and will revoke any access tokens associated with the account.
+ *
+ * @param {string} nanoid - The unique identifier of the connected account to delete
+ * @returns {Promise<ConnectedAccountDeleteResponse>} The deletion response
+ * @throws {Error} If the account doesn't exist or cannot be deleted
+ *
+ * @example
+ * ```typescript
+ * // Delete a connected account
+ * await composio.connectedAccounts.delete('conn_abc123');
+ * ```
*/
async delete(nanoid: string): Promise<ConnectedAccountDeleteResponse> {
return this.client.connectedAccounts.delete(nanoid);
}
/**
- * Refresh a connected account's credentials
- * @param {string} nanoid - Unique identifier of the connected account to refresh
- * @param {RequestOptions} options - Request options
- * @returns {Promise<ConnectedAccountRefreshResponse>} Refreshed connected account details
+ * Refreshes a connected account's authentication credentials.
+ *
+ * This method attempts to refresh OAuth tokens or other credentials associated with
+ * the connected account. This is useful when a token has expired or is about to expire.
+ *
+ * @param {string} nanoid - The unique identifier of the connected account to refresh
+ * @returns {Promise<ConnectedAccountRefreshResponse>} The response containing the refreshed account details
+ * @throws {Error} If the account doesn't exist or credentials cannot be refreshed
+ *
+ * @example
+ * ```typescript
+ * // Refresh a connected account's credentials
+ * const refreshedAccount = await composio.connectedAccounts.refresh('conn_abc123');
+ * ```
*/
async refresh(nanoid: string): Promise<ConnectedAccountRefreshResponse> {
return this.client.connectedAccounts.refresh(nanoid);
diff --git a/packages/core/src/models/ConnectionRequest.ts b/packages/core/src/models/ConnectionRequest.ts
index eeefefaf8..2c35461f6 100644
--- a/packages/core/src/models/ConnectionRequest.ts
+++ b/packages/core/src/models/ConnectionRequest.ts
@@ -39,9 +39,16 @@ export class ConnectionRequest {
}
/**
- * Transform the response from the Composio API to the SDK format
- * @param response
- * @returns
+ * Transforms the raw connected account response from the Composio API to the SDK format.
+ *
+ * This method converts property names from snake_case to camelCase and reorganizes
+ * the data structure to match the SDK's standardized format.
+ *
+ * @param {OriginalConnectedAccountResponse} response - The raw API response to transform
+ * @returns {Promise<ConnectedAccountRetrieveResponse>} The transformed response
+ * @throws {ZodError} If the response fails validation against the expected schema
+ *
+ * @private
*/
private async transformResponse(
response: OriginalConnectedAccountResponse
@@ -73,10 +80,30 @@ export class ConnectionRequest {
}
/**
- * Wait for the connection to be established.
- * The function will poll the Composio API every second until the connection is established or the timeout is reached.
- * @param {number} timeout - The time in milliseconds to wait for the connection to be established. Default is 30 seconds.
- * @returns
+ * Waits for the connection request to complete and become active.
+ *
+ * This method continuously polls the Composio API to check the status of the connection request
+ * until it either becomes active, enters a terminal error state, or times out.
+ *
+ * @param {number} [timeout=60000] - Maximum time to wait in milliseconds before timing out (default: 60 seconds)
+ * @returns {Promise<ConnectedAccountRetrieveResponse>} The final connected account response when successful
+ * @throws {ComposioConnectedAccountNotFoundError} If the connected account cannot be found
+ * @throws {ConnectionRequestFailedError} If the connection enters a failed, expired, or deleted state
+ * @throws {ConnectionRequestTimeoutError} If the connection request does not complete within the timeout period
+ *
+ * @example
+ * ```typescript
+ * // Wait for connection with default timeout (60 seconds)
+ * try {
+ * const connection = await connectionRequest.waitForConnection();
+ * console.log('Connection established:', connection.id);
+ * } catch (error) {
+ * console.error('Connection failed:', error.message);
+ * }
+ *
+ * // Wait for connection with custom timeout (2 minutes)
+ * const connection = await connectionRequest.waitForConnection(120000);
+ * ```
*/
async waitForConnection(timeout: number = 60000): Promise<ConnectedAccountRetrieveResponse> {
try {
diff --git a/packages/core/src/models/CustomTools.ts b/packages/core/src/models/CustomTools.ts
index 586b5d498..40adf1ef0 100644
--- a/packages/core/src/models/CustomTools.ts
+++ b/packages/core/src/models/CustomTools.ts
@@ -140,8 +140,8 @@ export class CustomTools {
});
}
const connectedAccounts = await this.client.connectedAccounts.list({
- toolkit_slug: toolkitSlug,
- user_id: metadata.userId,
+ toolkit_slugs: [toolkitSlug],
+ user_ids: [metadata.userId],
});
if (!connectedAccounts.items.length) {
diff --git a/packages/core/src/models/Toolkits.ts b/packages/core/src/models/Toolkits.ts
index 68808f296..0c91a0641 100644
--- a/packages/core/src/models/Toolkits.ts
+++ b/packages/core/src/models/Toolkits.ts
@@ -33,9 +33,15 @@ export class Toolkits {
this.authorize = this.authorize.bind(this);
}
/**
- * List all toolkits available in the Composio SDK.
- * This method fetches the toolkits from the Composio API.
- * @returns {Promise<Toolkit[]>} List of toolkits
+ * Retrieves a list of toolkits based on the provided query parameters.
+ *
+ * This method fetches toolkits from the Composio API and transforms the response
+ * from snake_case to camelCase format for consistency with JavaScript/TypeScript conventions.
+ *
+ * @param {ToolkitListParams} query - The query parameters to filter toolkits
+ * @returns {Promise<ToolKitListResponse>} The transformed list of toolkits
+ *
+ * @private
*/
private async getToolkits(query: ToolkitListParams): Promise<ToolKitListResponse> {
const parsedQuery = ToolkitsListParamsSchema.parse(query);
@@ -67,11 +73,73 @@ export class Toolkits {
}
/**
- * Fetches a toolkit by its Slug.
- * This method retrieves the toolkit from the Composio API.
- * @param slug - The ID of the toolkit to be retrieved
- * @param options - Request options
- * @returns {Promise<ToolkitRetrieveResponse>} The toolkit object
+ * Retrieves a specific toolkit by its slug identifier.
+ *
+ * @param {string} slug - The unique slug identifier of the toolkit to retrieve
+ * @returns {Promise<ToolkitRetrieveResponse>} The toolkit object with detailed information
+ * @throws {ComposioToolNotFoundError} If no toolkit with the given slug exists
+ *
+ * @example
+ * ```typescript
+ * // Get a specific toolkit
+ * const githubToolkit = await composio.toolkits.get('github');
+ * console.log(githubToolkit.name); // GitHub
+ * console.log(githubToolkit.authConfigDetails); // Authentication configuration details
+ * ```
+ */
+ async get(slug: string): Promise<ToolkitRetrieveResponse>;
+
+ /**
+ * Retrieves a list of toolkits based on the provided query parameters.
+ *
+ * @param {ToolkitListParams} query - The query parameters to filter toolkits
+ * @returns {Promise<ToolKitListResponse>} A paginated list of toolkits matching the query criteria
+ *
+ * @example
+ * ```typescript
+ * // Get all toolkits
+ * const allToolkits = await composio.toolkits.get({});
+ *
+ * // Get toolkits by category
+ * const devToolkits = await composio.toolkits.get({
+ * category: 'developer-tools'
+ * });
+ *
+ * // Get local toolkits
+ * const localToolkits = await composio.toolkits.get({
+ * isLocal: true
+ * });
+ * ```
+ */
+ async get(query: ToolkitListParams): Promise<ToolKitListResponse>;
+
+ /**
+ * Implementation method that handles both overloads for retrieving toolkits.
+ *
+ * @param {string | ToolkitListParams} arg - Either a toolkit slug or query parameters
+ * @returns {Promise<ToolkitRetrieveResponse | ToolKitListResponse>} The toolkit or list of toolkits
+ */
+ async get(
+ arg: string | ToolkitListParams
+ ): Promise<ToolkitRetrieveResponse | ToolKitListResponse> {
+ if (typeof arg === 'string') {
+ return this.getToolkitBySlug(arg);
+ }
+ return this.getToolkits(arg);
+ }
+
+ /**
+ * Retrieves a specific toolkit by its slug identifier.
+ *
+ * This method fetches a single toolkit from the Composio API and transforms
+ * the response to use camelCase property naming consistent with JavaScript/TypeScript conventions.
+ *
+ * @param {string} slug - The unique slug identifier of the toolkit to retrieve
+ * @returns {Promise<ToolkitRetrieveResponse>} The transformed toolkit object
+ * @throws {ValidationError} If the response cannot be properly parsed
+ * @throws {ComposioToolNotFoundError} If no toolkit with the given slug exists
+ *
+ * @private
*/
private async getToolkitBySlug(slug: string): Promise<ToolkitRetrieveResponse> {
try {
@@ -113,38 +181,19 @@ export class Toolkits {
}
/**
- * @overload
- * Fetches a toolkit by its Slug or a list of toolkits.
- * @param slug - The ID of the toolkit to be retrieved
- * @returns {Promise<ToolkitRetrieveResponse>} The toolkit object
- */
- async get(slug: string): Promise<ToolkitRetrieveResponse>;
- /**
- * @overload
- * Fetches a list of toolkits.
- * @param query - The parameters to fetch the toolkits
- * @returns {Promise<ToolKitListResponse>} The list of toolkits
- */
- async get(query: ToolkitListParams): Promise<ToolKitListResponse>;
- /**
- * Fetches a toolkit by its Slug or a list of toolkits.
- * This method retrieves the toolkit from the Composio API.
- * @param arg - The ID of the toolkit to be retrieved or a list of parameters
- * @returns {Promise<ToolkitRetrieveResponse | ToolKitListResponse>} The toolkit object or a list of toolkits
- */
- async get(
- arg: string | ToolkitListParams
- ): Promise<ToolkitRetrieveResponse | ToolKitListResponse> {
- if (typeof arg === 'string') {
- return this.getToolkitBySlug(arg);
- }
- return this.getToolkits(arg);
- }
-
- /**
- * Fetches all categories available in the Composio SDK
+ * Retrieves all toolkit categories available in the Composio SDK.
+ *
+ * This method fetches the complete list of categories from the Composio API
+ * and transforms the response to use camelCase property naming.
*
- * @returns {Promise<ToolkitRetrieveCategoriesResponse>} List of categories
+ * @returns {Promise<ToolkitRetrieveCategoriesResponse>} The list of toolkit categories
+ *
+ * @example
+ * ```typescript
+ * // Get all toolkit categories
+ * const categories = await composio.toolkits.listCategories();
+ * console.log(categories.items); // Array of category objects
+ * ```
*/
async listCategories(): Promise<ToolkitRetrieveCategoriesResponse> {
const result = await this.client.toolkits.retrieveCategories();
@@ -168,7 +217,7 @@ export class Toolkits {
* @param {string} userId - The user id of the user to authorize
* @param {string} toolkitSlug - The slug of the toolkit to authorize
* @returns {Promise<ConnectionRequest>} The connection request object
- *
+ *
* @example
* ```typescript
* const connectionRequest = await composio.toolkits.authorize(userId, 'github');
diff --git a/packages/core/src/models/Tools.ts b/packages/core/src/models/Tools.ts
index 0d9625db2..8cdfba861 100644
--- a/packages/core/src/models/Tools.ts
+++ b/packages/core/src/models/Tools.ts
@@ -73,9 +73,15 @@ export class Tools<
}
/**
- * Transform the tool cases
- * @param {ToolRetrieveResponse | ComposioToolListResponse['items'][0]} tool - The tool to transform
- * @returns {Tool} The transformed tool
+ * Transforms tool data from snake_case API format to camelCase for internal SDK use.
+ *
+ * This method standardizes the property naming convention for tools retrieved from the Composio API,
+ * making them more consistent with JavaScript/TypeScript conventions.
+ *
+ * @param {ToolRetrieveResponse | ComposioToolListResponse['items'][0]} tool - The tool object to transform
+ * @returns {Tool} The transformed tool with camelCase properties
+ *
+ * @private
*/
private transformToolCases(
tool: ToolRetrieveResponse | ComposioToolListResponse['items'][0]
@@ -88,9 +94,15 @@ export class Tools<
}
/**
- * Transform the tool execute response to camelcase
- * @param {ComposioToolExecuteResponse} response - The response to transform
- * @returns {ToolExecuteResponse} The transformed response
+ * Transforms tool execution response from snake_case API format to camelCase.
+ *
+ * This method converts the response received from the Composio API to a standardized format
+ * with consistent property naming that follows JavaScript/TypeScript conventions.
+ *
+ * @param {ComposioToolExecuteResponse} response - The raw API response to transform
+ * @returns {ToolExecuteResponse} The transformed response with camelCase properties
+ *
+ * @private
*/
private transformToolExecuteResponse(response: ComposioToolExecuteResponse): ToolExecuteResponse {
return ToolExecuteResponseSchema.parse({
@@ -202,9 +214,35 @@ export class Tools<
}
/**
- * Lists all tools available in the Composio SDK as well as custom tools.
- * This method fetches the tools from the Composio API in the raw format.
- * @returns {ToolList} List of tools
+ * Lists all tools available in the Composio SDK including custom tools.
+ *
+ * This method fetches tools from the Composio API in raw format and combines them with
+ * any registered custom tools. The response can be filtered and modified as needed.
+ *
+ * @param {string} userId - The user ID for whom to fetch the tools
+ * @param {ToolListParams} [query={}] - Optional query parameters to filter the tools
+ * @param {TransformToolSchemaModifier} [modifier] - Optional function to transform tool schemas
+ * @returns {Promise<ToolList>} List of tools matching the query criteria
+ *
+ * @example
+ * ```typescript
+ * // Get all tools
+ * const tools = await composio.tools.getRawComposioTools('default');
+ *
+ * // Get tools with filters
+ * const githubTools = await composio.tools.getRawComposioTools('default', {
+ * toolkits: ['github'],
+ * important: true
+ * });
+ *
+ * // Get tools with schema transformation
+ * const tools = await composio.tools.getRawComposioTools('default', {},
+ * (toolSlug, toolkitSlug, tool) => {
+ * // Add custom properties to tool schema
+ * return {...tool, customProperty: 'value'};
+ * }
+ * );
+ * ```
*/
async getRawComposioTools(
userId: string,
@@ -300,16 +338,26 @@ export class Tools<
}
/**
- * Get a list of tools from composio based on filters
- * @param userId - The user id
- * @param filters - The filters for the tools
- * @param options - The options for the tools
- * @returns The tools
+ * Get a list of tools from Composio based on filters.
+ * This method fetches the tools from the Composio API and wraps them using the provider.
+ *
+ * @param {string} userId - The user id to get the tools for
+ * @param {ToolListParams} filters - The filters to apply when fetching tools
+ * @param {ProviderOptions<TProvider>} [options] - Optional provider options including modifiers
+ * @returns {Promise<ReturnType<T['wrapTools']>>} The wrapped tools collection
*
* @example
- * ```ts
+ * ```typescript
+ * // Get tools from the GitHub toolkit
* const tools = await composio.tools.get('default', {
* toolkits: ['github'],
+ * limit: 10
+ * });
+ *
+ * // Get tools with search
+ * const tools = await composio.tools.get('default', {
+ * search: 'user',
+ * important: true
* });
* ```
*/
@@ -320,15 +368,26 @@ export class Tools<
): Promise<ReturnType<T['wrapTools']>>;
/**
- * Get a tool by its slug
- * @param userId - The user id
- * @param slug - The slug of the tool
- * @param options - The options for the tool
- * @returns The tool
+ * Get a specific tool by its slug.
+ * This method fetches the tool from the Composio API and wraps it using the provider.
+ *
+ * @param {string} userId - The user id to get the tool for
+ * @param {string} slug - The slug of the tool to fetch
+ * @param {ProviderOptions<TProvider>} [options] - Optional provider options including modifiers
+ * @returns {Promise<ReturnType<T['wrapTools']>>} The wrapped tool
*
* @example
- * ```ts
- * const tool = await composio.tools.get('default', 'HACKERNEWS_GET_USER');
+ * ```typescript
+ * // Get a specific tool by slug
+ * const hackerNewsUserTool = await composio.tools.get('default', 'HACKERNEWS_GET_USER');
+ *
+ * // Get a tool with schema modifications
+ * const tool = await composio.tools.get('default', 'GITHUB_GET_REPOS', {
+ * modifyToolSchema: (toolSlug, toolkitSlug, schema) => {
+ * // Customize the tool schema
+ * return {...schema, description: 'Custom description'};
+ * }
+ * });
* ```
*/
async get<T extends TProvider>(
@@ -338,11 +397,13 @@ export class Tools<
): Promise<ReturnType<T['wrapTools']>>;
/**
- * Get a tool by its slug
- * @param userId - The user id
- * @param arg2 - The slug of the tool or the filters for the tools
- * @param options - The options for the tools
- * @returns The tool or the tools
+ * Get a tool or list of tools based on the provided arguments.
+ * This is an implementation method that handles both overloads.
+ *
+ * @param {string} userId - The user id to get the tool(s) for
+ * @param {ToolListParams | string} arg2 - Either a slug string or filters object
+ * @param {ProviderOptions<TProvider>} [options] - Optional provider options
+ * @returns {Promise<TToolCollection>} The tool collection
*/
async get(
userId: string,
@@ -480,13 +541,43 @@ export class Tools<
}
/**
- * Exectes a given tool with the provided parameters.
+ * Executes a given tool with the provided parameters.
*
- * This method calls the Composio API to execute the tool and returns the response.
+ * This method calls the Composio API or a custom tool handler to execute the tool and returns the response.
+ * It automatically determines whether to use a custom tool or a Composio API tool based on the slug.
*
- * @param {string} slug - The ID of the tool to be executed
+ * @param {string} slug - The slug/ID of the tool to be executed
* @param {ToolExecuteParams} body - The parameters to be passed to the tool
+ * @param {ExecuteToolModifiers} [modifiers] - Optional modifiers to transform the request or response
* @returns {Promise<ToolExecuteResponse>} - The response from the tool execution
+ *
+ * @throws {ComposioCustomToolsNotInitializedError} If the CustomTools instance is not initialized
+ * @throws {ComposioToolNotFoundError} If the tool with the given slug is not found
+ * @throws {ComposioToolExecutionError} If there is an error during tool execution
+ *
+ * @example
+ * ```typescript
+ * // Execute a Composio API tool
+ * const result = await composio.tools.execute('HACKERNEWS_GET_USER', {
+ * userId: 'default',
+ * arguments: { userId: 'pg' }
+ * });
+ *
+ * // Execute with modifiers
+ * const result = await composio.tools.execute('GITHUB_GET_ISSUES', {
+ * userId: 'default',
+ * arguments: { owner: 'composio', repo: 'sdk' }
+ * }, {
+ * beforeToolExecute: (toolSlug, toolkitSlug, params) => {
+ * // Modify params before execution
+ * return params;
+ * },
+ * afterToolExecute: (toolSlug, toolkitSlug, result) => {
+ * // Transform result after execution
+ * return result;
+ * }
+ * });
+ * ```
*/
async execute(
slug: string,
@@ -554,9 +645,39 @@ export class Tools<
}
/**
- * Execute a custom tool
- * @param body
- * @returns
+ * Creates a custom tool that can be used within the Composio SDK.
+ *
+ * Custom tools allow you to extend the functionality of Composio with your own implementations
+ * while keeping a consistent interface for both built-in and custom tools.
+ *
+ * @param {CustomToolOptions} body - The configuration for the custom tool
+ * @returns {Promise<Tool>} The created custom tool
+ *
+ * @example
+ * ```typescript
+ * const customTool = await composio.tools.createCustomTool({
+ * name: 'My Custom Tool',
+ * description: 'A custom tool that does something specific',
+ * slug: 'MY_CUSTOM_TOOL',
+ * inputParameters: {
+ * param1: {
+ * type: 'string',
+ * description: 'First parameter',
+ * required: true
+ * }
+ * },
+ * outputParameters: {
+ * result: {
+ * type: 'string',
+ * description: 'The result of the operation'
+ * }
+ * },
+ * handler: async (params, context) => {
+ * // Custom logic here
+ * return { data: { result: 'Success!' } };
+ * }
+ * });
+ * ```
*/
async createCustomTool(body: CustomToolOptions): Promise<Tool> {
return this.customTools.createTool(body);
diff --git a/packages/core/src/types/connectedAccounts.types.ts b/packages/core/src/types/connectedAccounts.types.ts
index caf276972..854a745c8 100644
--- a/packages/core/src/types/connectedAccounts.types.ts
+++ b/packages/core/src/types/connectedAccounts.types.ts
@@ -109,7 +109,7 @@ export const ConnectedAccountRetrieveResponseSchema = z.object({
authConfig: ConnectedAccountAuthConfigSchema,
userId: z.string(),
data: z.record(z.string(), z.unknown()),
- params: z.record(z.string(), z.unknown()),
+ params: z.record(z.string(), z.unknown()).optional(),
status: ConnectedAccountStatusSchema,
statusReason: z.string().nullable(),
toolkit: z.object({
@@ -120,6 +120,62 @@ export const ConnectedAccountRetrieveResponseSchema = z.object({
createdAt: z.string(),
updatedAt: z.string(),
});
+// for some reason the list item doesn't have params
+export const ConnectedAccountListResponseItemSchema = ConnectedAccountAuthConfigSchema;
export type ConnectedAccountRetrieveResponse = z.infer<
typeof ConnectedAccountRetrieveResponseSchema
>;
+
+/**
+ * Type for list response item that doesn't include params
+ */
+export type ConnectedAccountListResponseItem = Omit<ConnectedAccountRetrieveResponse, 'params'>;
+
+export const ConnectedAccountListParamsSchema = z.object({
+ authConfigIds: z
+ .array(z.string())
+ .nullable()
+ .optional()
+ .describe('The auth config ids of the connected accounts'),
+ cursor: z
+ .number()
+ .nullable()
+ .optional()
+ .describe('The cursor to paginate through the connected accounts'),
+ labels: z
+ .array(z.string())
+ .nullable()
+ .optional()
+ .describe('The labels of the connected accounts'),
+ limit: z.number().nullable().optional().describe('The limit of the connected accounts to return'),
+ orderBy: z
+ .enum(['created_at', 'updated_at'])
+ .optional()
+ .describe('The order by of the connected accounts'),
+ statuses: z
+ .array(ConnectedAccountStatusSchema)
+ .nullable()
+ .optional()
+ .describe('The statuses of the connected accounts'),
+ toolkitSlugs: z
+ .array(z.string())
+ .nullable()
+ .optional()
+ .describe('The toolkit slugs of the connected accounts'),
+ userIds: z
+ .array(z.string())
+ .nullable()
+ .optional()
+ .describe('The user ids of the connected accounts'),
+});
+export type ConnectedAccountListParams = z.infer<typeof ConnectedAccountListParamsSchema>;
+
+export const ConnectedAccountListResponseSchema = z.object({
+ items: z.array(ConnectedAccountRetrieveResponseSchema).describe('The list of connected accounts'),
+ nextCursor: z
+ .string()
+ .nullable()
+ .describe('The next cursor to paginate through the connected accounts'),
+ totalPages: z.number().describe('The total number of pages of connected accounts'),
+});
+export type ConnectedAccountListResponse = z.infer<typeof ConnectedAccountListResponseSchema>;
diff --git a/packages/core/src/types/modifiers.types.ts b/packages/core/src/types/modifiers.types.ts
index 9259cc7c8..9422e3705 100644
--- a/packages/core/src/types/modifiers.types.ts
+++ b/packages/core/src/types/modifiers.types.ts
@@ -2,8 +2,51 @@ import { BaseAgenticProvider, BaseComposioProvider } from '../provider/BaseProvi
import { ToolExecuteParams, ToolExecuteResponse, Tool } from './tool.types';
/**
- * Modifier for altering the tool execute params
- * Called before the tool execute call
+ * Modifier for altering the tool execute parameters before execution.
+ *
+ * This function allows you to intercept and modify the parameters being passed to a tool
+ * before the actual execution happens. Common use cases include:
+ * - Adding or modifying authentication parameters
+ * - Transforming input data to match expected formats
+ * - Adding contextual information to the request
+ * - Implementing request validation or normalization
+ *
+ * @param {string} toolSlug - The slug identifier of the tool being executed
+ * @param {string} toolkitSlug - The slug identifier of the toolkit containing the tool
+ * @param {ToolExecuteParams} toolExecuteParams - The original execution parameters
+ * @returns {ToolExecuteParams} The modified execution parameters
+ *
+ * @example
+ * ```typescript
+ * // Add authentication headers to all tool requests
+ * const beforeToolExecute = (toolSlug, toolkitSlug, params) => {
+ * return {
+ * ...params,
+ * customAuthParams: {
+ * ...params.customAuthParams,
+ * headers: {
+ * ...params.customAuthParams?.headers,
+ * 'X-API-Key': 'my-api-key'
+ * }
+ * }
+ * };
+ * };
+ *
+ * // Transform input parameters for a specific tool
+ * const beforeToolExecute = (toolSlug, toolkitSlug, params) => {
+ * if (toolSlug === 'GITHUB_SEARCH_REPOS') {
+ * // Convert simple query to structured query format
+ * return {
+ * ...params,
+ * arguments: {
+ * ...params.arguments,
+ * q: `${params.arguments.query} in:name,description`
+ * }
+ * };
+ * }
+ * return params;
+ * };
+ * ```
*/
export type BeforeToolExecuteModifier = (
toolSlug: string,
@@ -12,8 +55,54 @@ export type BeforeToolExecuteModifier = (
) => ToolExecuteParams;
/**
- * Modifier for altering the tool execute response
- * Called after the tool execute call
+ * Modifier for altering the tool execution response after execution completes.
+ *
+ * This function allows you to intercept and modify the response returned from a tool
+ * after its execution has completed. Common use cases include:
+ * - Transforming response data into a more convenient format
+ * - Handling or enhancing error responses
+ * - Adding additional context or derived data to successful responses
+ * - Implementing cross-cutting concerns like logging or analytics
+ *
+ * @param {string} toolSlug - The slug identifier of the tool that was executed
+ * @param {string} toolkitSlug - The slug identifier of the toolkit containing the tool
+ * @param {ToolExecuteResponse} toolExecuteResponse - The original execution response
+ * @returns {ToolExecuteResponse} The modified execution response
+ *
+ * @example
+ * ```typescript
+ * // Transform the response data format
+ * const afterToolExecute = (toolSlug, toolkitSlug, response) => {
+ * if (toolSlug === 'GITHUB_LIST_REPOS' && response.successful) {
+ * // Transform the returned repos into a simpler format
+ * return {
+ * ...response,
+ * data: {
+ * repositories: response.data.items.map(repo => ({
+ * name: repo.name,
+ * url: repo.html_url,
+ * stars: repo.stargazers_count
+ * }))
+ * }
+ * };
+ * }
+ * return response;
+ * };
+ *
+ * // Add error handling with custom messages
+ * const afterToolExecute = (toolSlug, toolkitSlug, response) => {
+ * if (!response.successful) {
+ * return {
+ * ...response,
+ * error: {
+ * message: `Error using ${toolSlug}: ${response.error?.message || 'Unknown error'}`,
+ * code: response.error?.code || 'UNKNOWN_ERROR'
+ * }
+ * };
+ * }
+ * return response;
+ * };
+ * ```
*/
export type AfterToolExecuteModifier = (
toolSlug: string,
@@ -22,8 +111,63 @@ export type AfterToolExecuteModifier = (
) => ToolExecuteResponse;
/**
- * Modifier for altering the tool schema
- * Called after the tool schema is retrieved
+ * Modifier for altering the tool schema before it's exposed to consumers.
+ *
+ * This function allows you to customize the metadata, parameters, and behavior definitions
+ * of tools before they are used. Common use cases include:
+ * - Customizing input parameter definitions or descriptions
+ * - Adding, removing, or modifying parameters to match your application's needs
+ * - Changing the name or description of tools to better fit your context
+ * - Implementing versioning or feature flagging for tool schemas
+ *
+ * @param {string} toolSlug - The slug identifier of the tool being modified
+ * @param {string} toolkitSlug - The slug identifier of the toolkit containing the tool
+ * @param {Tool} toolSchema - The original tool schema
+ * @returns {Tool} The modified tool schema
+ *
+ * @example
+ * ```typescript
+ * // Modify the input parameters for a specific tool
+ * const modifyToolSchema = (toolSlug, toolkitSlug, toolSchema) => {
+ * if (toolSlug === 'HACKERNEWS_GET_USER') {
+ * return {
+ * ...toolSchema,
+ * inputParameters: {
+ * ...toolSchema.inputParameters,
+ * userId: {
+ * type: 'string',
+ * description: 'The HackerNews username to retrieve information for',
+ * required: true
+ * }
+ * }
+ * };
+ * }
+ * return toolSchema;
+ * };
+ *
+ * // Add custom descriptions to all tools in a toolkit
+ * const modifyToolSchema = (toolSlug, toolkitSlug, toolSchema) => {
+ * if (toolkitSlug === 'github') {
+ * return {
+ * ...toolSchema,
+ * description: `Company GitHub tool: ${toolSchema.description}`,
+ * important: true
+ * };
+ * }
+ * return toolSchema;
+ * };
+ *
+ * // Simplify tool schemas for a specific consumer
+ * const modifyToolSchema = (toolSlug, toolkitSlug, toolSchema) => {
+ * // Remove advanced or complex parameters
+ * const { complexParam1, complexParam2, ...simpleInputParams } = toolSchema.inputParameters;
+ *
+ * return {
+ * ...toolSchema,
+ * inputParameters: simpleInputParams
+ * };
+ * };
+ * ```
*/
export type TransformToolSchemaModifier = (
toolSlug: string,
@@ -32,34 +176,138 @@ export type TransformToolSchemaModifier = (
) => Tool;
/**
- * Non Agentic tool options. These are used by Non-Agentic toolsets
+ * Options for non-agentic tool configuration.
+ *
+ * These options are used when working with non-agentic tool providers to
+ * customize the behavior of tools through schema transformation.
+ *
+ * @example
+ * ```typescript
+ * // Configure tools with schema modification
+ * const tools = await composio.tools.get('default', {
+ * toolkits: ['github']
+ * }, {
+ * modifyToolSchema: (toolSlug, toolkitSlug, schema) => {
+ * // Custom schema modifications
+ * return schema;
+ * }
+ * });
+ * ```
*/
export type ToolOptions = {
/**
- * Transform tool schema modifier
+ * Function to transform tool schemas before they're exposed to consumers.
+ * This allows customizing input/output parameters, descriptions, and other metadata.
*/
modifyToolSchema?: TransformToolSchemaModifier;
};
/**
- * Modifiers for the tool execution
- * This is used by execute call and handleToolCall of Non-Agentic toolsets
+ * Options for configuring tool execution behavior.
+ *
+ * These modifiers allow you to intercept and modify tool execution at both
+ * the request and response stages, enabling custom behavior, data transformation,
+ * error handling, and more.
+ *
+ * @example
+ * ```typescript
+ * // Execute a tool with request and response modifications
+ * const result = await composio.tools.execute('GITHUB_GET_REPOS', {
+ * userId: 'default',
+ * arguments: { owner: 'composio' }
+ * }, {
+ * beforeToolExecute: (toolSlug, toolkitSlug, params) => {
+ * console.log(`Executing ${toolSlug} from ${toolkitSlug}`);
+ * return params;
+ * },
+ * afterToolExecute: (toolSlug, toolkitSlug, response) => {
+ * if (response.successful) {
+ * console.log(`Successfully executed ${toolSlug}`);
+ * }
+ * return response;
+ * }
+ * });
+ * ```
*/
export type ExecuteToolModifiers = {
/**
- * Before tool execute modifier
+ * Function to intercept and modify tool execution parameters before the tool is executed.
+ * This allows customizing the request based on tool-specific needs.
*/
beforeToolExecute?: BeforeToolExecuteModifier;
+
/**
- * After tool execute modifier
+ * Function to intercept and modify tool execution responses after the tool has executed.
+ * This allows transforming the response or implementing custom error handling.
*/
afterToolExecute?: AfterToolExecuteModifier;
};
/**
- * Agentic tool options. These are used by Agentic toolsets
+ * Options for agentic tool configuration.
+ *
+ * These options combine schema modification capabilities with execution behavior
+ * customization, providing full control over both the definition and execution
+ * of tools in agentic contexts (like LLM providers).
+ *
+ * @example
+ * ```typescript
+ * // Configure agentic tools with schema and execution modifications
+ * const agenticTools = await vercel.tools.get('default', 'GITHUB_GET_REPOS', {
+ * modifyToolSchema: (toolSlug, toolkitSlug, schema) => {
+ * return {
+ * ...schema,
+ * description: `Enhanced ${toolSlug} for better context`
+ * };
+ * },
+ *
+ * // Intercept before execution
+ * beforeToolExecute: (toolSlug, toolkitSlug, params) => {
+ * // Add analytics tracking
+ * trackToolUsage(toolSlug);
+ * return params;
+ * },
+ *
+ * // Transform after execution
+ * afterToolExecute: (toolSlug, toolkitSlug, response) => {
+ * // Log results and handle errors
+ * if (!response.successful) {
+ * logToolError(toolSlug, response.error);
+ * }
+ * return response;
+ * }
+ * });
+ * ```
*/
export type AgenticToolOptions = ToolOptions & ExecuteToolModifiers;
+/**
+ * Provider-specific options determined by the type of provider being used.
+ *
+ * This type automatically resolves to either AgenticToolOptions or ToolOptions
+ * based on whether the provider is agentic (like OpenAI or Vercel) or non-agentic.
+ *
+ * @template T - The provider type
+ *
+ * @example
+ * ```typescript
+ * // With standard provider (non-agentic)
+ * const tools = await composio.tools.get('default', 'GITHUB_GET_REPOS', {
+ * modifyToolSchema: (toolSlug, toolkitSlug, schema) => schema
+ * });
+ *
+ * // With agentic provider (e.g., VercelProvider)
+ * const vercel = new Composio({
+ * apiKey: process.env.COMPOSIO_API_KEY,
+ * provider: new VercelProvider()
+ * });
+ *
+ * const agenticTools = await vercel.tools.get('default', 'GITHUB_GET_REPOS', {
+ * modifyToolSchema: (toolSlug, toolkitSlug, schema) => schema,
+ * beforeToolExecute: (toolSlug, toolkitSlug, params) => params,
+ * afterToolExecute: (toolSlug, toolkitSlug, response) => response
+ * });
+ * ```
+ */
export type ProviderOptions<T extends BaseComposioProvider<unknown, unknown>> =
T extends BaseAgenticProvider<unknown, unknown> ? AgenticToolOptions : ToolOptions;
diff --git a/packages/core/test/connectedAccounts/connectedAccounts.test.ts b/packages/core/test/connectedAccounts/connectedAccounts.test.ts
index 1d237426a..6eebb498e 100644
--- a/packages/core/test/connectedAccounts/connectedAccounts.test.ts
+++ b/packages/core/test/connectedAccounts/connectedAccounts.test.ts
@@ -42,25 +42,33 @@ describe('ConnectedAccounts', () => {
describe('list', () => {
it('should call client.connectedAccounts.list with the provided query', async () => {
const query = { limit: 10 };
- const mockResponse = { items: [], totalPages: 0 };
+ const mockResponse = { items: [], next_cursor: null, total_pages: 0 };
extendedMockClient.connectedAccounts.list.mockResolvedValueOnce(mockResponse);
const result = await connectedAccounts.list(query);
expect(extendedMockClient.connectedAccounts.list).toHaveBeenCalledWith(query);
- expect(result).toEqual(mockResponse);
+ expect(result).toEqual({
+ items: [],
+ nextCursor: null,
+ totalPages: 0,
+ });
});
it('should call client.connectedAccounts.list without query if none provided', async () => {
- const mockResponse = { items: [], totalPages: 0 };
+ const mockResponse = { items: [], total_pages: 0, next_cursor: null };
extendedMockClient.connectedAccounts.list.mockResolvedValueOnce(mockResponse);
const result = await connectedAccounts.list();
expect(extendedMockClient.connectedAccounts.list).toHaveBeenCalledWith(undefined);
- expect(result).toEqual(mockResponse);
+ expect(result).toEqual({
+ items: [],
+ nextCursor: null,
+ totalPages: 0,
+ });
});
});