@devries-cameron20 / composio-1 / commits / f8c226491
Fork 0

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

Add errors and fix validatin errors

haxzie committed May 16, 2025 at 18:14 UTC f8c22649197ab7a7a8c7c35791575bcae2f79199
10 files changed +163 -49
examples/connected-accounts/src/index.ts
-15
@@ -1,9 +1,4 @@
1 import { AuthConfigTypes, AuthSchemeTypes, Composio } from '@composio/core';
2 -import { OpenAI } from 'openai';
3 -
4 -const openai = new OpenAI({
5 - apiKey: process.env.OPENAI_API_KEY,
6 -});
2
3 // Initialize Composio
4 // OpenAI Toolset is automatically installed and initialized
@@ -11,16 +6,6 @@ const composio = new Composio({
6 apiKey: process.env.COMPOSIO_API_KEY,
7 });
8
14 -// i think this should be a discriminated union, like only tools or toolkits or search can be there, inside the filter
15 -// the other ones should be third object {} options
16 -const tools = await composio.tools.get('user123', {
17 - tools: ['HACKERNEWS_GET_USER'],
18 - cursor: '123',
19 - important: '', // what is this doing do we need it can we remove it?
20 - limit: '10',
21 - toolkits: ['HACKERNEWS'],
22 -});
23 -
9 /**
10 * Create a new auth config
11 */
examples/connected-accounts/src/toolkit-authorize.ts new
+19
@@ -0,0 +1,19 @@
1 +import { Composio } from '@composio/core';
2 +
3 +// Initialize Composio
4 +// OpenAI Toolset is automatically installed and initialized
5 +const composio = new Composio({
6 + apiKey: process.env.COMPOSIO_API_KEY,
7 +});
8 +
9 +// magic flow
10 +const connectionRequest = await composio.toolkits.authorize('default', 'github');
11 +const redirectUrl = connectionRequest.redirectUrl;
12 +// app requires user to visit the following URL to authorize the toolkit
13 +if (redirectUrl) {
14 + console.log(`⚠️ Please visit the following URL to authorize the toolkit: ${redirectUrl}`);
15 +}
16 +console.log('Waiting for connection...');
17 +const connectedAccount = await connectionRequest.waitForConnection();
18 +console.log(`✅ Connected account created: ${connectedAccount.id}`);
19 +console.log(connectedAccount);
packages/core/src/errors/AuthConfigErrors.ts new
+20
@@ -0,0 +1,20 @@
1 +import { ComposioError } from './ComposioError';
2 +
3 +export const AuthConfigErrorCodes = {
4 + AUTH_CONFIG_NOT_FOUND: 'AUTH_CONFIG_NOT_FOUND',
5 +} as const;
6 +
7 +export class ComposioAuthConfigNotFoundError extends ComposioError {
8 + constructor(message: string, meta?: Record<string, unknown>) {
9 + super(message, {
10 + code: AuthConfigErrorCodes.AUTH_CONFIG_NOT_FOUND,
11 + cause: meta,
12 + possibleFixes: [
13 + 'Check if the auth config exists',
14 + 'Check if the auth config id is correct',
15 + 'Check if the auth config is enabled',
16 + ],
17 + });
18 + this.name = 'ComposioAuthConfigNotFoundError';
19 + }
20 +}
packages/core/src/errors/ValidationError.ts
+7 -5
@@ -30,11 +30,13 @@ export class ValidationError extends ComposioError {
30 super(message, {
31 code: ValidationErrorCodes.VALIDATION_ERROR,
32 meta: {
33 - issues: zodErrorInstance.issues.map(issue => ({
34 - path: issue.path.join('.'),
35 - message: issue.message,
36 - code: issue.code,
37 - })),
33 + issues: JSON.stringify(
34 + zodErrorInstance.issues.map(issue => ({
35 + path: issue.path.join('.'),
36 + message: issue.message,
37 + code: issue.code,
38 + }))
39 + ),
40 },
41 cause: zodErrorInstance,
42 });
packages/core/src/models/AuthConfigs.ts
+1
@@ -124,6 +124,7 @@ export class AuthConfigs {
124 },
125 auth_config: parsedOptions.data,
126 });
127 + console.log(JSON.stringify(result, null, 2));
128 const parsedResult = CreateAuthConfigResponseSchema.safeParse({
129 id: result.auth_config.id,
130 authScheme: result.auth_config.auth_scheme,
packages/core/src/models/ConnectedAccounts.ts
+1 -1
@@ -74,7 +74,7 @@ export class ConnectedAccounts {
74 user_id: userId,
75 },
76 });
77 - return new ConnectionRequest(this.client, response.id, response.status);
77 + return new ConnectionRequest(this.client, response.id, response.status, response.redirect_uri);
78 }
79
80 /**
packages/core/src/models/ConnectionRequest.ts
+4 -1
@@ -20,15 +20,18 @@ export class ConnectionRequest {
20 private client: ComposioClient;
21 private connectedAccountId: string;
22 private connectedAccountStatus: ConnectedAccountStatus;
23 + public redirectUrl?: string | null;
24
25 constructor(
26 client: ComposioClient,
27 connectedAccountId: string,
27 - connectedAccountStatus: ConnectedAccountStatus
28 + connectedAccountStatus: ConnectedAccountStatus,
29 + redirectUrl?: string | null
30 ) {
31 this.client = client;
32 this.connectedAccountId = connectedAccountId;
33 this.connectedAccountStatus = connectedAccountStatus;
34 + this.redirectUrl = redirectUrl;
35 }
36
37 /**
packages/core/src/models/Toolkits.ts
+62 -2
@@ -14,6 +14,10 @@ import {
14 import { ComposioToolNotFoundError } from '../errors/ToolErrors';
15 import { ZodError } from 'zod';
16 import { ValidationError } from '../errors/ValidationError';
17 +import { AuthConfigs } from './AuthConfigs';
18 +import { ComposioAuthConfigNotFoundError } from '../errors/AuthConfigErrors';
19 +import { ConnectedAccounts } from './ConnectedAccounts';
20 +import { ConnectionRequest } from './ConnectionRequest';
21
22 /**
23 * Toolkits class
@@ -26,6 +30,7 @@ export class Toolkits {
30
31 constructor(client: ComposioClient) {
32 this.client = client;
33 + this.authorize = this.authorize.bind(this);
34 }
35 /**
36 * List all toolkits available in the Composio SDK.
@@ -74,10 +79,27 @@ export class Toolkits {
79 const parsedResult = ToolkitRetrieveResponseSchema.parse({
80 name: result.name,
81 slug: result.slug,
77 - meta: result.meta,
82 + meta: {
83 + ...result.meta,
84 + createdAt: result.meta.created_at,
85 + updatedAt: result.meta.updated_at,
86 + toolsCount: result.meta.tools_count,
87 + triggersCount: result.meta.triggers_count,
88 + // appUrl: result.meta.app_url, @TODO Update the client type to include this
89 + },
90 isLocalToolkit: result.is_local_toolkit,
91 composioManagedAuthSchemes: result.composio_managed_auth_schemes,
80 - authConfigDetails: result.auth_config_details,
92 + authConfigDetails: result.auth_config_details?.map(authConfig => ({
93 + name: authConfig.name,
94 + mode: authConfig.mode,
95 + fields: {
96 + authConfigCreation: authConfig.fields.auth_config_creation,
97 + connectedAccountInitiation: authConfig.fields.connected_account_initiation,
98 + },
99 + proxy: {
100 + baseUrl: authConfig.proxy?.base_url,
101 + },
102 + })),
103 });
104 return parsedResult;
105 } catch (error) {
@@ -139,4 +161,42 @@ export class Toolkits {
161 });
162 return parsedResult;
163 }
164 +
165 + /**
166 + * Authorizes a user to use a toolkit.
167 + * This method will create an auth config if one doesn't exist and initiate a connection request.
168 + * @param {string} userId - The user id of the user to authorize
169 + * @param {string} toolkitSlug - The slug of the toolkit to authorize
170 + * @param {string} authConfigId - The id of the auth config to use
171 + * @returns {Promise<ConnectionRequest>} The connection request object
172 + */
173 + async authorize(
174 + userId: string,
175 + toolkitSlug: string,
176 + authConfigId?: string
177 + ): Promise<ConnectionRequest> {
178 + const toolkit = await this.getToolkitBySlug(toolkitSlug);
179 + const composioAuthConfig = new AuthConfigs(this.client);
180 + let authConfigIdToUse: string;
181 + if (authConfigId) {
182 + const authConfig = await composioAuthConfig.get(authConfigId);
183 + authConfigIdToUse = authConfig.id;
184 + } else {
185 + // create authConfig using composioManagedAuthSchemes
186 + if (toolkit.authConfigDetails && toolkit.authConfigDetails.length > 0) {
187 + const authConfig = await composioAuthConfig.create(toolkitSlug, {
188 + type: 'use_composio_managed_auth',
189 + name: `${toolkit.name} Auth Config`,
190 + });
191 + authConfigIdToUse = authConfig.id;
192 + } else {
193 + throw new ComposioAuthConfigNotFoundError('No auth config found for toolkit', {
194 + toolkitSlug,
195 + });
196 + }
197 + }
198 + // create the auth config
199 + const composioConnectedAccount = new ConnectedAccounts(this.client);
200 + return await composioConnectedAccount.initiate(userId, authConfigIdToUse);
201 + }
202 }
packages/core/src/types/toolkit.types.ts
+27 -25
@@ -20,19 +20,23 @@ export type ToolkitListParams = z.infer<typeof ToolkitsListParamsSchema>;
20 * Toolkits response
21 */
22 export const ToolKitMetaSchema = z.object({
23 - categories: z.array(
24 - z.object({
25 - id: z.string(),
26 - name: z.string(),
27 - })
28 - ),
29 - createdAt: z.string(),
30 - description: z.string(),
31 - logo: z.string(),
32 - toolsCount: z.number(),
33 - triggersCount: z.number(),
34 - updatedAt: z.string(),
23 + categories: z
24 + .array(
25 + z.object({
26 + slug: z.string(),
27 + name: z.string(),
28 + })
29 + )
30 + .optional(),
31 + appUrl: z.string().optional(),
32 + createdAt: z.string().optional(),
33 + description: z.string().optional(),
34 + logo: z.string().optional(),
35 + toolsCount: z.number().optional(),
36 + triggersCount: z.number().optional(),
37 + updatedAt: z.string().optional(),
38 });
39 +
40 export const ToolKitItemSchema = z.object({
41 name: z.string(),
42 slug: z.string(),
@@ -65,20 +69,18 @@ export const ToolkitAuthFieldSchema = z.object({
69 export const ToolkitAuthConfigDetailsSchema = z.object({
70 name: z.string(),
71 mode: z.string(),
68 - fields: z.array(
69 - z.object({
70 - authConfigCreation: z.object({
71 - optional: z.array(ToolkitAuthFieldSchema),
72 - required: z.array(ToolkitAuthFieldSchema),
73 - }),
74 - connectedAccountInitiation: z.object({
75 - optional: z.array(ToolkitAuthFieldSchema),
76 - required: z.array(ToolkitAuthFieldSchema),
77 - }),
78 - })
79 - ),
72 + fields: z.object({
73 + authConfigCreation: z.object({
74 + optional: z.array(ToolkitAuthFieldSchema),
75 + required: z.array(ToolkitAuthFieldSchema),
76 + }),
77 + connectedAccountInitiation: z.object({
78 + optional: z.array(ToolkitAuthFieldSchema),
79 + required: z.array(ToolkitAuthFieldSchema),
80 + }),
81 + }),
82 proxy: z.object({
81 - baseUrul: z.string(),
83 + baseUrl: z.string(),
84 }),
85 });
86
pnpm-lock.yaml
+22
@@ -89,6 +89,28 @@ importers:
89 specifier: ^5.8.3
90 version: 5.8.3
91
92 + examples/modifiers:
93 + dependencies:
94 + '@ai-sdk/openai':
95 + specifier: ^1.3.16
96 + version: 1.3.22(zod@3.24.4)
97 + '@composio/core':
98 + specifier: workspace:*
99 + version: link:../../packages/core
100 + '@composio/vercel':
101 + specifier: workspace:*
102 + version: link:../../packages/toolsets/vercel
103 + ai:
104 + specifier: ^4.3.8
105 + version: 4.3.15(react@19.1.0)(zod@3.24.4)
106 + devDependencies:
107 + '@types/bun':
108 + specifier: ^1.2.9
109 + version: 1.2.13
110 + typescript:
111 + specifier: ^5.8.3
112 + version: 5.8.3
113 +
114 examples/openai:
115 dependencies:
116 '@composio/core':