Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 22, 23:15 UTC
feat: Add file upload / download modifiers (#1670)
Musthaq Ahamad committed
Jun 19, 2025 at 19:02 UTC
84d43812e22db66b4301ceb8afab3d3de2d272d8
17 files changed
+721
-72
package.json
+4
-4
@@ -20,10 +20,10 @@
20
"lint:fix:packages": "eslint ts/packages --ext .ts,.tsx --fix",
21
"format": "prettier --write \"**/*.{ts,tsx,js,jsx,json,md}\"",
22
"prepare": "husky",
23
- "create:provider": "bash scripts/create-provider.sh",
24
- "create:example": "bash scripts/create-example.sh",
25
- "check:peer-deps": "tsx scripts/check-peer-deps.ts",
26
- "update:peer-deps": "tsx scripts/update-peer-deps.ts",
23
+ "create:provider": "bash ts/scripts/create-provider.sh",
24
+ "create:example": "bash ts/scripts/create-example.sh",
25
+ "check:peer-deps": "tsx ts/scripts/check-peer-deps.ts",
26
+ "update:peer-deps": "tsx ts/scripts/update-peer-deps.ts",
27
"prepublish": "pnpm run build:packages",
28
"changeset": "changeset",
29
"changeset:version": "changeset version",
pnpm-lock.yaml
+23
-28
@@ -413,6 +413,22 @@ importers:
413
specifier: ^5.8.3
414
version: 5.8.3
415
416
+ ts/examples/tools:
417
+ dependencies:
418
+ '@composio/core':
419
+ specifier: workspace:*
420
+ version: link:../../packages/core
421
+ dotenv:
422
+ specifier: ^16.4.1
423
+ version: 16.5.0
424
+ devDependencies:
425
+ '@types/bun':
426
+ specifier: ^1.2.9
427
+ version: 1.2.16
428
+ typescript:
429
+ specifier: ^5.8.3
430
+ version: 5.8.3
431
+
432
ts/examples/triggers:
433
dependencies:
434
'@composio/core':
@@ -532,6 +548,9 @@ importers:
548
'@composio/json-schema-to-zod':
549
specifier: 0.1.9
550
version: 0.1.9
551
+ '@types/json-schema':
552
+ specifier: ^7.0.15
553
+ version: 7.0.15
554
chalk:
555
specifier: ^5.4.1
556
version: 5.4.1
@@ -8738,14 +8757,6 @@ snapshots:
8757
chai: 5.2.0
8758
tinyrainbow: 2.0.0
8759
8741
- '@vitest/mocker@3.2.3(vite@6.3.5(@types/node@20.19.1)(jiti@1.21.7)(tsx@4.20.3)(yaml@2.8.0))':
8742
- dependencies:
8743
- '@vitest/spy': 3.2.3
8744
- estree-walker: 3.0.3
8745
- magic-string: 0.30.17
8746
- optionalDependencies:
8747
- vite: 6.3.5(@types/node@20.19.1)(jiti@1.21.7)(tsx@4.20.3)(yaml@2.8.0)
8748
-
8760
'@vitest/mocker@3.2.3(vite@6.3.5(@types/node@22.15.31)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0))':
8761
dependencies:
8762
'@vitest/spy': 3.2.3
@@ -8754,22 +8765,6 @@ snapshots:
8765
optionalDependencies:
8766
vite: 6.3.5(@types/node@22.15.31)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0)
8767
8757
- '@vitest/mocker@3.2.3(vite@6.3.5(@types/node@24.0.3)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0))':
8758
- dependencies:
8759
- '@vitest/spy': 3.2.3
8760
- estree-walker: 3.0.3
8761
- magic-string: 0.30.17
8762
- optionalDependencies:
8763
- vite: 6.3.5(@types/node@24.0.3)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0)
8764
-
8765
- '@vitest/mocker@3.2.3(vite@6.3.5(@types/node@24.0.3)(jiti@1.21.7)(tsx@4.20.3)(yaml@2.8.0))':
8766
- dependencies:
8767
- '@vitest/spy': 3.2.3
8768
- estree-walker: 3.0.3
8769
- magic-string: 0.30.17
8770
- optionalDependencies:
8771
- vite: 6.3.5(@types/node@24.0.3)(jiti@1.21.7)(tsx@4.20.3)(yaml@2.8.0)
8772
-
8768
'@vitest/mocker@3.2.4(vite@6.3.5(@types/node@24.0.3)(jiti@1.21.7)(tsx@4.20.3)(yaml@2.8.0))':
8769
dependencies:
8770
'@vitest/spy': 3.2.4
@@ -8827,7 +8822,7 @@ snapshots:
8822
sirv: 3.0.1
8823
tinyglobby: 0.2.14
8824
tinyrainbow: 2.0.0
8830
- vitest: 3.2.3(@types/node@24.0.3)(@vitest/ui@3.2.3)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0)
8825
+ vitest: 3.2.3(@types/node@22.15.31)(@vitest/ui@3.2.3)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0)
8826
8827
'@vitest/utils@3.2.3':
8828
dependencies:
@@ -11658,7 +11653,7 @@ snapshots:
11653
dependencies:
11654
'@types/chai': 5.2.2
11655
'@vitest/expect': 3.2.3
11661
- '@vitest/mocker': 3.2.3(vite@6.3.5(@types/node@20.19.1)(jiti@1.21.7)(tsx@4.20.3)(yaml@2.8.0))
11656
+ '@vitest/mocker': 3.2.3(vite@6.3.5(@types/node@22.15.31)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0))
11657
'@vitest/pretty-format': 3.2.3
11658
'@vitest/runner': 3.2.3
11659
'@vitest/snapshot': 3.2.3
@@ -11742,7 +11737,7 @@ snapshots:
11737
dependencies:
11738
'@types/chai': 5.2.2
11739
'@vitest/expect': 3.2.3
11745
- '@vitest/mocker': 3.2.3(vite@6.3.5(@types/node@24.0.3)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0))
11740
+ '@vitest/mocker': 3.2.3(vite@6.3.5(@types/node@22.15.31)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0))
11741
'@vitest/pretty-format': 3.2.3
11742
'@vitest/runner': 3.2.3
11743
'@vitest/snapshot': 3.2.3
@@ -11784,7 +11779,7 @@ snapshots:
11779
dependencies:
11780
'@types/chai': 5.2.2
11781
'@vitest/expect': 3.2.3
11787
- '@vitest/mocker': 3.2.3(vite@6.3.5(@types/node@24.0.3)(jiti@1.21.7)(tsx@4.20.3)(yaml@2.8.0))
11782
+ '@vitest/mocker': 3.2.3(vite@6.3.5(@types/node@22.15.31)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0))
11783
'@vitest/pretty-format': 3.2.3
11784
'@vitest/runner': 3.2.3
11785
'@vitest/snapshot': 3.2.3
ts/examples/tools/.env.example
new
+6
@@ -0,0 +1,6 @@
1
+# Composio API Key - Get it from https://app.composio.dev
2
+COMPOSIO_API_KEY=your_composio_api_key_here
3
+
4
+# Add other environment variables as needed for your example
5
+# OPENAI_API_KEY=your_openai_api_key_here
6
+# ANTHROPIC_API_KEY=your_anthropic_api_key_here
ts/examples/tools/README.md
new
+53
@@ -0,0 +1,53 @@
1
+# Tools Example
2
+
3
+This example demonstrates how to use Composio SDK for tools.
4
+
5
+## Setup
6
+
7
+1. **Install dependencies:**
8
+ ```bash
9
+ pnpm install
10
+ ```
11
+
12
+2. **Configure environment:**
13
+ ```bash
14
+ cp .env.example .env
15
+ ```
16
+
17
+ Then edit `.env` and add your API keys:
18
+ - `COMPOSIO_API_KEY`: Get it from [Composio Dashboard](https://app.composio.dev)
19
+
20
+## Running the Example
21
+
22
+```bash
23
+# Run the example
24
+pnpm start
25
+
26
+# Run in development mode (with file watching)
27
+pnpm dev
28
+```
29
+
30
+## What This Example Does
31
+
32
+- Initializes Composio SDK
33
+- Fetches available tools
34
+- Demonstrates basic usage patterns
35
+
36
+## Customization
37
+
38
+Edit `src/index.ts` to:
39
+- Add specific apps you want to integrate with
40
+- Implement your business logic
41
+- Add error handling and logging
42
+
43
+## Related Examples
44
+
45
+- [OpenAI Example](../openai) - Shows integration with OpenAI
46
+- [LangChain Example](../langchain) - Shows integration with LangChain
47
+- [More Examples](../) - Browse all available examples
48
+
49
+## Support
50
+
51
+- [Documentation](https://docs.composio.dev)
52
+- [Discord Community](https://discord.gg/composio)
53
+- [GitHub Issues](https://github.com/composio/composio/issues)
ts/examples/tools/package.json
new
+24
@@ -0,0 +1,24 @@
1
+{
2
+ "name": "tools-example",
3
+ "private": true,
4
+ "version": "0.1.0",
5
+ "description": "Example project for Tools",
6
+ "main": "src/index.ts",
7
+ "scripts": {
8
+ "start": "bun src/index.ts",
9
+ "dev": "bun --watch src/index.ts",
10
+ "test": "echo \"Error: no test specified\" && exit 1"
11
+ },
12
+ "keywords": ["composio", "example", "tools"],
13
+ "author": "",
14
+ "license": "ISC",
15
+ "packageManager": "pnpm@10.8.0",
16
+ "dependencies": {
17
+ "@composio/core": "workspace:*",
18
+ "dotenv": "^16.4.1"
19
+ },
20
+ "devDependencies": {
21
+ "@types/bun": "^1.2.9",
22
+ "typescript": "^5.8.3"
23
+ }
24
+}
ts/examples/tools/src/image.png
Binary files /dev/null and b/ts/examples/tools/src/image.png differ
ts/examples/tools/src/index.ts
new
+51
@@ -0,0 +1,51 @@
1
+/**
2
+ * Tools Example
3
+ *
4
+ * This example demonstrates how to use Composio SDK for tools.
5
+ *
6
+ * Prerequisites:
7
+ * 1. Set up your COMPOSIO_API_KEY in the .env file
8
+ * 3. Run the example: pnpm start
9
+ */
10
+
11
+import { Composio } from '@composio/core';
12
+import 'dotenv/config';
13
+import path from 'path';
14
+
15
+/**
16
+ * Initialize Composio
17
+ */
18
+const composio = new Composio({
19
+ apiKey: process.env.COMPOSIO_API_KEY,
20
+ allowTracking: false,
21
+ allowTracing: false,
22
+});
23
+
24
+/**
25
+ * Main function to run the example
26
+ */
27
+async function main() {
28
+ try {
29
+ console.log('🚀 Starting Tools Example...');
30
+
31
+ const tools = await composio.tools.getRawComposioTools({
32
+ tools: ['GOOGLEDRIVE_UPLOAD_FILE'],
33
+ });
34
+
35
+ console.log(JSON.stringify(tools, null, 2));
36
+
37
+ const result = await composio.tools.execute('GOOGLEDRIVE_UPLOAD_FILE', {
38
+ arguments: {
39
+ file_to_upload: path.join(__dirname, 'image.png'),
40
+ },
41
+ userId: 'default',
42
+ });
43
+
44
+ console.log(JSON.stringify(result, null, 2));
45
+ } catch (error) {
46
+ console.error('❌ Error running example:', error);
47
+ }
48
+}
49
+
50
+// Run the example
51
+main().catch(console.error);
ts/examples/tools/tsconfig.json
new
+16
@@ -0,0 +1,16 @@
1
+{
2
+ "compilerOptions": {
3
+ "target": "ESNext",
4
+ "module": "ESNext",
5
+ "declaration": true,
6
+ "declarationDir": "./dist",
7
+ "outDir": "./dist",
8
+ "rootDir": "./src",
9
+ "strict": true,
10
+ "esModuleInterop": true,
11
+ "moduleResolution": "node",
12
+ "skipLibCheck": true,
13
+ "resolveJsonModule": true
14
+ },
15
+ "include": ["src"]
16
+}
ts/packages/core/package.json
+1
@@ -39,6 +39,7 @@
39
"dependencies": {
40
"@composio/client": "0.1.0-alpha.24",
41
"@composio/json-schema-to-zod": "0.1.9",
42
+ "@types/json-schema": "^7.0.15",
43
"chalk": "^5.4.1",
44
"openai": "^4.94.0",
45
"pusher-js": "^8.4.0",
ts/packages/core/src/errors/FileModifierErrors.ts
new
+19
@@ -0,0 +1,19 @@
1
+import { ComposioError, ComposioErrorOptions } from './ComposioError';
2
+
3
+export const FileModifierErrorCodes = {
4
+ FILE_UPLOAD_FAILED: 'FILE_UPLOAD_FAILED',
5
+} as const;
6
+
7
+export class ComposioFileUploadError extends ComposioError {
8
+ constructor(
9
+ message: string = 'Failed to upload file',
10
+ options: Omit<ComposioErrorOptions, 'code'> = {}
11
+ ) {
12
+ super(message, {
13
+ ...options,
14
+ code: FileModifierErrorCodes.FILE_UPLOAD_FAILED,
15
+ possibleFixes: options.possibleFixes || ['Check if the file exists in the location provided'],
16
+ });
17
+ this.name = 'ComposioFileUploadError';
18
+ }
19
+}
ts/packages/core/src/models/Tools.ts
+119
-18
@@ -25,6 +25,8 @@ import {
25
import { CustomTools } from './CustomTools';
26
import { CustomToolInputParameter, CustomToolOptions } from '../types/customTool.types';
27
import {
28
+ afterExecuteModifier,
29
+ beforeExecuteModifier,
30
ExecuteToolModifiers,
31
ProviderOptions,
32
TransformToolSchemaModifier,
@@ -41,6 +43,7 @@ import {
43
} from '../errors/ToolErrors';
44
import { ValidationError } from '../errors/ValidationErrors';
45
import { telemetry } from '../telemetry/Telemetry';
46
+import { FileToolModifier } from '../utils/modifiers/FileToolModifier';
47
/**
48
* This class is used to manage tools in the Composio SDK.
49
* It provides methods to list, get, and execute tools.
@@ -218,6 +221,96 @@ export class Tools<
221
return null;
222
}
223
224
+ /**
225
+ * Applies the default schema modifiers to the tools
226
+ * @param tools - The tools to apply the default schema modifiers to
227
+ * @returns The tools with the default schema modifiers applied
228
+ */
229
+ private async applyDefaultSchemaModifiers(tools: Tool[]): Promise<Tool[]> {
230
+ const fileToolModifier = new FileToolModifier(this.client);
231
+ return await Promise.all(
232
+ tools.map(tool =>
233
+ fileToolModifier.modifyToolSchema(tool.slug, tool.toolkit?.slug ?? 'unknown', tool)
234
+ )
235
+ );
236
+ }
237
+
238
+ /**
239
+ * Applies the before execute modifiers to the tool execution params
240
+ * @param options.toolSlug - The slug of the tool
241
+ * @param options.toolkitSlug - The slug of the toolkit
242
+ * @param options.params - The params of the tool execution
243
+ * @param modifier - The modifier to apply
244
+ * @returns The modified params
245
+ */
246
+ private async applyBeforeExecuteModifiers(
247
+ tool: Tool,
248
+ {
249
+ toolSlug,
250
+ toolkitSlug,
251
+ params,
252
+ }: {
253
+ toolSlug: string;
254
+ toolkitSlug: string;
255
+ params: ToolExecuteParams;
256
+ },
257
+ modifier?: beforeExecuteModifier
258
+ ): Promise<ToolExecuteParams> {
259
+ const fileToolModifier = new FileToolModifier(this.client);
260
+ let modifiedParams = params;
261
+ if (modifier) {
262
+ if (typeof modifier === 'function') {
263
+ modifiedParams = await modifier(toolSlug, toolkitSlug, modifiedParams);
264
+ } else {
265
+ throw new ComposioInvalidModifierError('Invalid beforeExecute modifier. Not a function.');
266
+ }
267
+ }
268
+ modifiedParams = await fileToolModifier.fileUploadModifier(tool, {
269
+ toolSlug,
270
+ toolkitSlug,
271
+ params: modifiedParams,
272
+ });
273
+ return modifiedParams;
274
+ }
275
+
276
+ /**
277
+ * Applies the after execute modifiers to the tool execution result
278
+ * @param options.toolSlug - The slug of the tool
279
+ * @param options.toolkitSlug - The slug of the toolkit
280
+ * @param options.result - The result of the tool execution
281
+ * @param modifier - The modifier to apply
282
+ * @returns The modified result
283
+ */
284
+ private async applyAfterExecuteModifiers(
285
+ tool: Tool,
286
+ {
287
+ toolSlug,
288
+ toolkitSlug,
289
+ result,
290
+ }: {
291
+ toolSlug: string;
292
+ toolkitSlug: string;
293
+ result: ToolExecuteResponse;
294
+ },
295
+ modifier?: afterExecuteModifier
296
+ ): Promise<ToolExecuteResponse> {
297
+ const fileToolModifier = new FileToolModifier(this.client);
298
+ let modifiedResult = result;
299
+ if (modifier) {
300
+ if (typeof modifier === 'function') {
301
+ modifiedResult = await modifier(toolSlug, toolkitSlug, modifiedResult);
302
+ } else {
303
+ throw new ComposioInvalidModifierError('Invalid afterExecute modifier. Not a function.');
304
+ }
305
+ }
306
+ modifiedResult = await fileToolModifier.fileDownloadModifier(tool, {
307
+ toolSlug,
308
+ toolkitSlug,
309
+ result: modifiedResult,
310
+ });
311
+ return modifiedResult;
312
+ }
313
+
314
/**
315
* Lists all tools available in the Composio SDK including custom tools.
316
*
@@ -307,7 +400,10 @@ export class Tools<
400
toolSlugs: 'tools' in queryParams.data ? queryParams.data.tools : undefined,
401
});
402
310
- let modifiedTools = [...caseTransformedTools, ...customTools];
403
+ let modifiedTools = await this.applyDefaultSchemaModifiers([
404
+ ...caseTransformedTools,
405
+ ...customTools,
406
+ ]);
407
408
// apply local modifiers if they are provided
409
if (modifier) {
@@ -357,8 +453,8 @@ export class Tools<
453
});
454
}
455
360
- // change the case of the tool to camel case
361
- let modifiedTool = this.transformToolCases(tool);
456
+ // change the case of the tool to camel case and apply default modifiers
457
+ let [modifiedTool] = await this.applyDefaultSchemaModifiers([this.transformToolCases(tool)]);
458
// apply local modifiers if they are provided
459
if (modifier) {
460
if (typeof modifier === 'function') {
@@ -538,13 +634,17 @@ export class Tools<
634
body: ToolExecuteParams,
635
modifiers?: ExecuteToolModifiers
636
): Promise<ToolExecuteResponse> {
541
- if (modifiers?.beforeExecute) {
542
- if (typeof modifiers.beforeExecute === 'function') {
543
- body = await modifiers.beforeExecute(tool.slug, tool.toolkit?.slug ?? 'unknown', body);
544
- } else {
545
- throw new ComposioInvalidModifierError('Invalid beforeExecute modifier. Not a function.');
546
- }
547
- }
637
+ // apply before execute modifiers
638
+ body = await this.applyBeforeExecuteModifiers(
639
+ tool,
640
+ {
641
+ toolSlug: tool.slug,
642
+ toolkitSlug: tool.toolkit?.slug ?? 'unknown',
643
+ params: body,
644
+ },
645
+ modifiers?.beforeExecute
646
+ );
647
+
648
// fetch connected accounts if doesn't exist
649
let connectedAccountId = body.connectedAccountId;
650
if (!connectedAccountId) {
@@ -564,14 +664,15 @@ export class Tools<
664
// apply transformations to the response
665
result = this.transformToolExecuteResponse(result);
666
567
- // apply local modifiers if they are provided
568
- if (modifiers?.afterExecute) {
569
- if (typeof modifiers.afterExecute === 'function') {
570
- result = await modifiers.afterExecute(tool.slug, tool.toolkit?.slug ?? 'unknown', result);
571
- } else {
572
- throw new ComposioInvalidModifierError('Invalid afterExecute modifier. Not a function.');
573
- }
574
- }
667
+ result = await this.applyAfterExecuteModifiers(
668
+ tool,
669
+ {
670
+ toolSlug: tool.slug,
671
+ toolkitSlug: tool.toolkit?.slug ?? 'unknown',
672
+ result,
673
+ },
674
+ modifiers?.afterExecute
675
+ );
676
return result;
677
}
678
ts/packages/core/src/types/tool.types.ts
+25
-19
@@ -25,19 +25,24 @@ const JSONSchemaType = z.enum([
25
]);
26
27
// JSON Schema property definition
28
-const JSONSchemaProperty: z.ZodType<unknown> = z.object({
28
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
29
+export const JSONSchemaPropertySchema: z.ZodType<any> = z.object({
30
type: z.union([JSONSchemaType, z.array(JSONSchemaType)]).optional(),
31
description: z.string().optional(),
31
- anyOf: z.lazy(() => z.array(JSONSchemaProperty)).optional(),
32
- oneOf: z.lazy(() => z.array(JSONSchemaProperty)).optional(),
33
- allOf: z.lazy(() => z.array(JSONSchemaProperty)).optional(),
34
- not: z.lazy(() => JSONSchemaProperty).optional(),
32
+ anyOf: z.lazy(() => z.array(JSONSchemaPropertySchema)).optional(),
33
+ oneOf: z.lazy(() => z.array(JSONSchemaPropertySchema)).optional(),
34
+ allOf: z.lazy(() => z.array(JSONSchemaPropertySchema)).optional(),
35
+ not: z.lazy(() => JSONSchemaPropertySchema).optional(),
36
title: z.string().optional(),
37
default: z.any().optional(),
38
nullable: z.boolean().optional(),
38
- properties: z.lazy(() => z.record(z.string(), JSONSchemaProperty)).optional(),
39
+ properties: z.lazy(() => z.record(z.string(), JSONSchemaPropertySchema)).optional(),
40
required: z.array(z.string()).optional(),
40
- items: z.lazy(() => z.union([JSONSchemaProperty, z.array(JSONSchemaProperty)])).optional(),
41
+ file_uploadable: z.boolean().optional(),
42
+ file_downloadable: z.boolean().optional(),
43
+ items: z
44
+ .lazy(() => z.union([JSONSchemaPropertySchema, z.array(JSONSchemaPropertySchema)]))
45
+ .optional(),
46
enum: z.array(z.any()).optional(),
47
const: z.any().optional(),
48
minimum: z.number().optional(),
@@ -54,37 +59,38 @@ const JSONSchemaProperty: z.ZodType<unknown> = z.object({
59
uniqueItems: z.boolean().optional(),
60
minProperties: z.number().optional(),
61
maxProperties: z.number().optional(),
57
- patternProperties: z.lazy(() => z.record(z.string(), JSONSchemaProperty)).optional(),
58
- additionalProperties: z.union([z.boolean(), z.lazy(() => JSONSchemaProperty)]).optional(),
62
+ patternProperties: z.lazy(() => z.record(z.string(), JSONSchemaPropertySchema)).optional(),
63
+ additionalProperties: z.union([z.boolean(), z.lazy(() => JSONSchemaPropertySchema)]).optional(),
64
examples: z.array(z.any()).optional(),
65
readOnly: z.boolean().optional(),
66
writeOnly: z.boolean().optional(),
62
- if: z.lazy(() => JSONSchemaProperty).optional(),
63
- then: z.lazy(() => JSONSchemaProperty).optional(),
64
- else: z.lazy(() => JSONSchemaProperty).optional(),
67
+ if: z.lazy(() => JSONSchemaPropertySchema).optional(),
68
+ then: z.lazy(() => JSONSchemaPropertySchema).optional(),
69
+ else: z.lazy(() => JSONSchemaPropertySchema).optional(),
70
$ref: z.string().optional(),
71
definitions: z
72
.record(
73
z.string(),
69
- z.lazy(() => JSONSchemaProperty)
74
+ z.lazy(() => JSONSchemaPropertySchema)
75
)
76
.optional(),
77
$defs: z
78
.record(
79
z.string(),
75
- z.lazy(() => JSONSchemaProperty)
80
+ z.lazy(() => JSONSchemaPropertySchema)
81
)
82
.optional(),
83
});
84
+export type JSONSchemaProperty = z.infer<typeof JSONSchemaPropertySchema>;
85
86
// Schema for parameters (input/output)
87
const ParametersSchema = z.object({
88
type: z.literal('object'),
83
- anyOf: z.array(JSONSchemaProperty).optional(),
84
- oneOf: z.array(JSONSchemaProperty).optional(),
85
- allOf: z.array(JSONSchemaProperty).optional(),
86
- not: JSONSchemaProperty.optional(),
87
- properties: z.record(z.string(), JSONSchemaProperty),
89
+ anyOf: z.array(JSONSchemaPropertySchema).optional(),
90
+ oneOf: z.array(JSONSchemaPropertySchema).optional(),
91
+ allOf: z.array(JSONSchemaPropertySchema).optional(),
92
+ not: JSONSchemaPropertySchema.optional(),
93
+ properties: z.record(z.string(), JSONSchemaPropertySchema),
94
required: z.array(z.string()).optional(),
95
title: z.string().optional(),
96
default: z.any().optional(),
ts/packages/core/src/utils/fileUtils.ts
new
+209
@@ -0,0 +1,209 @@
1
+import crypto from 'crypto';
2
+import pathModule from 'path';
3
+import ComposioClient from '@composio/client';
4
+import { COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME } from './constants';
5
+import logger from './logger';
6
+
7
+const readFileContent = async (path: string): Promise<{ content: string; mimeType: string }> => {
8
+ try {
9
+ const content = require('fs').readFileSync(path);
10
+ return {
11
+ content: content.toString('base64'),
12
+ mimeType: 'application/octet-stream',
13
+ };
14
+ } catch (error) {
15
+ throw new Error(`Error reading file at ${path}: ${error}`);
16
+ }
17
+};
18
+
19
+const readFileContentFromURL = async (
20
+ path: string
21
+): Promise<{ content: string; mimeType: string }> => {
22
+ const response = await fetch(path);
23
+ if (!response.ok) {
24
+ throw new Error(`Failed to fetch file: ${response.statusText}`);
25
+ }
26
+ const arrayBuffer = await response.arrayBuffer();
27
+ const content = Buffer.from(arrayBuffer);
28
+ const mimeType = response.headers.get('content-type') || 'application/octet-stream';
29
+ return {
30
+ content: content.toString('base64'),
31
+ mimeType,
32
+ };
33
+};
34
+
35
+const uploadFileToS3 = async (
36
+ fileName: string,
37
+ content: string,
38
+ toolSlug: string,
39
+ toolkitSlug: string,
40
+ mimeType: string,
41
+ client: ComposioClient
42
+): Promise<string> => {
43
+ const response = await client.files.createPresignedURL({
44
+ filename: fileName,
45
+ mimetype: mimeType,
46
+ md5: crypto.createHash('md5').update(Buffer.from(content, 'base64')).digest('hex'),
47
+ tool_slug: toolSlug,
48
+ toolkit_slug: toolkitSlug,
49
+ });
50
+
51
+ const { key, type } = response;
52
+
53
+ if (type === 'new' || type === 'update') {
54
+ logger.debug(`Uploading ${key} file to S3: ${key}`);
55
+ const buffer = Buffer.from(content, 'base64');
56
+ const signedURL =
57
+ response.type === 'update' ? response.update_presigned_url : response.new_presigned_url;
58
+
59
+ // Upload the file using the presigned URL
60
+ const uploadResponse = await fetch(signedURL, {
61
+ method: 'PUT',
62
+ body: buffer,
63
+ headers: {
64
+ 'Content-Type': mimeType,
65
+ 'Content-Length': buffer.length.toString(),
66
+ },
67
+ });
68
+
69
+ if (!uploadResponse.ok) {
70
+ throw new Error(`Failed to upload file to S3: ${uploadResponse.statusText}`);
71
+ }
72
+ } else {
73
+ logger.debug(`File already exists in S3: ${key}`);
74
+ }
75
+
76
+ return key;
77
+};
78
+
79
+export const getFileDataAfterUploadingToS3 = async (
80
+ path: string,
81
+ toolSlug: string,
82
+ toolkitSlug: string,
83
+ client: ComposioClient
84
+): Promise<{
85
+ name: string;
86
+ mimetype: string;
87
+ s3key: string;
88
+}> => {
89
+ const isURL = path.startsWith('http');
90
+ const fileData = isURL ? await readFileContentFromURL(path) : await readFileContent(path);
91
+ logger.debug(`Uploading file to S3: ${path}`);
92
+ const s3key = await uploadFileToS3(
93
+ pathModule.basename(path) || `${toolSlug}_${Date.now()}`,
94
+ fileData.content,
95
+ toolSlug,
96
+ toolkitSlug,
97
+ fileData.mimeType,
98
+ client
99
+ );
100
+
101
+ logger.debug(`Done! File uploaded to S3: ${s3key}`, JSON.stringify(fileData, null, 2));
102
+ return {
103
+ name:
104
+ pathModule.basename(path) || `${toolSlug}_${Date.now()}.${fileData.mimeType.split('/')[1]}`,
105
+ mimetype: fileData.mimeType,
106
+ s3key: s3key,
107
+ };
108
+};
109
+
110
+export const downloadFileFromS3 = async ({
111
+ toolSlug,
112
+ s3Url,
113
+ mimeType,
114
+}: {
115
+ toolSlug: string;
116
+ s3Url: string;
117
+ mimeType: string;
118
+}) => {
119
+ const response = await fetch(s3Url);
120
+ if (!response.ok) {
121
+ throw new Error(`Failed to download file: ${response.statusText}`);
122
+ }
123
+ const data = await response.arrayBuffer();
124
+
125
+ const extension = mimeType.split('/')[1] || 'txt';
126
+ const fileName = `${toolSlug}_${Date.now()}.${extension}`;
127
+ const filePath = saveFile(fileName, Buffer.from(data), true);
128
+ return {
129
+ name: fileName,
130
+ mimeType: mimeType,
131
+ s3Key: s3Url,
132
+ filePath: filePath,
133
+ };
134
+};
135
+
136
+/**
137
+ * Gets the Composio directory.
138
+ * @param createDirIfNotExists - Whether to create the directory if it doesn't exist.
139
+ * @returns The path to the Composio directory.
140
+ */
141
+export const getComposioDir = (createDirIfNotExists: boolean = false) => {
142
+ try {
143
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
144
+ const os = require('os');
145
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
146
+ const path = require('path');
147
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
148
+ const fs = require('fs');
149
+ const composioDir = path.join(os.homedir(), COMPOSIO_DIR);
150
+ if (createDirIfNotExists && !fs.existsSync(composioDir)) {
151
+ fs.mkdirSync(composioDir, { recursive: true });
152
+ }
153
+ return composioDir;
154
+ } catch (_error) {
155
+ return null;
156
+ }
157
+};
158
+
159
+/**
160
+ * Gets the Composio temporary files directory.
161
+ * @param createDirIfNotExists - Whether to create the directory if it doesn't exist.
162
+ * @returns The path to the Composio temporary files directory.
163
+ */
164
+export const getComposioTempFilesDir = (createDirIfNotExists: boolean = false) => {
165
+ try {
166
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
167
+ const os = require('os');
168
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
169
+ const path = require('path');
170
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
171
+ const fs = require('fs');
172
+ const composioFilesDir = path.join(os.homedir(), COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME);
173
+ if (createDirIfNotExists && !fs.existsSync(composioFilesDir)) {
174
+ fs.mkdirSync(composioFilesDir, { recursive: true });
175
+ }
176
+ return composioFilesDir;
177
+ } catch (_error) {
178
+ return null;
179
+ }
180
+};
181
+
182
+/**
183
+ * Saves a file to the Composio directory.
184
+ * @param file - The name of the file to save.
185
+ * @param content - The content of the file to save. Can be a string or Buffer.
186
+ * @param isTempFile - Whether the file is a temporary file.
187
+ * @returns The path to the saved file.
188
+ */
189
+export const saveFile = (file: string, content: string | Buffer, isTempFile: boolean = false) => {
190
+ try {
191
+ const path = require('path');
192
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
193
+ const fs = require('fs');
194
+ const composioFilesDir = isTempFile ? getComposioTempFilesDir(true) : getComposioDir(true);
195
+ const filePath = path.join(composioFilesDir, path.basename(file));
196
+
197
+ logger.info(`Saving file to: ${filePath}`);
198
+
199
+ if (Buffer.isBuffer(content)) {
200
+ fs.writeFileSync(filePath, content);
201
+ } else {
202
+ fs.writeFileSync(filePath, content, 'utf8');
203
+ }
204
+
205
+ return filePath;
206
+ } catch (_error) {
207
+ return null;
208
+ }
209
+};
ts/packages/core/src/utils/modifiers/FileToolModifier.ts
new
+168
@@ -0,0 +1,168 @@
1
+import {
2
+ JSONSchemaProperty,
3
+ Tool,
4
+ ToolExecuteParams,
5
+ ToolExecuteResponse,
6
+} from '../../types/tool.types';
7
+import ComposioClient from '@composio/client';
8
+import logger from '../logger';
9
+import { ComposioFileUploadError } from '../../errors/FileModifierErrors';
10
+import { downloadFileFromS3, getFileDataAfterUploadingToS3 } from '../fileUtils';
11
+
12
+/**
13
+ * Transforms the properties of the tool schema to include the file upload URL.
14
+ *
15
+ * Attaches the format: 'path' to the properties that are file uploadable for agents.
16
+ *
17
+ * @param properties - The properties of the tool schema.
18
+ * @returns The transformed properties.
19
+ */
20
+const transformProperties = (properties: JSONSchemaProperty): JSONSchemaProperty => {
21
+ const newProperties: JSONSchemaProperty = {};
22
+
23
+ for (const [key, property] of Object.entries(properties) as [string, JSONSchemaProperty][]) {
24
+ if (!property.file_uploadable) {
25
+ newProperties[key] = property;
26
+ continue;
27
+ }
28
+ newProperties[key] = {
29
+ ...property,
30
+ format: 'path',
31
+ };
32
+ }
33
+
34
+ return properties;
35
+};
36
+
37
+export class FileToolModifier {
38
+ private client: ComposioClient;
39
+
40
+ constructor(client: ComposioClient) {
41
+ this.client = client;
42
+ }
43
+
44
+ /**
45
+ * Modifies the tool schema to include the file upload URL.
46
+ *
47
+ * @description This modifier is used to upload a file to the Composio platform and replace the file path with the file upload URL.
48
+ *
49
+ * @param _toolSlug - The slug of the tool that is being executed.
50
+ * @param _toolkitSlug - The slug of the toolkit that is being executed.
51
+ * @param schema - The schema of the tool.
52
+ * @returns The schema with the file upload URL included.
53
+ */
54
+ async modifyToolSchema(toolSlug: string, toolkitSlug: string, schema: Tool): Promise<Tool> {
55
+ if (!schema.inputParameters?.properties) {
56
+ return schema;
57
+ }
58
+
59
+ const properties = transformProperties(schema.inputParameters.properties);
60
+
61
+ return {
62
+ ...schema,
63
+ inputParameters: {
64
+ ...schema.inputParameters,
65
+ properties,
66
+ },
67
+ };
68
+ }
69
+
70
+ /**
71
+ * Modifies the input parameters to include the file upload URL.
72
+ *
73
+ * @description This modifier is used to upload a file to the Composio platform and replace the file path with the file upload URL.
74
+ *
75
+ * @param toolSlug - The slug of the tool that is being executed.
76
+ * @param toolkitSlug - The slug of the toolkit that is being executed.
77
+ *
78
+ */
79
+ async fileUploadModifier(
80
+ tool: Tool,
81
+ options: { toolSlug: string; toolkitSlug: string; params: ToolExecuteParams }
82
+ ): Promise<ToolExecuteParams> {
83
+ const { arguments: args } = options.params;
84
+ if (!args) {
85
+ return options.params;
86
+ }
87
+ // Check if the arguments is an object
88
+ for (const key of Object.keys(args)) {
89
+ // Check if the key ends with _schema_parsed_file and is a string
90
+ const toolProperty = tool.inputParameters?.properties?.[key];
91
+
92
+ if (toolProperty?.file_uploadable) {
93
+ logger.debug(`Processing file upload for: ${key}`);
94
+ try {
95
+ const fileData = await getFileDataAfterUploadingToS3(
96
+ args[key] as string,
97
+ options.toolSlug,
98
+ options.toolkitSlug ?? 'unknown',
99
+ this.client
100
+ );
101
+ args[key] = fileData;
102
+ } catch (error) {
103
+ throw new ComposioFileUploadError(`Failed to upload file: ${key}`, {
104
+ cause: error,
105
+ });
106
+ }
107
+ }
108
+ }
109
+ return options.params;
110
+ }
111
+
112
+ /**
113
+ * Modifies the result to include the file download URL.
114
+ *
115
+ * @description This modifier is used to download a file and
116
+ *
117
+ * @param toolSlug - The slug of the tool that is being executed.
118
+ * @param toolkitSlug - The slug of the toolkit that is being executed.
119
+ * @param result - The result of the tool execution.
120
+ * @returns The result with the file download URL included.
121
+ */
122
+ async fileDownloadModifier(
123
+ tool: Tool,
124
+ options: {
125
+ toolSlug: string;
126
+ toolkitSlug: string;
127
+ result: ToolExecuteResponse;
128
+ }
129
+ ): Promise<ToolExecuteResponse> {
130
+ console.log(JSON.stringify(options.result, null, 2));
131
+ console.log(JSON.stringify(tool.outputParameters, null, 2));
132
+ for (const [key, value] of Object.entries(options.result?.data)) {
133
+ const fileData = value as { s3url?: string; mimetype?: string };
134
+
135
+ if (!fileData?.s3url) continue;
136
+
137
+ logger.debug(`Downloading file from S3: ${fileData.s3url}`);
138
+
139
+ try {
140
+ const downloadedFile = await downloadFileFromS3({
141
+ toolSlug: options.toolSlug,
142
+ s3Url: fileData.s3url,
143
+ mimeType: fileData.mimetype || 'application/txt',
144
+ });
145
+
146
+ logger.debug(`Downloaded file from S3: ${downloadedFile.filePath}`);
147
+
148
+ options.result.data[key] = {
149
+ uri: downloadedFile.filePath,
150
+ file_downloaded: true,
151
+ s3url: fileData.s3url,
152
+ mimeType: downloadedFile.mimeType,
153
+ };
154
+ } catch (error) {
155
+ logger.error(`Failed to download file from S3: ${fileData.s3url}`, {
156
+ cause: error,
157
+ });
158
+ options.result.data[key] = {
159
+ uri: '',
160
+ file_downloaded: false,
161
+ s3url: fileData.s3url,
162
+ mimeType: fileData.mimetype || 'application/txt',
163
+ };
164
+ }
165
+ }
166
+ return options.result;
167
+ }
168
+}
ts/scripts/create-example.sh
+1
-1
@@ -8,7 +8,7 @@ if [ -z "$1" ]; then
8
fi
9
10
EXAMPLE_NAME=$1
11
-EXAMPLE_PATH="examples/$EXAMPLE_NAME"
11
+EXAMPLE_PATH="ts/examples/$EXAMPLE_NAME"
12
CAPITAL_EXAMPLE_NAME="$(tr '[:lower:]' '[:upper:]' <<< ${EXAMPLE_NAME:0:1})${EXAMPLE_NAME:1}"
13
14
# Check if example directory already exists
ts/scripts/create-provider.sh
+1
-1
@@ -8,7 +8,7 @@ if [ -z "$1" ]; then
8
fi
9
10
TOOLSET_NAME=$1
11
-TOOLSET_PATH="packages/providers/$TOOLSET_NAME"
11
+TOOLSET_PATH="ts/packages/providers/$TOOLSET_NAME"
12
CAPITAL_TOOLSET_NAME="$(tr '[:lower:]' '[:upper:]' <<< ${TOOLSET_NAME:0:1})${TOOLSET_NAME:1}"
13
14
# Check if provider should be agentic
ts/scripts/update-peer-deps.ts
+1
-1
@@ -6,7 +6,7 @@
6
import fs from 'fs';
7
import path from 'path';
8
9
-const corePkgPackageJson = path.resolve(__dirname, '../packages/core', 'package.json');
9
+const corePkgPackageJson = path.resolve(__dirname, '../ts/packages/core', 'package.json');
10
const corePkg = JSON.parse(fs.readFileSync(corePkgPackageJson, 'utf-8'));
11
const coreVersion = corePkg.version;
12