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 23, 00:30 UTC
Add telemetry support for sdk (#1633)
Musthaq Ahamad committed
Jun 13, 2025 at 17:48 UTC
d1a958526e0d0a43b72f95fa1d91d9f2c83e866a
45 files changed
+1164
-1623
.github/workflows/build.yml
+1
-1
@@ -32,4 +32,4 @@ jobs:
32
run: pnpm lint
33
34
- name: Run Build
35
- run: pnpm run build
35
+ run: pnpm run build:packages
apps/telemetry-proxy/.gitignore
deleted
-39
@@ -1,39 +0,0 @@
1
-# prod
2
-dist/
3
-
4
-# dev
5
-.yarn/
6
-!.yarn/releases
7
-.vscode/*
8
-!.vscode/launch.json
9
-!.vscode/*.code-snippets
10
-.idea/workspace.xml
11
-.idea/usage.statistics.xml
12
-.idea/shelf
13
-
14
-# deps
15
-node_modules/
16
-.wrangler
17
-
18
-# env
19
-.env
20
-.env.production
21
-.dev.vars
22
-
23
-# logs
24
-logs/
25
-*.log
26
-npm-debug.log*
27
-yarn-debug.log*
28
-yarn-error.log*
29
-pnpm-debug.log*
30
-lerna-debug.log*
31
-
32
-# misc
33
-.DS_Store
34
-
35
-
36
-# env
37
-.dev.vars
38
-.env
39
-.wrangler
\ No newline at end of file
apps/telemetry-proxy/README.md
deleted
-21
@@ -1,21 +0,0 @@
1
-```txt
2
-npm install
3
-npm run dev
4
-```
5
-
6
-```txt
7
-npm run deploy
8
-```
9
-
10
-[For generating/synchronizing types based on your Worker configuration run](https://developers.cloudflare.com/workers/wrangler/commands/#types):
11
-
12
-```txt
13
-npm run cf-typegen
14
-```
15
-
16
-Pass the `CloudflareBindings` as generics when instantiation `Hono`:
17
-
18
-```ts
19
-// src/index.ts
20
-const app = new Hono<{ Bindings: CloudflareBindings }>()
21
-```
apps/telemetry-proxy/package.json
deleted
-19
@@ -1,19 +0,0 @@
1
-{
2
- "name": "@composio/telemetry-proxy",
3
- "version": "0.0.1",
4
- "private": true,
5
- "type": "module",
6
- "scripts": {
7
- "dev": "wrangler dev",
8
- "deploy": "wrangler deploy --minify",
9
- "cf-typegen": "wrangler types --env-interface CloudflareBindings"
10
- },
11
- "dependencies": {
12
- "@hono/zod-openapi": "^0.19.8",
13
- "hono": "^4.7.11",
14
- "zod": "^3.24.2"
15
- },
16
- "devDependencies": {
17
- "wrangler": "^4.4.0"
18
- }
19
-}
apps/telemetry-proxy/src/index.ts
deleted
-15
@@ -1,15 +0,0 @@
1
-import telemetry from './routes/v1/telemetry';
2
-import { AppBindings } from './types/app.types';
3
-import { OpenAPIHono } from '@hono/zod-openapi';
4
-
5
-const app = new OpenAPIHono<{ Bindings: AppBindings }>();
6
-app.route('/v1', telemetry);
7
-app.doc('/docs', {
8
- openapi: '3.0.0',
9
- info: {
10
- title: 'Composio Telemetry API',
11
- version: '1.0.0',
12
- },
13
-});
14
-
15
-export default app;
apps/telemetry-proxy/src/lib/errors.ts
deleted
-57
@@ -1,57 +0,0 @@
1
-import { ErrorLogPayload, ErrorLogPayloadSchema } from '../types/errors.types';
2
-
3
-const getLogTags = (errorData: ErrorLogPayload) => {
4
- const { source, metadata } = errorData;
5
- return [
6
- ...(source?.name ? [`source:${source.name}`] : []),
7
- ...(source?.service ? [`service:${source.service}`] : []),
8
- ...(source?.language ? [`language:${source.language}`] : []),
9
- ...(source?.version ? [`version:${source.version}`] : []),
10
- ...(source?.platform ? [`platform:${source.platform}`] : []),
11
- ...(metadata?.projectId ? [`project_id:${metadata.projectId}`] : []),
12
- ...(metadata?.provider ? [`provider:${metadata.provider}`] : []),
13
- 'status:error',
14
- 'level:error',
15
- ]
16
- .filter(Boolean)
17
- .join(',');
18
-};
19
-
20
-const getLogHost = (errorData: ErrorLogPayload) => {
21
- const { source } = errorData;
22
- return `composio-${source?.service}-${source?.language}`;
23
-};
24
-
25
-export const createErrorLogPayload = (errorData: ErrorLogPayload) => {
26
- const logBody = {
27
- message: errorData.message,
28
- ddtags: getLogTags(errorData),
29
- hostname: getLogHost(errorData),
30
- service: getLogHost(errorData),
31
- };
32
- return logBody;
33
-};
34
-
35
-export async function sendErrorLogToDatadog(errorData: ErrorLogPayload, datadogApiKey: string) {
36
- const parsedPayload = ErrorLogPayloadSchema.safeParse(errorData);
37
- if (parsedPayload.error) {
38
- throw parsedPayload.error;
39
- }
40
-
41
- const logBody = createErrorLogPayload(parsedPayload.data);
42
-
43
- const res = await fetch('https://api.datadoghq.com/api/v1/series', {
44
- method: 'POST',
45
- headers: {
46
- 'Content-Type': 'application/json',
47
- 'DD-API-KEY': datadogApiKey,
48
- },
49
- body: JSON.stringify(logBody),
50
- });
51
-
52
- if (!res.ok) {
53
- console.error('Failed to send error log to Datadog:', await res.text());
54
- }
55
-
56
- return res.ok;
57
-}
apps/telemetry-proxy/src/lib/metrics.ts
deleted
-105
@@ -1,105 +0,0 @@
1
-import {
2
- DDMetricPayload,
3
- DDMetricPayloadSchema,
4
- TelemetryMetricPayload,
5
- TelemetryMetricPayloadSchema,
6
-} from '../types/metrics.types';
7
-
8
-const getMetricName = (
9
- type: 'function_invocation' | 'function_duration',
10
- payload: TelemetryMetricPayload
11
-) => {
12
- const { functionName, source } = payload;
13
- if (source?.service === 'sdk') {
14
- return `composio.${source.service}.${type}`;
15
- }
16
- return `composio.sdk.${type}`;
17
-};
18
-
19
-const getMetricTags = (payload: TelemetryMetricPayload) => {
20
- const { functionName, source, metadata, error } = payload;
21
- return [
22
- `function:${functionName}`,
23
- ...(source?.name ? [`source:${source.name}`] : []),
24
- ...(source?.service ? [`service:${source.service}`] : []),
25
- ...(source?.language ? [`language:${source.language}`] : []),
26
- ...(source?.version ? [`version:${source.version}`] : []),
27
- ...(source?.platform ? [`platform:${source.platform}`] : []),
28
- ...(metadata?.projectId ? [`project_id:${metadata.projectId}`] : []),
29
- ...(metadata?.provider ? [`provider:${metadata.provider}`] : []),
30
- ...(error ? ['status:error'] : ['status:success']),
31
- ];
32
-};
33
-
34
-const getMetricHost = (payload: TelemetryMetricPayload) => {
35
- const { source } = payload;
36
- return `composio-${source?.service}-${source?.language}`;
37
-};
38
-
39
-const createDDMetricPayload = (
40
- type: 'count' | 'gauge',
41
- payload: TelemetryMetricPayload
42
-): DDMetricPayload => {
43
- const { durationMs, timestamp } = payload;
44
- const executionTimestamp = timestamp ?? Math.floor(Date.now() / 1000);
45
- const executionDuration = durationMs ?? 1;
46
-
47
- const parsedPayload = DDMetricPayloadSchema.safeParse({
48
- host: getMetricHost(payload),
49
- metric: getMetricName('function_invocation', payload),
50
- points: [[executionTimestamp, executionDuration]],
51
- tags: getMetricTags(payload),
52
- type,
53
- });
54
-
55
- if (parsedPayload.error) {
56
- throw parsedPayload.error;
57
- }
58
-
59
- return parsedPayload.data;
60
-};
61
-
62
-/**
63
- * Creates a metric payload for Datadog.
64
- *
65
- * @description This function creates a metric payload for Datadog. It returns an array of two
66
- * objects, one for the count metric and one for the duration metric.
67
- *
68
- * @param payload - The payload to create a metric for.
69
- * @returns An array of two objects, one for the count metric and one for the duration metric.
70
- */
71
-export const createMetricPayload = (payload: TelemetryMetricPayload): Array<DDMetricPayload> => {
72
- const parsedPayload = TelemetryMetricPayloadSchema.safeParse(payload);
73
- if (parsedPayload.error) {
74
- throw parsedPayload.error;
75
- }
76
-
77
- const DDMetricCountPayload = createDDMetricPayload('count', payload);
78
- const DDMetricDurationPayload = createDDMetricPayload('gauge', payload);
79
-
80
- return [DDMetricCountPayload, DDMetricDurationPayload];
81
-};
82
-
83
-export const sendMetricToDatadog = async (
84
- payload: Array<TelemetryMetricPayload>,
85
- datadogApiKey: string
86
-) => {
87
- const parsedPayload = payload.map(item => createMetricPayload(item)).flat();
88
- console.log(JSON.stringify(parsedPayload, null, 2));
89
- const res = await fetch('https://api.datadoghq.com/api/v1/series', {
90
- method: 'POST',
91
- headers: {
92
- 'Content-Type': 'application/json',
93
- 'DD-API-KEY': datadogApiKey,
94
- },
95
- body: JSON.stringify({
96
- series: parsedPayload,
97
- }),
98
- });
99
-
100
- if (!res.ok) {
101
- console.error('Failed to send metric payload to Datadog:', await res.text());
102
- }
103
-
104
- return res.ok;
105
-};
apps/telemetry-proxy/src/routes/v1/telemetry.ts
deleted
-120
@@ -1,120 +0,0 @@
1
-import {
2
- TelemetryMetricPayload,
3
- TelemetryMetricPayloadSchema,
4
- TelemetryMetricRequestSchema,
5
-} from '../../types/metrics.types';
6
-import { AppBindings } from '../../types/app.types';
7
-import { sendMetricToDatadog } from '../../lib/metrics';
8
-import { sendErrorLogToDatadog } from '../../lib/errors';
9
-import { ErrorLogPayload, ErrorLogPayloadSchema } from '../../types/errors.types';
10
-import { createRoute, OpenAPIHono, z } from '@hono/zod-openapi';
11
-
12
-const app = new OpenAPIHono<{ Bindings: AppBindings }>();
13
-
14
-const metricsRoute = createRoute({
15
- method: 'post',
16
- path: '/metrics/invocations',
17
- tags: ['telemetry'],
18
- request: {
19
- body: {
20
- content: {
21
- 'application/json': {
22
- schema: TelemetryMetricRequestSchema,
23
- },
24
- },
25
- },
26
- },
27
- responses: {
28
- 200: {
29
- description: 'The success of the request',
30
- content: {
31
- 'application/json': {
32
- schema: z.object({ success: z.boolean() }),
33
- },
34
- },
35
- },
36
- 400: {
37
- description: 'Invalid request body',
38
- content: {
39
- 'application/json': {
40
- schema: z.object({
41
- success: z.boolean(),
42
- error: z.string(),
43
- }),
44
- },
45
- },
46
- },
47
- },
48
-});
49
-
50
-const errorsRoute = createRoute({
51
- method: 'post',
52
- path: '/errors',
53
- tags: ['telemetry'],
54
- request: {
55
- body: {
56
- content: {
57
- 'application/json': {
58
- schema: ErrorLogPayloadSchema,
59
- },
60
- },
61
- },
62
- },
63
- responses: {
64
- 200: {
65
- description: 'The success of the request',
66
- content: {
67
- 'application/json': {
68
- schema: z.object({ success: z.boolean() }),
69
- },
70
- },
71
- },
72
- 400: {
73
- description: 'Invalid request body',
74
- content: {
75
- 'application/json': {
76
- schema: z.object({
77
- success: z.boolean(),
78
- error: z.string(),
79
- }),
80
- },
81
- },
82
- },
83
- },
84
-});
85
-
86
-app.openapi(metricsRoute, async c => {
87
- try {
88
- const rawBody = await c.req.json();
89
- const result = TelemetryMetricRequestSchema.safeParse(rawBody);
90
-
91
- if (!result.success) {
92
- return c.json({ success: false, error: 'Invalid request body' }, 400);
93
- }
94
-
95
- const apiKey = c.env.DATADOG_API_KEY as string;
96
- const res = await sendMetricToDatadog(result.data, apiKey);
97
- return c.json({ success: res, error: '' }, res ? 200 : 400);
98
- } catch (error) {
99
- return c.json({ success: false, error: 'Failed to process request' }, 400);
100
- }
101
-});
102
-
103
-app.openapi(errorsRoute, async c => {
104
- try {
105
- const rawBody = await c.req.json();
106
- const result = ErrorLogPayloadSchema.safeParse(rawBody);
107
-
108
- if (!result.success) {
109
- return c.json({ success: false, error: 'Invalid request body' }, 400);
110
- }
111
-
112
- const apiKey = c.env.DATADOG_API_KEY as string;
113
- const res = await sendErrorLogToDatadog(result.data, apiKey);
114
- return c.json({ success: res, error: '' }, res ? 200 : 400);
115
- } catch (error) {
116
- return c.json({ success: false, error: 'Failed to process request' }, 400);
117
- }
118
-});
119
-
120
-export default app;
apps/telemetry-proxy/src/types/app.types.ts
deleted
-3
@@ -1,3 +0,0 @@
1
-export interface AppBindings {
2
- DATADOG_API_KEY: string;
3
-}
apps/telemetry-proxy/src/types/errors.types.ts
deleted
-14
@@ -1,14 +0,0 @@
1
-import { z } from '@hono/zod-openapi';
2
-import { TelemetryMetricMetadataSchema, TelemetryMetricSourceSchema } from './telemetry.types';
3
-
4
-export const ErrorLogPayloadSchema = z.object({
5
- functionName: z.string().describe('The name of the function that was invoked'),
6
- errorName: z.string().describe('The name of the error').optional(),
7
- message: z.string().describe('The message of the error').optional(),
8
- stack: z.string().describe('The stack trace of the error').optional(),
9
- timestamp: z.number().describe('The timestamp of the error in epoch milliseconds').optional(),
10
- props: z.record(z.any()).optional().describe('The properties of the error'),
11
- source: TelemetryMetricSourceSchema.optional(),
12
- metadata: TelemetryMetricMetadataSchema.optional(),
13
-});
14
-export type ErrorLogPayload = z.infer<typeof ErrorLogPayloadSchema>;
apps/telemetry-proxy/src/types/metrics.types.ts
deleted
-47
@@ -1,47 +0,0 @@
1
-import { z } from '@hono/zod-openapi';
2
-import { TelemetryMetricSourceSchema } from './telemetry.types';
3
-import { TelemetryMetricMetadataSchema } from './telemetry.types';
4
-
5
-export const TelemetryMetricPayloadSchema = z.object({
6
- functionName: z.string().describe('The name of the function that was invoked'),
7
- durationMs: z.number().describe('The duration of the function invocation in milliseconds'),
8
- timestamp: z.number().describe('The timestamp of the function invocation in epoch milliseconds'),
9
- props: z.record(z.any()).optional().describe('The properties of the function invocation'),
10
- source: TelemetryMetricSourceSchema.optional(),
11
- metadata: TelemetryMetricMetadataSchema.optional(),
12
- error: z
13
- .object({
14
- name: z.string().describe('The name of the error'),
15
- message: z.string().describe('The message of the error'),
16
- })
17
- .optional()
18
- .describe('The error that occurred during the function invocation'),
19
-});
20
-
21
-export type TelemetryMetricSource = z.infer<typeof TelemetryMetricSourceSchema>;
22
-export type TelemetryMetricMetadata = z.infer<typeof TelemetryMetricMetadataSchema>;
23
-export type TelemetryMetricPayload = z.infer<typeof TelemetryMetricPayloadSchema>;
24
-
25
-export const TelemetryMetricRequestSchema = z.array(TelemetryMetricPayloadSchema);
26
-export type TelemetryMetricRequest = z.infer<typeof TelemetryMetricRequestSchema>;
27
-
28
-// {
29
-// metric: 'composio.sdk.function_invocation',
30
-// type: 'count',
31
-// points: [[Math.floor(Date.now() / 1000), 1]],
32
-// tags: [
33
-// `function:${body.functionName}`,
34
-// ...(body.error ? ['status:error'] : ['status:success']),
35
-// ],
36
-// host: 'composio-sdk',
37
-// },
38
-export const DDMetricPayloadSchema = z.object({
39
- metric: z.string().describe('The name of the metric'),
40
- type: z
41
- .enum(['count', 'gauge', 'histogram', 'distribution', 'rate'])
42
- .describe('The type of the metric'),
43
- points: z.array(z.array(z.number())).describe('The points of the metric'),
44
- tags: z.array(z.string()).describe('The tags of the metric'),
45
- host: z.string().describe('The host of the metric'),
46
-});
47
-export type DDMetricPayload = z.infer<typeof DDMetricPayloadSchema>;
apps/telemetry-proxy/src/types/telemetry.types.ts
deleted
-20
@@ -1,20 +0,0 @@
1
-import { z } from '@hono/zod-openapi';
2
-
3
-export const TelemetryMetricSourceSchema = z.object({
4
- name: z.string().describe('The name of the source').optional(),
5
- service: z
6
- .enum(['sdk', 'apollo', 'hermes', 'thermos'])
7
- .describe('The service of the source')
8
- .optional(),
9
- language: z
10
- .enum(['python', 'typescript', 'go', 'rust'])
11
- .describe('The language of the function that was invoked')
12
- .optional(),
13
- version: z.string().describe('The version of the source').optional(),
14
- platform: z.string().describe('The platform of the source').optional(),
15
-});
16
-
17
-export const TelemetryMetricMetadataSchema = z.object({
18
- projectId: z.string().describe('The project ID of the source').optional(),
19
- provider: z.string().describe('The provider used in the source').optional(),
20
-});
apps/telemetry-proxy/tsconfig.json
deleted
-14
@@ -1,14 +0,0 @@
1
-{
2
- "compilerOptions": {
3
- "target": "ESNext",
4
- "module": "ESNext",
5
- "moduleResolution": "Bundler",
6
- "strict": true,
7
- "skipLibCheck": true,
8
- "lib": [
9
- "ESNext"
10
- ],
11
- "jsx": "react-jsx",
12
- "jsxImportSource": "hono/jsx"
13
- },
14
-}
\ No newline at end of file
apps/telemetry-proxy/wrangler.jsonc
deleted
-38
@@ -1,38 +0,0 @@
1
-{
2
- "$schema": "node_modules/wrangler/config-schema.json",
3
- "name": "telemetry-proxy",
4
- "main": "src/index.ts",
5
- "compatibility_date": "2025-06-11",
6
- // "compatibility_flags": [
7
- // "nodejs_compat"
8
- // ],
9
- // "vars": {
10
- // "MY_VAR": "my-variable"
11
- // },
12
- // "kv_namespaces": [
13
- // {
14
- // "binding": "MY_KV_NAMESPACE",
15
- // "id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
16
- // }
17
- // ],
18
- // "r2_buckets": [
19
- // {
20
- // "binding": "MY_BUCKET",
21
- // "bucket_name": "my-bucket"
22
- // }
23
- // ],
24
- // "d1_databases": [
25
- // {
26
- // "binding": "MY_DB",
27
- // "database_name": "my-database",
28
- // "database_id": ""
29
- // }
30
- // ],
31
- // "ai": {
32
- // "binding": "AI"
33
- // },
34
- // "observability": {
35
- // "enabled": true,
36
- // "head_sampling_rate": 1
37
- // }
38
-}
examples/json-schema-to-zod/.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
examples/json-schema-to-zod/README.md
new
+53
@@ -0,0 +1,53 @@
1
+# Json-schema-to-zod Example
2
+
3
+This example demonstrates how to use Composio SDK for json-schema-to-zod.
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)
examples/json-schema-to-zod/package.json
new
+29
@@ -0,0 +1,29 @@
1
+{
2
+ "name": "json-schema-to-zod-example",
3
+ "private": true,
4
+ "version": "0.1.0",
5
+ "description": "Example project for Json-schema-to-zod",
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": [
13
+ "composio",
14
+ "example",
15
+ "json-schema-to-zod"
16
+ ],
17
+ "author": "",
18
+ "license": "ISC",
19
+ "packageManager": "pnpm@10.8.0",
20
+ "dependencies": {
21
+ "@composio/core": "workspace:*",
22
+ "dotenv": "^16.4.1",
23
+ "zod-to-json-schema": "^3.24.5"
24
+ },
25
+ "devDependencies": {
26
+ "@types/bun": "^1.2.9",
27
+ "typescript": "^5.8.3"
28
+ }
29
+}
examples/json-schema-to-zod/src/index.ts
new
+48
@@ -0,0 +1,48 @@
1
+/**
2
+ * Json-schema-to-zod Example
3
+ *
4
+ * This example demonstrates how to use Composio SDK for json-schema-to-zod.
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, jsonSchemaToZodSchema } from '@composio/core';
12
+import { zodToJsonSchema } from 'zod-to-json-schema';
13
+import 'dotenv/config';
14
+
15
+/**
16
+ * Initialize Composio
17
+ */
18
+const composio = new Composio({
19
+ apiKey: process.env.COMPOSIO_API_KEY,
20
+});
21
+
22
+/**
23
+ * Main function to run the example
24
+ */
25
+async function main() {
26
+ try {
27
+ console.log('🚀 Starting Json-schema-to-zod Example...');
28
+
29
+ // Get available tools
30
+ const tool = await composio.tools.getRawComposioToolBySlug(
31
+ 'default',
32
+ 'GOOGLECALENDAR_PATCH_EVENT'
33
+ );
34
+
35
+ console.log(JSON.stringify(tool.inputParameters, null, 2));
36
+
37
+ const zodSchema = jsonSchemaToZodSchema(tool.inputParameters ?? {});
38
+
39
+ console.log(JSON.stringify(zodToJsonSchema(zodSchema), null, 2));
40
+ // TODO: Add your example implementation here
41
+ console.log('📝 Implement your json-schema-to-zod logic here!');
42
+ } catch (error) {
43
+ console.error('❌ Error running example:', error);
44
+ }
45
+}
46
+
47
+// Run the example
48
+main().catch(console.error);
examples/json-schema-to-zod/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
+}
examples/modifiers/src/index.ts
+7
-4
@@ -15,10 +15,13 @@ const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER', {
15
toolSchema = {
16
...toolSchema,
17
inputParameters: {
18
- ...toolSchema.inputParameters,
19
- userId: {
20
- type: 'string',
21
- description: 'The user ID to get the user for',
18
+ type: 'object',
19
+ properties: {
20
+ ...toolSchema.inputParameters?.properties,
21
+ userId: {
22
+ type: 'string',
23
+ description: 'The user ID to get the user for',
24
+ },
25
},
26
},
27
};
examples/toolkits/src/auth-fields.ts
new
+20
@@ -0,0 +1,20 @@
1
+import { Composio } from '@composio/core';
2
+
3
+const composio = new Composio({
4
+ apiKey: process.env.COMPOSIO_API_KEY,
5
+});
6
+
7
+const toolkitSlug = 'shopify';
8
+
9
+console.log('🔄 Getting auth config creation fields for toolkit: ', toolkitSlug);
10
+const authConfigCreationFields = await composio.toolkits.getAuthConfigCreationFields(toolkitSlug);
11
+
12
+console.log('✅ Auth config creation fields:');
13
+console.log(authConfigCreationFields);
14
+
15
+console.log('🔄 Getting connected account initiation fields for toolkit: ', toolkitSlug);
16
+const connectedAccountInitiationFields =
17
+ await composio.toolkits.getConnectedAccountInitiationFields(toolkitSlug);
18
+
19
+console.log('✅ Connected account initiation fields:');
20
+console.log(connectedAccountInitiationFields);
packages/core/package.json
+3
-3
@@ -37,15 +37,15 @@
37
"vitest": "^3.1.4"
38
},
39
"dependencies": {
40
- "@composio/client": "0.1.0-alpha.17",
40
+ "@composio/client": "0.1.0-alpha.22",
41
"@composio/json-schema-to-zod": "0.1.6",
42
- "zod-to-json-schema": "^3.24.5",
42
"chalk": "^5.4.1",
43
"openai": "^4.94.0",
44
"pusher-js": "^8.4.0",
45
"semver": "^7.7.2",
46
"uuid": "^11.1.0",
48
- "zod": "^3.24.2"
47
+ "zod": "^3.24.2",
48
+ "zod-to-json-schema": "^3.24.5"
49
},
50
"gitHead": "4fae6e54d5c150fba955cc5fa314281da5a1e064"
51
}
packages/core/src/composio.ts
+14
-19
@@ -6,7 +6,6 @@ import { AuthConfigs } from './models/AuthConfigs';
6
import { ConnectedAccounts } from './models/ConnectedAccounts';
7
import { BaseComposioProvider } from './provider/BaseProvider';
8
import { telemetry } from './telemetry/Telemetry';
9
-import { BaseTelemetryTransport } from './telemetry/TelemetryTransport';
9
import { getSDKConfig } from './utils/sdk';
10
import logger from './utils/logger';
11
import { IS_DEVELOPMENT_OR_CI } from './utils/constants';
@@ -25,7 +24,6 @@ export type ComposioConfig<
24
allowTracking?: boolean;
25
allowTracing?: boolean;
26
provider?: TProvider;
28
- telemetryTransport?: BaseTelemetryTransport;
27
/**
28
* Request options to be passed to the Composio API client.
29
* This is useful for passing in a custom fetch implementation.
@@ -82,7 +80,6 @@ export class Composio<TProvider extends BaseComposioProvider<unknown, unknown> =
80
* @param {boolean} [config.allowTracking=true] - Whether to allow anonymous usage analytics
81
* @param {boolean} [config.allowTracing=true] - Whether to allow request tracing for debugging
82
* @param {TProvider} [config.provider] - The provider to use for this Composio instance (defaults to OpenAIProvider)
85
- * @param {BaseTelemetryTransport} [config.telemetryTransport] - Custom telemetry transport implementation
83
*
84
* @example
85
* ```typescript
@@ -150,22 +147,20 @@ export class Composio<TProvider extends BaseComposioProvider<unknown, unknown> =
147
* Initialize the client telemetry.
148
*/
149
if (this.config.allowTracking) {
153
- telemetry.setup(
154
- {
155
- apiKey: apiKeyParsed ?? '',
156
- baseUrl: baseURLParsed ?? '',
157
- frameworkRuntime: this.provider?.name ?? 'unknown',
158
- isAgentic: this.provider?._isAgentic || false,
159
- source: 'javascript',
160
- version: version,
161
- sdkType: 'Typescript-V3',
162
- isBrowser: typeof window !== 'undefined',
163
- // @TODO: Users might want to pass their own session id
164
- // @TODO: We shouldn't be doing this as people might always have one session id throughout the process in server
165
- sessionId: this.config.allowTracing ? getRandomUUID() : undefined, // @TODO: get the session id
166
- },
167
- config?.telemetryTransport
168
- );
150
+ telemetry.setup({
151
+ apiKey: apiKeyParsed ?? '',
152
+ baseUrl: baseURLParsed ?? '',
153
+ frameworkRuntime: this.provider?.name ?? 'unknown',
154
+ isAgentic: this.provider?._isAgentic || false,
155
+ source: 'composio-sdk-typescript',
156
+ version: version,
157
+ sdkType: 'Typescript-V3',
158
+ isBrowser: typeof window !== 'undefined',
159
+ provider: this.provider?.name ?? 'openai',
160
+ // @TODO: Users might want to pass their own session id
161
+ // @TODO: We shouldn't be doing this as people might always have one session id throughout the process in server
162
+ sessionId: this.config.allowTracing ? getRandomUUID() : undefined, // @TODO: get the session id
163
+ });
164
}
165
telemetry.instrument(this);
166
// instrument the provider since we are not using the provider class directly
packages/core/src/index.ts
-1
@@ -4,7 +4,6 @@ export { ComposioProvider } from './provider/ComposioProvider';
4
export { BaseAgenticProvider, BaseNonAgenticProvider } from './provider/BaseProvider';
5
export type { BaseComposioProvider } from './provider/BaseProvider';
6
export { OpenAIProvider } from './provider/OpenAIProvider';
7
-export { BaseTelemetryTransport, ConsoleTelemetryTransport } from './telemetry/TelemetryTransport';
7
export { jsonSchemaToZodSchema } from './utils/jsonSchema';
8
export { AuthScheme } from './models/AuthScheme';
9
export * from './types/provider.types';
packages/core/src/models/Toolkits.ts
+113
-1
@@ -10,6 +10,8 @@ import {
10
ToolkitRetrieveCategoriesResponse,
11
ToolkitRetrieveCategoriesResponseSchema,
12
ToolkitCategorySchema,
13
+ ToolkitAuthField,
14
+ ToolkitAuthFieldsResponse,
15
} from '../types/toolkit.types';
16
import { ComposioToolkitFetchError, ComposioToolkitNotFoundError } from '../errors';
17
import { ValidationError } from '../errors/ValidationErrors';
@@ -18,6 +20,8 @@ import { ComposioAuthConfigNotFoundError } from '../errors/AuthConfigErrors';
20
import { ConnectedAccounts } from './ConnectedAccounts';
21
import { ConnectionRequest } from './ConnectionRequest';
22
import { telemetry } from '../telemetry/Telemetry';
23
+import { AuthSchemeEnum, AuthSchemeType } from '../types/authConfigs.types';
24
+import logger from '../utils/logger';
25
/**
26
* Toolkits class
27
*
@@ -113,7 +117,7 @@ export class Toolkits {
117
*
118
* @private
119
*/
116
- private async getToolkitBySlug(slug: string): Promise<ToolkitRetrieveResponse> {
120
+ protected async getToolkitBySlug(slug: string): Promise<ToolkitRetrieveResponse> {
121
try {
122
const result = await this.client.toolkits.retrieve(slug);
123
const parsedResult = ToolkitRetrieveResponseSchema.safeParse({
@@ -221,6 +225,114 @@ export class Toolkits {
225
return this.getToolkits(arg);
226
}
227
228
+ private async getAuthConfigFields(
229
+ toolkitSlug: string,
230
+ authScheme: AuthSchemeType | null,
231
+ authConfigType: 'authConfigCreation' | 'connectedAccountInitiation',
232
+ requiredOnly: boolean
233
+ ): Promise<ToolkitAuthFieldsResponse> {
234
+ const toolkit = await this.getToolkitBySlug(toolkitSlug);
235
+ if (!toolkit.authConfigDetails) {
236
+ throw new ComposioAuthConfigNotFoundError('No auth config found for toolkit', {
237
+ meta: {
238
+ toolkitSlug,
239
+ },
240
+ });
241
+ }
242
+
243
+ // if multiple auth configs are found, warn the user and select the first one
244
+ if (toolkit.authConfigDetails.length > 1 && !authScheme) {
245
+ logger.warn(
246
+ `Multiple auth configs found for ${toolkitSlug}, please specify the auth scheme to get details of specific auth scheme. Selecting the first scheme by default.`,
247
+ {
248
+ meta: {
249
+ toolkitSlug,
250
+ },
251
+ }
252
+ );
253
+ }
254
+
255
+ // if authScheme is provided, find the auth config for the given auth scheme
256
+ // otherwise, use the first auth config
257
+ const authConfig = authScheme
258
+ ? toolkit.authConfigDetails.find(authConfig => authConfig.mode === authScheme)
259
+ : toolkit.authConfigDetails[0];
260
+
261
+ if (!authConfig) {
262
+ throw new ComposioAuthConfigNotFoundError('No auth config found for toolkit', {
263
+ meta: {
264
+ toolkitSlug,
265
+ authScheme,
266
+ },
267
+ });
268
+ }
269
+
270
+ const requiredFields = authConfig.fields[authConfigType].required.map(field => ({
271
+ ...field,
272
+ required: true,
273
+ }));
274
+ if (requiredOnly) {
275
+ return {
276
+ authScheme: AuthSchemeEnum.parse(authConfig.mode),
277
+ fields: requiredFields,
278
+ };
279
+ }
280
+
281
+ const optionalFields = authConfig.fields[authConfigType].optional.map(field => ({
282
+ ...field,
283
+ required: false,
284
+ }));
285
+
286
+ return {
287
+ authScheme: AuthSchemeEnum.parse(authConfig.mode),
288
+ fields: [...requiredFields, ...optionalFields],
289
+ };
290
+ }
291
+
292
+ /**
293
+ * Retrieves the fields required for creating an auth config for a toolkit.
294
+ * @param toolkitSlug - The slug of the toolkit to retrieve the fields for
295
+ * @param authScheme - The auth scheme to retrieve the fields for
296
+ * @param requiredOnly - Whether to only return the required fields
297
+ * @returns {Promise<ToolkitAuthFieldsResponse>} The fields required for creating an auth config
298
+ */
299
+ async getAuthConfigCreationFields(
300
+ toolkitSlug: string,
301
+ {
302
+ authScheme,
303
+ requiredOnly = false,
304
+ }: { authScheme?: AuthSchemeType; requiredOnly?: boolean } = {}
305
+ ): Promise<ToolkitAuthFieldsResponse> {
306
+ return this.getAuthConfigFields(
307
+ toolkitSlug,
308
+ authScheme ?? null,
309
+ 'authConfigCreation',
310
+ requiredOnly
311
+ );
312
+ }
313
+
314
+ /**
315
+ * Retrieves the fields required for initiating a connected account for a toolkit.
316
+ * @param toolkitSlug - The slug of the toolkit to retrieve the fields for
317
+ * @param authScheme - The auth scheme to retrieve the fields for
318
+ * @param requiredOnly - Whether to only return the required fields
319
+ * @returns {Promise<ToolkitAuthFieldsResponse>} The fields required for initiating a connected account
320
+ */
321
+ async getConnectedAccountInitiationFields(
322
+ toolkitSlug: string,
323
+ {
324
+ authScheme,
325
+ requiredOnly = false,
326
+ }: { authScheme?: AuthSchemeType; requiredOnly?: boolean } = {}
327
+ ): Promise<ToolkitAuthFieldsResponse> {
328
+ return this.getAuthConfigFields(
329
+ toolkitSlug,
330
+ authScheme ?? null,
331
+ 'connectedAccountInitiation',
332
+ requiredOnly
333
+ );
334
+ }
335
+
336
/**
337
* Retrieves all toolkit categories available in the Composio SDK.
338
*
packages/core/src/services/telemetry/TelemetryService.ts
new
+35
@@ -0,0 +1,35 @@
1
+import { TelemetryMetricPayloadBody, TelemetryPayload } from './TelemetryService.types';
2
+
3
+const TELEMETRY_URL = 'https://telemetry.composio.dev/v1';
4
+
5
+export class TelemetryService {
6
+ /**
7
+ * Sends a metric to the Telemetry API.
8
+ * @param payload - The payload to send to the Telemetry API.
9
+ * @returns The response from the Telemetry API.
10
+ */
11
+ static async sendMetric(payload: TelemetryMetricPayloadBody) {
12
+ return fetch(`${TELEMETRY_URL}/metrics/invocations`, {
13
+ method: 'POST',
14
+ headers: {
15
+ 'Content-Type': 'application/json',
16
+ },
17
+ body: JSON.stringify(payload),
18
+ });
19
+ }
20
+
21
+ /**
22
+ * Sends an error log to the Telemetry API.
23
+ * @param payload - The payload to send to the Telemetry API.
24
+ * @returns The response from the Telemetry API.
25
+ */
26
+ static async sendErrorLog(payload: TelemetryPayload) {
27
+ return fetch(`${TELEMETRY_URL}/errors`, {
28
+ method: 'POST',
29
+ headers: {
30
+ 'Content-Type': 'application/json',
31
+ },
32
+ body: JSON.stringify(payload),
33
+ });
34
+ }
35
+}
packages/core/src/services/telemetry/TelemetryService.types.ts
new
+64
@@ -0,0 +1,64 @@
1
+import { z } from 'zod';
2
+
3
+export const TelemetryMetricSourceSchema = z.object({
4
+ name: z.string().describe('The name of the source').optional(),
5
+ service: z
6
+ .enum(['sdk', 'apollo', 'hermes', 'thermos'])
7
+ .describe('The service of the source')
8
+ .optional(),
9
+ language: z
10
+ .enum(['python', 'typescript', 'go', 'rust'])
11
+ .describe('The language of the function that was invoked')
12
+ .optional(),
13
+ version: z.string().describe('The version of the source').optional(),
14
+ platform: z.string().describe('The platform of the source').optional(),
15
+ environment: z
16
+ .enum(['development', 'production', 'ci', 'staging', 'test'])
17
+ .describe('The environment of the source, eg: development, production, ci etc')
18
+ .optional(),
19
+});
20
+
21
+export const TelemetryMetricMetadataSchema = z.object({
22
+ projectId: z.string().describe('The project ID of the source').optional(),
23
+ provider: z.string().describe('The provider used in the source').optional(),
24
+});
25
+
26
+export const TelemetryPayloadSchema = z.object({
27
+ functionName: z.string().describe('The name of the function that was invoked'),
28
+ durationMs: z
29
+ .number()
30
+ .describe('The duration of the function invocation in milliseconds')
31
+ .optional(),
32
+ timestamp: z
33
+ .number()
34
+ .describe('The timestamp of the function invocation in epoch seconds')
35
+ .optional(),
36
+ props: z.record(z.any()).optional().describe('The properties of the function invocation'),
37
+ source: TelemetryMetricSourceSchema.optional(),
38
+ metadata: TelemetryMetricMetadataSchema.optional(),
39
+ error: z
40
+ .object({
41
+ name: z.string().describe('The name of the error'),
42
+ code: z.string().describe('The code of the error').optional(),
43
+ errorId: z
44
+ .string()
45
+ .describe(
46
+ 'The unique error ID of the error, this is used to track the error across invocations'
47
+ )
48
+ .optional(),
49
+ message: z.string().describe('The message of the error').optional(),
50
+ stack: z.string().describe('The stack trace of the error').optional(),
51
+ })
52
+ .optional()
53
+ .describe('The error that occurred during the function invocation'),
54
+});
55
+
56
+export const TelemetryMetricPayloadBodySchema = z.array(TelemetryPayloadSchema);
57
+
58
+export type TelemetryMetricSource = z.infer<typeof TelemetryMetricSourceSchema>;
59
+export type TelemetryMetricMetadata = z.infer<typeof TelemetryMetricMetadataSchema>;
60
+export type TelemetryPayload = z.infer<typeof TelemetryPayloadSchema>;
61
+export type TelemetryMetricPayloadBody = z.infer<typeof TelemetryMetricPayloadBodySchema>;
62
+
63
+export const TelemetryRequestBodySchema = z.array(TelemetryPayloadSchema);
64
+export type TelemetryRequestBody = z.infer<typeof TelemetryRequestBodySchema>;
packages/core/src/telemetry/BatchProcessor.ts
+38
-34
@@ -1,39 +1,43 @@
1
+import {
2
+ TelemetryMetricPayloadBody,
3
+ TelemetryPayload,
4
+} from '../services/telemetry/TelemetryService.types';
5
+
6
export class BatchProcessor {
2
- private batch: unknown[] = [];
3
- private time: number;
4
- private batchSize: number;
5
- private processBatchCallback: (data: unknown[]) => void;
6
- private timer: NodeJS.Timeout | null = null;
7
-
8
- constructor(
9
- time: number = 2000,
10
- batchSize: number = 100,
11
- processBatchCallback: (data: unknown[]) => void
12
- ) {
13
- this.batch = [];
14
- this.time = time;
15
- this.batchSize = batchSize;
16
- this.processBatchCallback = processBatchCallback;
7
+ private batch: TelemetryMetricPayloadBody = [];
8
+ private time: number;
9
+ private batchSize: number;
10
+ private processBatchCallback: (data: TelemetryMetricPayloadBody) => void;
11
+ private timer: NodeJS.Timeout | null = null;
12
+
13
+ constructor(
14
+ time: number = 2000,
15
+ batchSize: number = 100,
16
+ processBatchCallback: (data: TelemetryMetricPayloadBody) => void
17
+ ) {
18
+ this.batch = [];
19
+ this.time = time;
20
+ this.batchSize = batchSize;
21
+ this.processBatchCallback = processBatchCallback;
22
+ }
23
+
24
+ pushItem(item: TelemetryPayload) {
25
+ this.batch.push(item);
26
+ if (this.batch.length >= this.batchSize) {
27
+ this.processBatch();
28
+ } else if (!this.timer) {
29
+ this.timer = setTimeout(() => this.processBatch(), this.time);
30
}
18
-
19
- pushItem(item: unknown) {
20
- this.batch.push(item);
21
- if (this.batch.length >= this.batchSize) {
22
- this.processBatch();
23
- } else if (!this.timer) {
24
- this.timer = setTimeout(() => this.processBatch(), this.time);
25
- }
31
+ }
32
+
33
+ processBatch() {
34
+ if (this.batch.length > 0) {
35
+ this.processBatchCallback(this.batch);
36
+ this.batch = [];
37
}
27
-
28
- processBatch() {
29
- if (this.batch.length > 0) {
30
- this.processBatchCallback(this.batch);
31
- this.batch = [];
32
- }
33
- if (this.timer) {
34
- clearTimeout(this.timer);
35
- this.timer = null;
36
- }
38
+ if (this.timer) {
39
+ clearTimeout(this.timer);
40
+ this.timer = null;
41
}
42
}
39
-
\ No newline at end of file
43
+}
packages/core/src/telemetry/README.md
+89
-174
@@ -1,208 +1,123 @@
1
-# Telemetry Transports
1
+# Telemetry System Overview
2
3
-This directory contains implementations of different telemetry transport mechanisms for sending telemetry data to various endpoints.
3
+This document describes how telemetry is implemented in the SDK, including the main components, their responsibilities, and the data flow.
4
5
-## Available Transports
5
+---
6
7
-- `BrowserTransport`: Uses XMLHttpRequest for browser environments
8
-- `ProcessTransport`: Uses Node.js child processes for server-side environments
9
-- `ConsoleTransport`: Logs telemetry data to console (for development/debugging)
7
+## 1. Telemetry Architecture Overview
8
11
-## Using with Composio
9
+**Purpose:**
10
+The telemetry system collects, batches, and sends usage and error data from the SDK to a remote telemetry server, with minimal impact on application performance.
11
13
-To use a custom telemetry transport with the Composio instance:
12
+**Key Components:**
13
15
-```typescript
16
-import { Composio, BaseTelemetryTransport } from '@composio/core';
17
-
18
-// Create your custom transport
19
-class CustomTelemetryTransport implements BaseTelemetryTransport {
20
- async send(payload: TelemetryTransportParams): Promise<void> {
21
- // Your custom implementation
22
- console.log('Sending telemetry:', payload);
23
- return Promise.resolve();
24
- }
25
-}
26
-
27
-// Initialize Composio with your custom transport
28
-const composio = new Composio({
29
- apiKey: 'your-api-key',
30
- baseURL: 'https://api.composio.dev',
31
- allowTracking: true, // Enable telemetry
32
- telemetryTransport: new CustomTelemetryTransport() // Pass your custom transport
33
-});
34
-```
14
+- `TelemetryTransport`: Main class for instrumentation and telemetry logic.
15
+- `BatchProcessor`: Buffers and batches telemetry events before sending.
16
+- `TelemetryService`: Handles HTTP requests to the telemetry API.
17
+- **Types**: Define the structure of telemetry payloads.
18
36
-You can also use the built-in transports:
19
+---
20
38
-```typescript
39
-import { Composio, BrowserTelemetryTransport, ProcessTelemetryTransport } from '@composio/core';
40
-
41
-// For browser environments
42
-const composio = new Composio({
43
- apiKey: 'your-api-key',
44
- telemetryTransport: new BrowserTelemetryTransport()
45
-});
46
-
47
-// For Node.js environments
48
-const composio = new Composio({
49
- apiKey: 'your-api-key',
50
- telemetryTransport: new ProcessTelemetryTransport()
51
-});
52
-```
21
+## 2. BatchProcessor
22
54
-Note: The telemetry system will automatically use the appropriate transport based on the environment if you don't specify one, but you can override this behavior by providing your own transport.
23
+**Role:** Efficiently batches telemetry events to reduce the number of API calls and avoid performance bottlenecks.
24
56
-## Creating a New Transport
25
+**How it works:**
26
58
-To create a new telemetry transport, follow these steps:
27
+- Maintains an internal array (`batch`) to store telemetry events.
28
+- Configurable batch size and time interval (defaults: 100 items or 2 seconds).
29
+- When an event is added via `pushItem`:
30
+ - If the batch size is reached, immediately processes (sends) the batch.
31
+ - If not, starts a timer (if not already running) to process the batch after the interval.
32
+- `processBatch`:
33
+ - Invokes a callback (provided at construction) with the current batch.
34
+ - Clears the batch and resets the timer.
35
60
-1. Create a new file in the `transports` directory (e.g., `YourNewTransport.ts`)
36
+---
37
62
-2. Implement the `BaseTelemetryTransport` interface:
38
+## 3. TelemetryTransport (Main Telemetry Class)
39
64
-```typescript
65
-import { TelemetryTransportParams } from "../../types/telemetry.types";
66
-import { BaseTelemetryTransport } from "../TelemetryTransport";
67
-
68
-export class YourNewTransport implements BaseTelemetryTransport {
69
- send(payload: TelemetryTransportParams): Promise<void> {
70
- return new Promise((resolve) => {
71
- try {
72
- // Your transport-specific implementation
73
- // e.g., using fetch, WebSocket, or any other transport mechanism
74
-
75
- // Always resolve the promise, even on error
76
- resolve();
77
- } catch (error) {
78
- // Handle errors silently
79
- resolve();
80
- }
81
- });
82
- }
83
-}
84
-```
40
+**Initialization:**
41
86
-### Required Interface
42
+- Configured with metadata (SDK version, environment, provider, etc.).
43
+- Sets up a `BatchProcessor` with a callback to send metrics via `TelemetryService.sendMetric`.
44
88
-Your transport must implement the following interface:
45
+**Instrumentation:**
46
90
-```typescript
91
-interface TelemetryTransportParams {
92
- url: string; // The endpoint to send data to
93
- method: string; // HTTP method (e.g., 'POST')
94
- headers: Record<string, string>; // HTTP headers
95
- data: AcceptableJSONValue; // The actual telemetry data
96
-}
97
-```
47
+- The `instrument` method wraps all async methods of a given instance (e.g., SDK classes).
48
+- For each method call:
49
+ - Creates a telemetry payload with function name, arguments, timestamp, etc.
50
+ - Pushes the payload to the batch processor.
51
+ - If the method throws an error, captures error details and sends error telemetry immediately.
52
99
-### Implementation Guidelines
53
+**Sending Telemetry:**
54
101
-1. **Error Handling**
102
- - Always resolve the promise, even when errors occur
103
- - Don't throw errors that could affect the main application flow
104
- - Log errors appropriately for debugging
55
+- **Metrics:** Batched and sent via `TelemetryService.sendMetric` (POST to `/metrics/invocations`).
56
+- **Errors:** Sent immediately via `TelemetryService.sendErrorLog` (POST to `/errors`).
57
106
-2. **Environment Awareness**
107
- - Add environment-specific checks if your transport is meant for a specific runtime
108
- - Example:
109
- ```typescript
110
- if (typeof window === 'undefined') {
111
- return Promise.reject(new Error('YourTransport can only be used in specific environment'));
112
- }
113
- ```
58
+**Environment Awareness:**
59
115
-3. **Performance**
116
- - Keep the implementation lightweight
117
- - Ensure non-blocking operation
118
- - Consider using background processes or workers for heavy operations
60
+- Telemetry is disabled in certain environments (e.g., `test`, `ci`, or if `TELEMETRY_DISABLED` is set).
61
120
-### Example: WebSocket Transport
62
+---
63
122
-Here's an example of a WebSocket-based transport:
64
+## 4. TelemetryService
65
124
-```typescript
125
-export class WebSocketTransport implements BaseTelemetryTransport {
126
- private ws: WebSocket | null = null;
127
- private queue: TelemetryTransportParams[] = [];
128
- private isConnecting = false;
129
-
130
- constructor(private url: string) {}
131
-
132
- private async connect(): Promise<void> {
133
- if (this.isConnecting) return;
134
- this.isConnecting = true;
135
-
136
- return new Promise((resolve) => {
137
- this.ws = new WebSocket(this.url);
138
-
139
- this.ws.onopen = () => {
140
- this.isConnecting = false;
141
- this.processQueue();
142
- resolve();
143
- };
144
-
145
- this.ws.onerror = () => {
146
- this.isConnecting = false;
147
- resolve();
148
- };
149
- });
150
- }
151
-
152
- private async processQueue() {
153
- while (this.queue.length > 0 && this.ws?.readyState === WebSocket.OPEN) {
154
- const payload = this.queue.shift();
155
- if (payload) {
156
- this.ws.send(JSON.stringify(payload));
157
- }
158
- }
159
- }
160
-
161
- async send(payload: TelemetryTransportParams): Promise<void> {
162
- return new Promise((resolve) => {
163
- try {
164
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
165
- this.queue.push(payload);
166
- this.connect().then(resolve);
167
- } else {
168
- this.ws.send(JSON.stringify(payload));
169
- resolve();
170
- }
171
- } catch (error) {
172
- resolve();
173
- }
174
- });
175
- }
176
-}
177
-```
66
+- **sendMetric:** Sends a batch of telemetry events to the `/metrics/invocations` endpoint.
67
+- **sendErrorLog:** Sends a single error event to the `/errors` endpoint.
68
+- **Implementation:** Uses `fetch` with JSON payloads.
69
179
-### Integration
70
+---
71
181
-To use your new transport:
72
+## 5. Telemetry Payload Structure
73
183
-```typescript
184
-import { YourNewTransport } from './transports/YourNewTransport';
74
+**Types:** Defined in `TelemetryService.types.ts` using Zod schemas and TypeScript types.
75
186
-// Create an instance
187
-const transport = new YourNewTransport();
76
+**Payload Fields:**
77
189
-// Use with telemetry system
190
-telemetrySystem.setTransport(transport);
78
+- `functionName`: Name of the function/method invoked.
79
+- `durationMs`: Duration of the invocation (optional).
80
+- `timestamp`: Epoch time of the event.
81
+- `props`: Additional properties (e.g., method arguments).
82
+- `source`: Metadata about the SDK/runtime.
83
+- `metadata`: Project/provider info.
84
+- `error`: Error details (if any).
85
+
86
+---
87
+
88
+## 6. Error Handling
89
+
90
+**Error Instrumentation:**
91
+
92
+- If an instrumented method throws, the error is captured.
93
+- Error details (name, message, stack, code) are included in the telemetry payload.
94
+- Each error is assigned a unique `errorId` if not already present.
95
+
96
+---
97
+
98
+## 7. Usage Example
99
+
100
+```typescript
101
+const telemetry = new TelemetryTransport();
102
+telemetry.setup(metadata); // metadata includes SDK version, provider, etc.
103
+telemetry.instrument(someSdkInstance); // Instruments all async methods for telemetry
104
```
105
193
-## Best Practices
106
+---
107
+
108
+## 8. Summary of Flow
109
+
110
+1. SDK initializes telemetry with environment and version info.
111
+2. SDK classes are instrumented so all async method calls are logged.
112
+3. Each method call generates a telemetry event, which is batched.
113
+4. BatchProcessor sends events in bulk (by size or time) to the telemetry server.
114
+5. Errors are captured and sent immediately.
115
+6. TelemetryService handles the actual HTTP requests.
116
195
-1. **Testing**
196
- - Write unit tests for your transport
197
- - Test error scenarios
198
- - Verify environment-specific behavior
117
+---
118
200
-2. **Documentation**
201
- - Document any specific requirements or dependencies
202
- - Include usage examples
203
- - Note any environment limitations
119
+## 9. Telemetry Service Hosting & Source
120
205
-3. **Maintenance**
206
- - Keep dependencies up to date
207
- - Monitor for deprecation warnings
208
- - Update documentation as needed
121
+- The telemetry services are hosted at: https://telemetry.composio.io
122
+- The source code for the telemetry backend is available in the [ComposioHQ/hermes](https://github.com/ComposioHQ/hermes) repository.
123
+- The relevant backend implementation can be found in the `/apps/telemetry-proxy` directory of that repository.
packages/core/src/telemetry/Telemetry.ts
+99
-99
@@ -6,22 +6,18 @@ declare global {
6
}
7
8
import { ComposioError as ComposioClientError } from '@composio/client';
9
-import {
10
- TELEMETRY_EVENTS,
11
- // TelemetryErrorPayload,
12
- TelemetryErrorPayloadParams,
13
- TelemetryMetadata,
14
- TelemetryPayload,
15
- TelemetryPayloadParams,
16
-} from '../types/telemetry.types';
17
-import { TELEMETRY_URL } from '../utils/constants';
9
+import { TELEMETRY_EVENTS, TelemetryMetadata } from '../types/telemetry.types';
10
import { getEnvVariable } from '../utils/env';
11
import { BatchProcessor } from './BatchProcessor';
20
-import { BaseTelemetryTransport } from './TelemetryTransport';
21
-import { BrowserTelemetryTransport } from './transports/BrowserTransport';
22
-import { ProcessTelemetryTransport } from './transports/ProcessTransport';
12
import { ComposioError } from '../errors/ComposioError';
13
import { getRandomUUID } from '../utils/uuid';
14
+import {
15
+ TelemetryMetricPayloadBody,
16
+ TelemetryMetricSource,
17
+ TelemetryPayload,
18
+} from '../services/telemetry/TelemetryService.types';
19
+import { TelemetryService } from '../services/telemetry/TelemetryService';
20
+import logger from '../utils/logger';
21
/**
22
* The Telemetry class is used to log the telemetry for any given instance which extends InstrumentedInstance.
23
*
@@ -39,35 +35,41 @@ import { getRandomUUID } from '../utils/uuid';
35
* telemetry.instrument(composio.triggers);
36
*
37
*/
42
-export class TelemetryService {
38
+export class TelemetryTransport {
39
private telemetryMetadata!: TelemetryMetadata;
44
- private transport!: BaseTelemetryTransport;
40
private isTelemetryDisabled: boolean = true;
46
-
47
- private batchProcessor = new BatchProcessor(100, 10, async data => {
48
- await this.sendTelemetry(data as TelemetryPayload[]);
41
+ private telemetrySource!: TelemetryMetricSource;
42
+ private readonly telemetrySourceName = 'typescript-sdk';
43
+ private readonly telemetryServiceName = 'sdk';
44
+ private readonly telemetryLanguage = 'typescript';
45
+
46
+ private batchProcessor = new BatchProcessor(200, 10, async (data: TelemetryMetricPayloadBody) => {
47
+ logger.debug('Sending batch of telemetry metrics', data);
48
+ await TelemetryService.sendMetric(data as TelemetryPayload[]);
49
});
50
51
- setup(metadata: TelemetryMetadata, transport?: BaseTelemetryTransport) {
51
+ setup(metadata: TelemetryMetadata) {
52
this.telemetryMetadata = metadata;
53
this.isTelemetryDisabled = false;
54
-
55
- const isBrowser = typeof window !== 'undefined';
56
- if (transport) {
57
- this.transport = transport;
58
- } else if (isBrowser) {
59
- this.transport = new BrowserTelemetryTransport();
60
- this.telemetryMetadata.transport = 'browser';
61
- } else {
62
- this.transport = new ProcessTelemetryTransport();
63
- this.telemetryMetadata.transport = 'process';
64
- }
65
-
54
+ this.telemetrySource = {
55
+ name: this.telemetrySourceName,
56
+ service: this.telemetryServiceName,
57
+ language: this.telemetryLanguage,
58
+ version: this.telemetryMetadata?.version,
59
+ platform: this.telemetryMetadata?.isBrowser ? 'browser' : 'node',
60
+ };
61
// send telemetry event for SDK initialization
67
- this.sendTelemetry([
62
+ this.sendMetric([
63
{
69
- eventName: TELEMETRY_EVENTS.SDK_INITIALIZED,
70
- data: {},
64
+ functionName: TELEMETRY_EVENTS.SDK_INITIALIZED,
65
+ durationMs: 0,
66
+ timestamp: Date.now() / 1000,
67
+ props: {},
68
+ source: this.telemetrySource,
69
+ metadata: {
70
+ provider: this.telemetryMetadata?.provider ?? 'openai',
71
+ },
72
+ error: undefined,
73
},
74
]);
75
}
@@ -101,13 +103,20 @@ export class TelemetryService {
103
) => Promise<unknown>;
104
105
(instance as unknown as Record<string, Function>)[name] = async (...args: unknown[]) => {
104
- const telemetryPayload: TelemetryPayloadParams = {
105
- eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
106
- data: {
106
+ const telemetryPayload: TelemetryPayload = {
107
+ functionName: `${instrumentedClassName}.${name}`,
108
+ durationMs: 0,
109
+ timestamp: Date.now() / 1000,
110
+ props: {
111
fileName: instrumentedClassName,
112
method: name,
113
params: args,
114
},
115
+ metadata: {
116
+ provider: this.telemetryMetadata?.provider ?? 'openai',
117
+ },
118
+ error: undefined,
119
+ source: this.telemetrySource,
120
};
121
122
this.batchProcessor.pushItem(telemetryPayload);
@@ -118,7 +127,7 @@ export class TelemetryService {
127
if (error instanceof Error) {
128
if (!error.errorId) {
129
error.errorId = getRandomUUID();
121
- this.prepareAndSendErrorTelemetry(error, instrumentedClassName, name, args);
130
+ await this.prepareAndSendErrorTelemetry(error, instrumentedClassName, name, args);
131
}
132
}
133
throw error;
@@ -134,14 +143,12 @@ export class TelemetryService {
143
* @returns true if the telemetry should be sent, false otherwise
144
*/
145
private shouldSendTelemetry() {
137
- const devEnvironments = ['test', 'development', 'CI'];
146
+ const telemetryDisabledEnvironments = ['test', 'ci'];
147
const nodeEnv = (getEnvVariable('NODE_ENV', 'development') || '').toLowerCase();
139
- const isDevEnvironment = devEnvironments.includes(nodeEnv);
148
+ const isDisabledEnvironment = telemetryDisabledEnvironments.includes(nodeEnv);
149
const isTelemetryDisabledByEnv = getEnvVariable('TELEMETRY_DISABLED', 'false') === 'true';
150
142
- return (
143
- this.transport && !this.isTelemetryDisabled && !isTelemetryDisabledByEnv && !isDevEnvironment
144
- );
151
+ return !this.isTelemetryDisabled && !isTelemetryDisabledByEnv && !isDisabledEnvironment;
152
}
153
154
/**
@@ -153,45 +160,52 @@ export class TelemetryService {
160
* @param {string} instrumentedClassName - The class name of the instrumented class.
161
* @param {string} name - The name of the method that threw the error.
162
*/
156
- private prepareAndSendErrorTelemetry(
163
+ private async prepareAndSendErrorTelemetry(
164
error: unknown,
165
instrumentedClassName: string,
166
name: string,
167
args: unknown[]
168
) {
169
+ const telemetryPayload: TelemetryPayload = {
170
+ functionName: `${instrumentedClassName}.${name}`,
171
+ durationMs: 0,
172
+ timestamp: Date.now() / 1000,
173
+ props: {
174
+ fileName: instrumentedClassName,
175
+ method: name,
176
+ params: args,
177
+ },
178
+ metadata: {
179
+ provider: this.telemetryMetadata?.provider ?? 'openai',
180
+ },
181
+ source: this.telemetrySource,
182
+ };
183
// client error, this is likely handled by the API itseld
184
if (error instanceof ComposioClientError) {
164
- const telemetryPayload: TelemetryErrorPayloadParams = {
165
- error_id: error.errorId || '',
166
- error_message: error.message,
167
- original_error: error.cause || error,
168
- current_stack: error.stack ? error.stack.split('\n') : [],
169
- description: `Original Call : ${this.telemetryMetadata?.source}:${instrumentedClassName}.${name}(${JSON.stringify(args)})`,
185
+ telemetryPayload.error = {
186
+ errorId: error.errorId,
187
+ name: error.name,
188
+ message: error.message,
189
+ stack: error.stack,
190
};
171
- this.sendErrorTelemetry(telemetryPayload);
191
} else if (error instanceof ComposioError) {
173
- // Composio SDK Errors
174
- const telemetryPayload: TelemetryErrorPayloadParams = {
175
- error_id: error.errorId || '',
176
- error_message: error.message,
177
- original_error: error.cause || error,
178
- current_stack: error.stack ? error.stack.split('\n') : [],
179
- error_code: error.code,
180
- possible_fix: error.possibleFixes?.join('\n'),
181
- description: `Original Call : ${instrumentedClassName}.${name}(${JSON.stringify(args)})`,
192
+ telemetryPayload.error = {
193
+ errorId: error.errorId,
194
+ name: error.name,
195
+ code: error.code,
196
+ message: error.message,
197
+ stack: error.stack,
198
};
183
- this.sendErrorTelemetry(telemetryPayload);
199
} else if (error instanceof Error) {
185
- // Unhandled errors
186
- const telemetryPayload: TelemetryErrorPayloadParams = {
187
- error_id: error.errorId || '',
188
- error_message: error instanceof Error ? error.name : 'Unknown error',
189
- original_error: error,
190
- current_stack: error.stack ? error.stack.split('\n') : [],
191
- description: `Original Call : ${this.telemetryMetadata?.source}:${instrumentedClassName}.${name}(${JSON.stringify(args)})`,
200
+ telemetryPayload.error = {
201
+ errorId: error.errorId,
202
+ name: error.name ?? 'Unknown error',
203
+ message: error.message,
204
+ stack: error.stack,
205
};
193
- this.sendErrorTelemetry(telemetryPayload);
206
}
207
+
208
+ await this.sendErrorTelemetry(telemetryPayload);
209
}
210
211
/**
@@ -199,45 +213,31 @@ export class TelemetryService {
213
* @param payload - the telemetry payload to send
214
* @returns
215
*/
202
- async sendTelemetry(payload: TelemetryPayloadParams[]) {
216
+ async sendMetric(payload: TelemetryMetricPayloadBody) {
217
if (!this.shouldSendTelemetry()) {
218
+ logger.debug('Telemetry is disabled, skipping metric telemetry', payload);
219
return;
220
}
206
-
207
- const url = `${TELEMETRY_URL}/api/sdk_metrics/telemetry`;
208
-
209
- const reqPayload = {
210
- data: payload.map(p => ({
211
- ...p,
212
- sdk_meta: this.telemetryMetadata,
213
- })),
214
- url,
215
- method: 'POST',
216
- headers: { 'Content-Type': 'application/json' },
217
- };
218
-
219
- this.transport.send(reqPayload);
221
+ try {
222
+ logger.debug('SDK Metric', payload);
223
+ await TelemetryService.sendMetric(payload);
224
+ } catch (error) {
225
+ logger.error('Error sending metric telemetry', error);
226
+ }
227
}
228
// @TODO: check if this will send the error telemetry to the server
222
- async sendErrorTelemetry(payload: TelemetryErrorPayloadParams) {
229
+ async sendErrorTelemetry(payload: TelemetryPayload) {
230
if (!this.shouldSendTelemetry()) {
231
+ logger.debug('Telemetry is disabled, skipping metric telemetry', payload);
232
return;
233
}
226
-
227
- const url = `${TELEMETRY_URL}/api/sdk_metrics/error`;
228
-
229
- const reqPayload = {
230
- data: {
231
- ...payload,
232
- sdk_meta: this.telemetryMetadata,
233
- },
234
- url,
235
- method: 'POST',
236
- headers: { 'Content-Type': 'application/json' },
237
- };
238
-
239
- this.transport.send(reqPayload);
234
+ try {
235
+ logger.debug('SDK Error Telemetry', payload);
236
+ await TelemetryService.sendErrorLog(payload);
237
+ } catch (error) {
238
+ logger.error('Error sending error telemetry', error);
239
+ }
240
}
241
}
242
243
-export const telemetry = new TelemetryService();
243
+export const telemetry = new TelemetryTransport();
packages/core/src/telemetry/TelemetryTransport.ts
deleted
-22
@@ -1,22 +0,0 @@
1
-import chalk from 'chalk';
2
-import { TelemetryTransportParams } from '../types/telemetry.types';
3
-import logger from '../utils/logger';
4
-
5
-export abstract class BaseTelemetryTransport {
6
- /**
7
- * Send the payload to the telemetry service.
8
- * @param payload - The payload to send.
9
- */
10
- abstract send(payload: TelemetryTransportParams): Promise<void>;
11
-}
12
-
13
-/**
14
- * A telemetry transport that logs to the console.
15
- * This is just for testing purposes.
16
- */
17
-export class ConsoleTelemetryTransport implements BaseTelemetryTransport {
18
- send(payload: TelemetryTransportParams): Promise<void> {
19
- logger.debug(chalk.yellow('telemetry'), JSON.stringify(payload, null, 2));
20
- return Promise.resolve();
21
- }
22
-}
packages/core/src/telemetry/transports/BrowserTransport.ts
deleted
-43
@@ -1,43 +0,0 @@
1
-import { TelemetryTransportParams } from '../../types/telemetry.types';
2
-import logger from '../../utils/logger';
3
-import { BaseTelemetryTransport } from '../TelemetryTransport';
4
-export class BrowserTelemetryTransport implements BaseTelemetryTransport {
5
- send(payload: TelemetryTransportParams): Promise<void> {
6
- if (typeof window === 'undefined') {
7
- return Promise.reject(
8
- new Error('BrowserTelemetryTransport can only be used in browser environments')
9
- );
10
- }
11
-
12
- return new Promise(resolve => {
13
- try {
14
- // Create a new XMLHttpRequest object
15
- const xhr = new XMLHttpRequest();
16
- // Open a new POST request to the telemetry server
17
- xhr.open(payload.method, payload.url, true);
18
- // Set the request header to indicate JSON content
19
- xhr.setRequestHeader('Content-Type', 'application/json');
20
- Object.entries(payload.headers || {}).forEach(([key, value]) => {
21
- xhr.setRequestHeader(key, value);
22
- });
23
-
24
- // Define the onload event handler
25
- xhr.onload = function () {
26
- // Log the response if the request was successful
27
- // if (xhr.status === 200) {
28
- // logger.debug(xhr.response);
29
- // }
30
- resolve();
31
- };
32
-
33
- // Send the reporting payload as a JSON string
34
- xhr.send(JSON.stringify(payload.data));
35
- } catch (error) {
36
- logger.error('Error sending error to telemetry', error);
37
- // logger.debug("Error sending error to telemetry", error);
38
- // DO NOTHING
39
- resolve();
40
- }
41
- });
42
- }
43
-}
packages/core/src/telemetry/transports/ProcessTransport.ts
deleted
-69
@@ -1,69 +0,0 @@
1
-import chalk from 'chalk';
2
-import { TelemetryTransportParams } from '../../types/telemetry.types';
3
-import logger from '../../utils/logger';
4
-import { BaseTelemetryTransport } from '../TelemetryTransport';
5
-export class ProcessTelemetryTransport implements BaseTelemetryTransport {
6
- send(payload: TelemetryTransportParams): Promise<void> {
7
- if (typeof window !== 'undefined') {
8
- return Promise.reject(
9
- new Error('ProcessTelemetryTransport can only be used in Node.js environments')
10
- );
11
- }
12
-
13
- return new Promise(resolve => {
14
- try {
15
- // use fetch to send the telemetry
16
-
17
- const url = new URL(payload.url);
18
- const protocol = url.protocol === 'https:' ? 'https' : 'http';
19
- const port = url.port || (url.protocol === 'https:' ? 443 : 80);
20
-
21
- const args = [
22
- '-e',
23
- `
24
- const http = require('${protocol}');
25
- const options = {
26
- hostname: '${url.hostname}',
27
- path: '${url.pathname}${url.search}',
28
- port: ${port},
29
- method: '${payload.method}',
30
- headers: ${JSON.stringify(payload.headers)}
31
- };
32
-
33
- const req = http.request(options, (res) => {
34
- res.on('data', () => {});
35
- res.on('end', () => {
36
- process.exit(0);
37
- });
38
- });
39
-
40
- req.on('error', () => {
41
- process.exit(0);
42
- });
43
-
44
- req.write(JSON.stringify(${JSON.stringify(payload.data)}));
45
- req.end();
46
- `,
47
- ];
48
-
49
- import('child_process')
50
- .then(({ spawn }) => {
51
- spawn('node', args, {
52
- stdio: 'ignore',
53
- detached: false,
54
- shell: false,
55
- }).unref();
56
- resolve();
57
- })
58
- .catch(error => {
59
- logger.error('Error sending telemetry', error);
60
- resolve();
61
- });
62
- logger.debug(chalk.yellow('Process Telemetry'), JSON.stringify(payload, null, 2));
63
- } catch (error) {
64
- logger.error('Error sending telemetry', error);
65
- resolve();
66
- }
67
- });
68
- }
69
-}
packages/core/src/types/telemetry.types.ts
+1
@@ -17,6 +17,7 @@ export type TelemetryMetadata = {
17
frameworkRuntime: string;
18
isAgentic: boolean;
19
source: string;
20
+ provider?: string;
21
transport?: string;
22
sdkType?: string;
23
sessionId?: string;
packages/core/src/types/tool.types.ts
+6
@@ -29,6 +29,9 @@ const JSONSchemaProperty: z.ZodType<unknown> = z.object({
29
type: JSONSchemaType.optional(),
30
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(),
35
title: z.string().optional(),
36
default: z.any().optional(),
37
properties: z.lazy(() => z.record(z.string(), JSONSchemaProperty)).optional(),
@@ -40,6 +43,9 @@ const JSONSchemaProperty: z.ZodType<unknown> = z.object({
43
const ParametersSchema = z.object({
44
type: z.literal('object'),
45
anyOf: z.array(JSONSchemaProperty).optional(),
46
+ oneOf: z.array(JSONSchemaProperty).optional(),
47
+ allOf: z.array(JSONSchemaProperty).optional(),
48
+ not: JSONSchemaProperty.optional(),
49
properties: z.record(z.string(), JSONSchemaProperty),
50
required: z.array(z.string()).optional(),
51
title: z.string().optional(),
packages/core/src/types/toolkit.types.ts
+12
@@ -1,4 +1,5 @@
1
import { z } from 'zod';
2
+import { AuthSchemeEnum } from './authConfigs.types';
3
4
/**
5
* Toolkit list params
@@ -112,3 +113,14 @@ export type ToolkitCategory = z.infer<typeof ToolkitCategorySchema>;
113
export type ToolkitRetrieveCategoriesResponse = z.infer<
114
typeof ToolkitRetrieveCategoriesResponseSchema
115
>;
116
+
117
+export const ToolkitAuthFieldsResponseSchema = z.object({
118
+ authScheme: AuthSchemeEnum,
119
+ fields: z.array(
120
+ ToolkitAuthFieldSchema.extend({
121
+ required: z.boolean().optional(),
122
+ })
123
+ ),
124
+});
125
+
126
+export type ToolkitAuthFieldsResponse = z.infer<typeof ToolkitAuthFieldsResponseSchema>;
packages/core/src/utils/jsonSchema.ts
+2
-1
@@ -82,7 +82,8 @@ export function jsonSchemaToZodSchema(
82
);
83
}
84
// Convert the JSON schema properties to Zod schema
85
- return jsonSchemaToZod(schema) as z.ZodType;
85
+ const zodSchema = jsonSchemaToZod(schema) as z.ZodTypeAny;
86
+ return zodSchema;
87
} catch (error) {
88
throw new JsonSchemaToZodError('Failed to convert JSON Schema to Zod Schema', {
89
cause: error,
packages/core/test/models/toolkits.test.ts
+206
-4
@@ -1,11 +1,9 @@
1
import { describe, it, expect, vi, beforeEach } from 'vitest';
2
-import { Toolkits } from '../../src/models/toolkits';
2
+import { Toolkits } from '../../src/models/Toolkits';
3
import ComposioClient from '@composio/client';
4
-import { ValidationError } from '../../src/errors/ValidationErrors';
5
-import { ComposioToolkitFetchError, ComposioToolkitNotFoundError } from '../../src/errors';
4
import { telemetry } from '../../src/telemetry/Telemetry';
7
-import { ConnectionRequest } from '../../src/models/ConnectionRequest';
5
import { ComposioAuthConfigNotFoundError } from '../../src/errors/AuthConfigErrors';
6
+import { AuthSchemeTypes } from '../../src/types/authConfigs.types';
7
8
// Mock dependencies
9
vi.mock('../../src/telemetry/Telemetry', () => ({
@@ -446,4 +444,208 @@ describe('Toolkits', () => {
444
expect(mockClient.connectedAccounts.initiate).not.toHaveBeenCalled();
445
});
446
});
447
+
448
+ describe('getAuthConfigCreationFields', () => {
449
+ const toolkitSlug = 'test-toolkit';
450
+ const mockToolkit = {
451
+ authConfigDetails: [
452
+ {
453
+ name: 'oauth2',
454
+ mode: 'OAUTH2',
455
+ fields: {
456
+ authConfigCreation: {
457
+ required: [{ name: 'client_id' }, { name: 'client_secret' }],
458
+ optional: [{ name: 'redirect_uri' }],
459
+ },
460
+ connectedAccountInitiation: {
461
+ required: [{ name: 'code' }],
462
+ optional: [{ name: 'state' }],
463
+ },
464
+ },
465
+ },
466
+ ],
467
+ };
468
+
469
+ beforeEach(() => {
470
+ vi.spyOn(Toolkits.prototype as any, 'getToolkitBySlug').mockResolvedValue(mockToolkit as any);
471
+ });
472
+
473
+ it('returns all fields when requiredOnly is false', async () => {
474
+ const result = await toolkits.getAuthConfigCreationFields(toolkitSlug, {
475
+ requiredOnly: false,
476
+ });
477
+ expect(result).toEqual({
478
+ authScheme: 'OAUTH2',
479
+ fields: [
480
+ { name: 'client_id', required: true },
481
+ { name: 'client_secret', required: true },
482
+ { name: 'redirect_uri', required: false },
483
+ ],
484
+ });
485
+ });
486
+
487
+ it('returns only required fields when requiredOnly is true', async () => {
488
+ const result = await toolkits.getAuthConfigCreationFields(toolkitSlug, {
489
+ requiredOnly: true,
490
+ });
491
+ expect(result).toEqual({
492
+ authScheme: 'OAUTH2',
493
+ fields: [
494
+ { name: 'client_id', required: true },
495
+ { name: 'client_secret', required: true },
496
+ ],
497
+ });
498
+ });
499
+
500
+ it('selects the correct auth config by authScheme', async () => {
501
+ const multiToolkit = {
502
+ authConfigDetails: [
503
+ {
504
+ name: 'oauth2',
505
+ mode: 'OAUTH2',
506
+ fields: {
507
+ authConfigCreation: {
508
+ required: [{ name: 'client_id' }],
509
+ optional: [],
510
+ },
511
+ connectedAccountInitiation: {
512
+ required: [],
513
+ optional: [],
514
+ },
515
+ },
516
+ },
517
+ {
518
+ name: 'api_key',
519
+ mode: 'API_KEY',
520
+ fields: {
521
+ authConfigCreation: {
522
+ required: [{ name: 'api_key' }],
523
+ optional: [],
524
+ },
525
+ connectedAccountInitiation: {
526
+ required: [],
527
+ optional: [],
528
+ },
529
+ },
530
+ },
531
+ ],
532
+ };
533
+ (Toolkits.prototype as any).getToolkitBySlug = vi.fn().mockResolvedValueOnce(multiToolkit);
534
+ const result = await toolkits.getAuthConfigCreationFields(toolkitSlug, {
535
+ authScheme: AuthSchemeTypes.API_KEY,
536
+ requiredOnly: true,
537
+ });
538
+ expect(result).toEqual({
539
+ authScheme: 'API_KEY',
540
+ fields: [{ name: 'api_key', required: true }],
541
+ });
542
+ });
543
+
544
+ it('throws if no authConfigDetails', async () => {
545
+ (Toolkits.prototype as any).getToolkitBySlug = vi.fn().mockResolvedValueOnce({});
546
+ await expect(
547
+ toolkits.getAuthConfigCreationFields(toolkitSlug, { requiredOnly: true })
548
+ ).rejects.toThrow(ComposioAuthConfigNotFoundError);
549
+ });
550
+ });
551
+
552
+ describe('getConnectedAccountInitiationFields', () => {
553
+ const toolkitSlug = 'test-toolkit';
554
+ const mockToolkit = {
555
+ authConfigDetails: [
556
+ {
557
+ name: 'oauth2',
558
+ mode: 'OAUTH2',
559
+ fields: {
560
+ authConfigCreation: {
561
+ required: [],
562
+ optional: [],
563
+ },
564
+ connectedAccountInitiation: {
565
+ required: [{ name: 'code' }],
566
+ optional: [{ name: 'state' }],
567
+ },
568
+ },
569
+ },
570
+ ],
571
+ };
572
+
573
+ beforeEach(() => {
574
+ vi.spyOn(Toolkits.prototype as any, 'getToolkitBySlug').mockResolvedValue(mockToolkit as any);
575
+ });
576
+
577
+ it('returns all fields when requiredOnly is false', async () => {
578
+ const result = await toolkits.getConnectedAccountInitiationFields(toolkitSlug, {
579
+ requiredOnly: false,
580
+ });
581
+ expect(result).toEqual({
582
+ authScheme: 'OAUTH2',
583
+ fields: [
584
+ { name: 'code', required: true },
585
+ { name: 'state', required: false },
586
+ ],
587
+ });
588
+ });
589
+
590
+ it('returns only required fields when requiredOnly is true', async () => {
591
+ const result = await toolkits.getConnectedAccountInitiationFields(toolkitSlug, {
592
+ requiredOnly: true,
593
+ });
594
+ expect(result).toEqual({
595
+ authScheme: 'OAUTH2',
596
+ fields: [{ name: 'code', required: true }],
597
+ });
598
+ });
599
+
600
+ it('selects the correct auth config by authScheme', async () => {
601
+ const multiToolkit = {
602
+ authConfigDetails: [
603
+ {
604
+ name: 'oauth2',
605
+ mode: 'OAUTH2',
606
+ fields: {
607
+ authConfigCreation: {
608
+ required: [],
609
+ optional: [],
610
+ },
611
+ connectedAccountInitiation: {
612
+ required: [{ name: 'code' }],
613
+ optional: [],
614
+ },
615
+ },
616
+ },
617
+ {
618
+ name: 'api_key',
619
+ mode: 'API_KEY',
620
+ fields: {
621
+ authConfigCreation: {
622
+ required: [],
623
+ optional: [],
624
+ },
625
+ connectedAccountInitiation: {
626
+ required: [{ name: 'api_key_code' }],
627
+ optional: [],
628
+ },
629
+ },
630
+ },
631
+ ],
632
+ };
633
+ (Toolkits.prototype as any).getToolkitBySlug = vi.fn().mockResolvedValueOnce(multiToolkit);
634
+ const result = await toolkits.getConnectedAccountInitiationFields(toolkitSlug, {
635
+ authScheme: AuthSchemeTypes.API_KEY,
636
+ requiredOnly: true,
637
+ });
638
+ expect(result).toEqual({
639
+ authScheme: 'API_KEY',
640
+ fields: [{ name: 'api_key_code', required: true }],
641
+ });
642
+ });
643
+
644
+ it('throws if no authConfigDetails', async () => {
645
+ (Toolkits.prototype as any).getToolkitBySlug = vi.fn().mockResolvedValueOnce({});
646
+ await expect(
647
+ toolkits.getConnectedAccountInitiationFields(toolkitSlug, { requiredOnly: true })
648
+ ).rejects.toThrow(ComposioAuthConfigNotFoundError);
649
+ });
650
+ });
651
});
packages/core/test/telemetry/BatchProcessor.test.ts
deleted
-119
@@ -1,119 +0,0 @@
1
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
-import { BatchProcessor } from '../../src/telemetry/BatchProcessor';
3
-
4
-describe('BatchProcessor', () => {
5
- // Mock timer functions
6
- vi.useFakeTimers();
7
-
8
- let batchProcessor: BatchProcessor;
9
- let processBatchCallback: ReturnType<typeof vi.fn>;
10
-
11
- beforeEach(() => {
12
- processBatchCallback = vi.fn().mockResolvedValue(undefined);
13
- batchProcessor = new BatchProcessor(1000, 3, processBatchCallback);
14
- });
15
-
16
- afterEach(() => {
17
- vi.clearAllTimers();
18
- vi.clearAllMocks();
19
- });
20
-
21
- it('should create an instance with default parameters', () => {
22
- const defaultProcessor = new BatchProcessor(undefined, undefined, processBatchCallback);
23
- expect(defaultProcessor).toBeInstanceOf(BatchProcessor);
24
- });
25
-
26
- it('should batch items and not process until batch size is reached', () => {
27
- batchProcessor.pushItem('item1');
28
- batchProcessor.pushItem('item2');
29
-
30
- expect(processBatchCallback).not.toHaveBeenCalled();
31
- });
32
-
33
- it('should process batch when the batch size is reached', () => {
34
- batchProcessor.pushItem('item1');
35
- batchProcessor.pushItem('item2');
36
- batchProcessor.pushItem('item3');
37
-
38
- expect(processBatchCallback).toHaveBeenCalledWith(['item1', 'item2', 'item3']);
39
- expect(processBatchCallback).toHaveBeenCalledTimes(1);
40
- });
41
-
42
- it('should process batch after the specified time', () => {
43
- batchProcessor.pushItem('item1');
44
- batchProcessor.pushItem('item2');
45
-
46
- expect(processBatchCallback).not.toHaveBeenCalled();
47
-
48
- // Fast-forward time by 1 second
49
- vi.advanceTimersByTime(1000);
50
-
51
- expect(processBatchCallback).toHaveBeenCalledWith(['item1', 'item2']);
52
- expect(processBatchCallback).toHaveBeenCalledTimes(1);
53
- });
54
-
55
- it('should reset the timer after processing batch due to size limit', () => {
56
- batchProcessor.pushItem('item1');
57
- batchProcessor.pushItem('item2');
58
- batchProcessor.pushItem('item3');
59
-
60
- expect(processBatchCallback).toHaveBeenCalledTimes(1);
61
- processBatchCallback.mockClear();
62
-
63
- // Add a new item, which should start a new timer
64
- batchProcessor.pushItem('item4');
65
-
66
- // Fast-forward time by 1 second
67
- vi.advanceTimersByTime(1000);
68
-
69
- expect(processBatchCallback).toHaveBeenCalledWith(['item4']);
70
- expect(processBatchCallback).toHaveBeenCalledTimes(1);
71
- });
72
-
73
- it('should not process an empty batch', () => {
74
- // No items added
75
- batchProcessor.processBatch();
76
-
77
- expect(processBatchCallback).not.toHaveBeenCalled();
78
- });
79
-
80
- it('should clear timer after manual processBatch call', () => {
81
- // Spy on setTimeout
82
- const setTimeoutSpy = vi.spyOn(global, 'setTimeout');
83
-
84
- batchProcessor.pushItem('item1');
85
-
86
- // A timer should be set
87
- expect(setTimeoutSpy).toHaveBeenCalled();
88
-
89
- // Clear the spy call history
90
- setTimeoutSpy.mockClear();
91
-
92
- // Process the batch manually
93
- batchProcessor.processBatch();
94
-
95
- // Add a new item, which should start a new timer
96
- batchProcessor.pushItem('item2');
97
-
98
- // setTimeout should be called again
99
- expect(setTimeoutSpy).toHaveBeenCalled();
100
- });
101
-
102
- it('should handle batches efficiently', () => {
103
- // Create a batch processor with a moderate batch size
104
- const processor = new BatchProcessor(1000, 20, processBatchCallback);
105
-
106
- // Add 19 items
107
- for (let i = 0; i < 19; i++) {
108
- processor.pushItem(`item${i}`);
109
- }
110
-
111
- expect(processBatchCallback).not.toHaveBeenCalled();
112
-
113
- // Add the 20th item to trigger batch processing
114
- processor.pushItem('item-last');
115
-
116
- expect(processBatchCallback).toHaveBeenCalledTimes(1);
117
- expect(processBatchCallback.mock.calls[0][0].length).toBe(20);
118
- });
119
-});
packages/core/test/telemetry/BrowserTransport.test.ts
deleted
-117
@@ -1,117 +0,0 @@
1
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
-import { BrowserTelemetryTransport } from '../../src/telemetry/transports/BrowserTransport';
3
-import { TelemetryTransportParams } from '../../src/types/telemetry.types';
4
-
5
-describe('BrowserTelemetryTransport', () => {
6
- let transport: BrowserTelemetryTransport;
7
-
8
- // Define the mock XHR class
9
- const mockXHR = {
10
- open: vi.fn(),
11
- send: vi.fn(),
12
- setRequestHeader: vi.fn(),
13
- onload: null as Function | null,
14
- };
15
-
16
- // Save original globals
17
- const originalWindow = global.window;
18
- const originalXMLHttpRequest = global.XMLHttpRequest;
19
-
20
- beforeEach(() => {
21
- // Setup mock window and XMLHttpRequest
22
- global.window = global.window || ({} as any);
23
- global.XMLHttpRequest = vi.fn(() => mockXHR) as any;
24
-
25
- // Reset mock functions and state
26
- mockXHR.open.mockReset();
27
- mockXHR.send.mockReset();
28
- mockXHR.setRequestHeader.mockReset();
29
- mockXHR.onload = null;
30
-
31
- // Create new transport instance
32
- transport = new BrowserTelemetryTransport();
33
- });
34
-
35
- afterEach(() => {
36
- // Restore globals
37
- global.window = originalWindow;
38
- global.XMLHttpRequest = originalXMLHttpRequest;
39
- });
40
-
41
- it('should create an instance successfully', () => {
42
- expect(transport).toBeInstanceOf(BrowserTelemetryTransport);
43
- });
44
-
45
- it('should send telemetry data via XMLHttpRequest', async () => {
46
- const payload: TelemetryTransportParams = {
47
- url: 'https://example.com/telemetry',
48
- method: 'POST',
49
- headers: {
50
- 'Content-Type': 'application/json',
51
- 'X-Custom-Header': 'test-value',
52
- },
53
- data: { key: 'value' },
54
- };
55
-
56
- // Start sending the data
57
- const promise = transport.send(payload);
58
-
59
- // Verify XHR was configured correctly
60
- expect(mockXHR.open).toHaveBeenCalledWith('POST', 'https://example.com/telemetry', true);
61
- expect(mockXHR.setRequestHeader).toHaveBeenCalledWith('Content-Type', 'application/json');
62
- expect(mockXHR.setRequestHeader).toHaveBeenCalledWith('X-Custom-Header', 'test-value');
63
- expect(mockXHR.send).toHaveBeenCalledWith(JSON.stringify({ key: 'value' }));
64
-
65
- // Trigger the onload callback if it was set
66
- if (mockXHR.onload) {
67
- (mockXHR.onload as Function)();
68
- }
69
-
70
- // Verify promise resolves
71
- await expect(promise).resolves.toBeUndefined();
72
- });
73
-
74
- it('should reject if not running in a browser environment', async () => {
75
- // Temporarily remove window to simulate non-browser environment
76
- const tempWindow = global.window;
77
- global.window = undefined as any;
78
-
79
- // Expect rejection when sending in non-browser env
80
- await expect(
81
- transport.send({
82
- url: 'https://example.com/telemetry',
83
- method: 'POST',
84
- headers: {},
85
- data: {},
86
- })
87
- ).rejects.toThrow('BrowserTelemetryTransport can only be used in browser environments');
88
-
89
- // Restore window for other tests
90
- global.window = tempWindow;
91
- });
92
-
93
- it('should handle errors gracefully', async () => {
94
- const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
95
-
96
- const payload: TelemetryTransportParams = {
97
- url: 'https://example.com/telemetry',
98
- method: 'POST',
99
- headers: {},
100
- data: {},
101
- };
102
-
103
- // Make the send method throw an error
104
- mockXHR.send.mockImplementation(() => {
105
- throw new Error('Network error');
106
- });
107
-
108
- // Should resolve despite the error
109
- const promise = transport.send(payload);
110
- await expect(promise).resolves.toBeUndefined();
111
-
112
- // Should log the error
113
- expect(consoleSpy).toHaveBeenCalled();
114
-
115
- consoleSpy.mockRestore();
116
- });
117
-});
packages/core/test/telemetry/ProcessTransport.test.ts
deleted
-91
@@ -1,91 +0,0 @@
1
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
-import { ProcessTelemetryTransport } from '../../src/telemetry/transports/ProcessTransport';
3
-import { TelemetryTransportParams } from '../../src/types/telemetry.types';
4
-
5
-describe('ProcessTelemetryTransport', () => {
6
- let transport: ProcessTelemetryTransport;
7
- const originalWindow = global.window;
8
-
9
- // Spy on console.error to validate error handling
10
- const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
11
-
12
- beforeEach(() => {
13
- // Reset window to simulate Node.js environment
14
- delete (global as any).window;
15
-
16
- // Reset mocks and spies
17
- vi.clearAllMocks();
18
-
19
- // Create transport instance
20
- transport = new ProcessTelemetryTransport();
21
- });
22
-
23
- afterEach(() => {
24
- // Restore window
25
- global.window = originalWindow;
26
- });
27
-
28
- it('should create an instance successfully', () => {
29
- expect(transport).toBeInstanceOf(ProcessTelemetryTransport);
30
- });
31
-
32
- it('should reject if running in a browser environment', async () => {
33
- // Set window to simulate browser environment
34
- global.window = {} as any;
35
-
36
- await expect(
37
- transport.send({
38
- url: 'https://example.com/telemetry',
39
- method: 'POST',
40
- headers: {},
41
- data: {},
42
- })
43
- ).rejects.toThrow('ProcessTelemetryTransport can only be used in Node.js environments');
44
- });
45
-
46
- // Since we're running in a test environment and can't easily mock dynamic imports,
47
- // we'll focus on testing the URL handling and error handling aspects
48
-
49
- it('should handle errors gracefully', async () => {
50
- // Force an error by making URL constructor throw
51
- const originalURL = global.URL;
52
- global.URL = vi.fn().mockImplementation(() => {
53
- throw new Error('Invalid URL');
54
- }) as any;
55
-
56
- const payload: TelemetryTransportParams = {
57
- url: 'invalid:///url',
58
- method: 'POST',
59
- headers: {},
60
- data: {},
61
- };
62
-
63
- // Test that the promise still resolves despite the error
64
- await expect(transport.send(payload)).resolves.toBeUndefined();
65
-
66
- // Verify error was logged
67
- expect(consoleErrorSpy).toHaveBeenCalled();
68
-
69
- // Restore URL
70
- global.URL = originalURL;
71
- });
72
-
73
- // For these tests, we can't easily verify the spawn call since it's dynamically imported
74
- // and would require more complex mocking. Instead, we'll focus on ensuring the method
75
- // runs without throwing errors.
76
-
77
- it('should handle telemetry requests without throwing errors', async () => {
78
- const payload: TelemetryTransportParams = {
79
- url: 'https://example.com/telemetry',
80
- method: 'POST',
81
- headers: {
82
- 'Content-Type': 'application/json',
83
- 'X-Custom-Header': 'test-value',
84
- },
85
- data: { key: 'value' },
86
- };
87
-
88
- // The test passes if no exception is thrown
89
- await expect(transport.send(payload)).resolves.toBeUndefined();
90
- });
91
-});
packages/core/test/telemetry/TelemetryService.test.ts
+128
-265
@@ -1,292 +1,155 @@
1
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
-import { TelemetryService } from '../../src/telemetry/Telemetry';
3
-import { BaseTelemetryTransport } from '../../src/telemetry/TelemetryTransport';
4
-import { BrowserTelemetryTransport } from '../../src/telemetry/transports/BrowserTransport';
5
-import { ProcessTelemetryTransport } from '../../src/telemetry/transports/ProcessTransport';
6
-import { TELEMETRY_EVENTS, TelemetryMetadata } from '../../src/types/telemetry.types';
7
-import * as envUtils from '../../src/utils/env';
8
-
9
-describe('TelemetryService', () => {
10
- let telemetryService: TelemetryService;
11
- let mockTransport: BaseTelemetryTransport;
12
- let testMetadata: TelemetryMetadata;
1
+import { describe, it, expect, vi, beforeEach, afterEach, beforeAll, afterAll } from 'vitest';
2
+import { BatchProcessor } from '../../src/telemetry/BatchProcessor';
3
+import { TelemetryTransport } from '../../src/telemetry/Telemetry';
4
+import { TelemetryService } from '../../src/services/telemetry/TelemetryService';
5
+import type {
6
+ TelemetryPayload,
7
+ TelemetryMetricPayloadBody,
8
+ TelemetryMetricMetadata,
9
+} from '../../src/services/telemetry/TelemetryService.types';
10
+import { TelemetryMetadata } from '../../src/types/telemetry.types';
11
+
12
+// Helper to create a mock telemetry payload
13
+const createPayload = (overrides: Partial<TelemetryPayload> = {}): TelemetryPayload => ({
14
+ functionName: 'TestClass.testMethod',
15
+ durationMs: 123,
16
+ timestamp: Date.now() / 1000,
17
+ props: { foo: 'bar' },
18
+ source: {
19
+ name: 'test',
20
+ service: 'sdk',
21
+ language: 'typescript',
22
+ version: '1.0.0',
23
+ platform: 'node',
24
+ },
25
+ metadata: { provider: 'test' },
26
+ ...overrides,
27
+});
28
14
- // Save original window
15
- const originalWindow = global.window;
29
+describe('BatchProcessor', () => {
30
+ let callback: ReturnType<typeof vi.fn>;
31
+ let processor: BatchProcessor;
32
33
beforeEach(() => {
18
- // Create a new instance for each test
19
- telemetryService = new TelemetryService();
20
-
21
- // Create mock transport
22
- mockTransport = {
23
- send: vi.fn().mockResolvedValue(undefined),
24
- };
25
-
26
- // Test metadata
27
- testMetadata = {
28
- apiKey: 'test-api-key',
29
- baseUrl: 'https://api.test.com',
30
- version: '1.0.0',
31
- frameworkRuntime: 'test-framework',
32
- isAgentic: false,
33
- source: 'test',
34
- sessionId: 'test-session-id',
35
- isBrowser: false,
36
- };
37
-
38
- // Reset window to simulate Node.js environment by default
39
- delete (global as any).window;
40
-
41
- // Mock environment variable
42
- vi.spyOn(envUtils, 'getEnvVariable').mockImplementation((key, defaultValue) => {
43
- if (key === 'TELEMETRY_DISABLED') return 'false';
44
- if (key === 'NODE_ENV') return 'production'; // Return 'production' instead of 'test' to allow telemetry
45
- return defaultValue || '';
46
- });
34
+ callback = vi.fn();
35
+ processor = new BatchProcessor(50, 3, callback); // small batch size and time for test
36
});
37
38
afterEach(() => {
50
- vi.clearAllMocks();
51
-
52
- // Restore window
53
- if (originalWindow !== undefined) {
54
- global.window = originalWindow;
55
- }
39
+ vi.useRealTimers();
40
});
41
58
- describe('setup', () => {
59
- it('should set up telemetry metadata', () => {
60
- telemetryService.setup(testMetadata, mockTransport);
61
-
62
- expect(mockTransport.send).toHaveBeenCalledWith(
63
- expect.objectContaining({
64
- data: expect.arrayContaining([
65
- expect.objectContaining({
66
- eventName: TELEMETRY_EVENTS.SDK_INITIALIZED,
67
- sdk_meta: testMetadata,
68
- }),
69
- ]),
70
- })
71
- );
72
- });
73
-
74
- it('should use BrowserTelemetryTransport in browser environment', () => {
75
- // Mock window to simulate browser environment
76
- global.window = {} as any;
77
-
78
- // Create a proper mock transport with a send method
79
- const mockBrowserTransport = { send: vi.fn().mockResolvedValue(undefined) };
80
-
81
- // Spy on the BrowserTelemetryTransport constructor
82
- vi.spyOn(BrowserTelemetryTransport.prototype, 'send').mockImplementation(() =>
83
- Promise.resolve()
84
- );
85
-
86
- // Setup with the mock transport
87
- telemetryService.setup(testMetadata, mockBrowserTransport);
88
-
89
- // Send a test event to verify the transport
90
- telemetryService['sendTelemetry']([
91
- {
92
- eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
93
- data: {},
94
- },
95
- ]);
96
-
97
- expect(mockBrowserTransport.send).toHaveBeenCalled();
98
- });
42
+ it('should batch items and call callback when batch size is reached', () => {
43
+ const payloads = [createPayload(), createPayload(), createPayload()];
44
+ payloads.forEach(p => processor.pushItem(p));
45
+ expect(callback).toHaveBeenCalledOnce();
46
+ expect(callback).toHaveBeenCalledWith(payloads);
47
+ });
48
100
- it('should use ProcessTelemetryTransport in Node.js environment', () => {
101
- // Create a proper mock transport with a send method
102
- const mockProcessTransport = { send: vi.fn().mockResolvedValue(undefined) };
49
+ it('should call callback after timeout if batch size not reached', async () => {
50
+ vi.useFakeTimers();
51
+ const payloads = [createPayload(), createPayload()];
52
+ payloads.forEach(p => processor.pushItem(p));
53
+ expect(callback).not.toHaveBeenCalled();
54
+ vi.advanceTimersByTime(60);
55
+ expect(callback).toHaveBeenCalledOnce();
56
+ expect(callback).toHaveBeenCalledWith(payloads);
57
+ });
58
104
- // Spy on the ProcessTelemetryTransport constructor
105
- vi.spyOn(ProcessTelemetryTransport.prototype, 'send').mockImplementation(() =>
106
- Promise.resolve()
107
- );
59
+ it('should reset timer and batch after processing', () => {
60
+ const payloads = [createPayload(), createPayload(), createPayload()];
61
+ payloads.forEach(p => processor.pushItem(p));
62
+ // After batch, timer should be null and batch empty
63
+ // @ts-expect-error: private access for test
64
+ expect(processor.timer).toBeNull();
65
+ // @ts-expect-error: private access for test
66
+ expect(processor.batch).toEqual([]);
67
+ });
68
+});
69
109
- // Setup with the mock transport
110
- telemetryService.setup(testMetadata, mockProcessTransport);
70
+describe('TelemetryTransport', () => {
71
+ let transport: TelemetryTransport;
72
+ let sendMetricSpy: any;
73
+ let sendErrorLogSpy: any;
74
+ const metadata: TelemetryMetadata = {
75
+ apiKey: 'test-key',
76
+ baseUrl: 'http://localhost',
77
+ version: '1.0.0',
78
+ frameworkRuntime: 'node',
79
+ isAgentic: false,
80
+ source: 'test-source',
81
+ provider: 'test',
82
+ };
83
112
- // Send a test event to verify the transport
113
- telemetryService['sendTelemetry']([
114
- {
115
- eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
116
- data: {},
117
- },
118
- ]);
84
+ beforeEach(() => {
85
+ sendMetricSpy = vi.spyOn(TelemetryService, 'sendMetric').mockResolvedValue({} as any);
86
+ sendErrorLogSpy = vi.spyOn(TelemetryService, 'sendErrorLog').mockResolvedValue({} as any);
87
+ transport = new TelemetryTransport();
88
+ transport.setup(metadata);
89
+ });
90
120
- expect(mockProcessTransport.send).toHaveBeenCalled();
121
- });
91
+ afterEach(() => {
92
+ vi.restoreAllMocks();
93
+ });
94
123
- it('should use custom transport when provided', () => {
124
- telemetryService.setup(testMetadata, mockTransport);
95
+ it('should send SDK_INITIALIZED metric on setup', () => {
96
+ expect(sendMetricSpy).toHaveBeenCalled();
97
+ const call = sendMetricSpy.mock.calls[0][0][0];
98
+ expect(call.functionName).toBeDefined();
99
+ expect(call.metadata?.provider).toBe('test');
100
+ });
101
126
- // Send a test event to verify the transport
127
- telemetryService['sendTelemetry']([
128
- {
129
- eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
130
- data: {},
131
- },
132
- ]);
102
+ it('should batch metrics and send via TelemetryService', async () => {
103
+ const payload = createPayload();
104
+ await transport.sendMetric([payload]);
105
+ expect(sendMetricSpy).toHaveBeenCalledWith([payload]);
106
+ });
107
134
- expect(mockTransport.send).toHaveBeenCalledTimes(2); // Once during setup and once for the test
135
- });
108
+ it('should send error telemetry immediately', async () => {
109
+ const payload = createPayload({ error: { name: 'Error', message: 'fail', stack: 'stack' } });
110
+ await transport.sendErrorTelemetry(payload);
111
+ expect(sendErrorLogSpy).toHaveBeenCalledWith(payload);
112
});
113
138
- describe('instrument', () => {
114
+ it('should instrument async methods and batch telemetry', async () => {
115
class TestClass {
140
- constructor() {}
141
-
142
- async testMethod(param1: string, param2: number) {
143
- return { result: `${param1}-${param2}` };
144
- }
145
-
146
- async failingMethod() {
147
- throw new Error('Test error');
116
+ async foo(a: number) {
117
+ return a * 2;
118
}
119
+ }
120
+ const instance = new TestClass();
121
+ const instrumented = transport.instrument(instance);
122
+ await instrumented.foo(21);
123
+ // The batchProcessor will push the payload, but we can check sendMetric is eventually called
124
+ await transport.sendMetric([]); // flush
125
+ expect(sendMetricSpy).toHaveBeenCalled();
126
+ });
127
150
- synchronousMethod() {
151
- return 'sync result';
128
+ it('should send error telemetry if instrumented method throws', async () => {
129
+ class TestClass {
130
+ async fail() {
131
+ throw new Error('fail!');
132
}
133
}
154
-
155
- beforeEach(() => {
156
- telemetryService.setup(testMetadata, mockTransport);
157
- vi.spyOn(telemetryService as any, 'sendErrorTelemetry');
158
- });
159
-
160
- it('should instrument async methods of an object', async () => {
161
- const testInstance = new TestClass();
162
- telemetryService.instrument(testInstance);
163
-
164
- // Reset the mock to clear the SDK_INITIALIZED call
165
- vi.clearAllMocks();
166
-
167
- await testInstance.testMethod('test', 123);
168
-
169
- // Manually process the batch
170
- (telemetryService as any).batchProcessor.processBatch();
171
-
172
- expect(mockTransport.send).toHaveBeenCalledWith(
173
- expect.objectContaining({
174
- data: expect.arrayContaining([
175
- expect.objectContaining({
176
- eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
177
- data: expect.objectContaining({
178
- fileName: 'TestClass',
179
- method: 'testMethod',
180
- params: ['test', 123],
181
- }),
182
- sdk_meta: testMetadata,
183
- }),
184
- ]),
185
- })
186
- );
187
- });
188
- // @TODO: fix this test
189
- // it('should capture errors from instrumented methods', async () => {
190
- // const testInstance = new TestClass();
191
- // telemetryService.instrument(testInstance);
192
-
193
- // // Reset the mock to clear the SDK_INITIALIZED call
194
- // vi.clearAllMocks();
195
- // // vi.spyOn(telemetryService, 'sendErrorTelemetry').mockImplementation(() => Promise.resolve());
196
-
197
- // try {
198
- // await testInstance.failingMethod();
199
- // } catch (error) {
200
- // // Wait for any pending promises to resolve
201
- // expect(telemetryService.sendErrorTelemetry).toHaveBeenCalledWith(
202
- // expect.objectContaining({
203
- // data: expect.arrayContaining([
204
- // expect.objectContaining({
205
- // eventName: TELEMETRY_EVENTS.SDK_METHOD_ERROR,
206
- // data: expect.objectContaining({
207
- // fileName: 'TestClass',
208
- // method: 'failingMethod',
209
- // error: expect.objectContaining({
210
- // message: 'Test error',
211
- // }),
212
- // }),
213
- // sdk_meta: testMetadata,
214
- // }),
215
- // ]),
216
- // })
217
- // );
218
- // }
219
- // });
220
-
221
- it('should use the filename if constructor name is not available', () => {
222
- const anonymousObject = {
223
- async testMethod() {
224
- return 'result';
225
- },
226
- };
227
-
228
- telemetryService.instrument(anonymousObject, 'custom-filename');
229
-
230
- // Verify the instrumentation works with the custom filename
231
- expect(anonymousObject.testMethod).not.toBe(undefined);
232
- expect(typeof anonymousObject.testMethod).toBe('function');
233
- });
134
+ const instance = new TestClass();
135
+ const instrumented = transport.instrument(instance);
136
+ await expect(instrumented.fail()).rejects.toThrow('fail!');
137
+ expect(sendErrorLogSpy).toHaveBeenCalled();
138
});
139
+});
140
236
- describe('sendTelemetry', () => {
237
- beforeEach(() => {
238
- telemetryService.setup(testMetadata, mockTransport);
239
- });
240
-
241
- it('should not send telemetry if transport is not set', async () => {
242
- // Create a new instance without setting up transport
243
- const newTelemetryService = new TelemetryService();
244
-
245
- // Reset the mock to clear any previous calls
246
- vi.clearAllMocks();
247
-
248
- await newTelemetryService['sendTelemetry']([
249
- {
250
- eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
251
- data: {},
252
- },
253
- ]);
254
-
255
- expect(mockTransport.send).not.toHaveBeenCalled();
256
- });
257
-
258
- it('should not send telemetry if telemetry is disabled', async () => {
259
- // Mock environment variable to disable telemetry
260
- vi.spyOn(envUtils, 'getEnvVariable').mockImplementation(() => 'true');
261
-
262
- await telemetryService['sendTelemetry']([
263
- {
264
- eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
265
- data: {},
266
- },
267
- ]);
268
-
269
- // We expect only the SDK_INITIALIZED call during setup
270
- expect(mockTransport.send).toHaveBeenCalledTimes(1);
271
- });
272
-
273
- it('should send telemetry with correct payload format', async () => {
274
- const testPayload = [
275
- {
276
- eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
277
- data: { test: 'data' },
278
- sdk_meta: testMetadata,
279
- },
280
- ];
281
-
282
- await telemetryService['sendTelemetry'](testPayload);
141
+beforeAll(() => {
142
+ // Save the original NODE_ENV
143
+ process.env._ORIGINAL_NODE_ENV = process.env.NODE_ENV;
144
+ process.env.NODE_ENV = 'development';
145
+});
146
284
- expect(mockTransport.send).toHaveBeenLastCalledWith({
285
- data: testPayload,
286
- url: expect.stringContaining('/api/sdk_metrics/telemetry'),
287
- method: 'POST',
288
- headers: { 'Content-Type': 'application/json' },
289
- });
290
- });
291
- });
147
+afterAll(() => {
148
+ // Restore the original NODE_ENV
149
+ if (process.env._ORIGINAL_NODE_ENV !== undefined) {
150
+ process.env.NODE_ENV = process.env._ORIGINAL_NODE_ENV;
151
+ delete process.env._ORIGINAL_NODE_ENV;
152
+ } else {
153
+ delete process.env.NODE_ENV;
154
+ }
155
});
packages/json-schema-to-zod/src/parsers/parse-array.ts
+2
-1
@@ -4,6 +4,7 @@ import { parseSchema } from './parse-schema';
4
import type { JsonSchemaObject, Refs, JsonSchema } from '../types';
5
import { extendSchemaWithMessage } from '../utils/extend-schema';
6
import { its } from '../utils/its';
7
+import { JSONSchema7TypeName } from 'json-schema';
8
9
type MetadataFields =
10
| keyof Pick<JsonSchemaObject, 'default' | 'description' | 'title'>
@@ -30,7 +31,7 @@ export const parseArray = (jsonSchema: JsonSchemaObject & { type: 'array' }, ref
31
32
// Create new schema with combined types
33
const newSchema: JsonSchemaObject = {
33
- type: Array.from(types),
34
+ type: Array.from(types) as JSONSchema7TypeName[],
35
...(items && { items }),
36
};
37
pnpm-lock.yaml
+25
-6
@@ -146,6 +146,25 @@ importers:
146
specifier: ^5.8.3
147
version: 5.8.3
148
149
+ examples/json-schema-to-zod:
150
+ dependencies:
151
+ '@composio/core':
152
+ specifier: workspace:*
153
+ version: link:../../packages/core
154
+ dotenv:
155
+ specifier: ^16.4.1
156
+ version: 16.5.0
157
+ zod-to-json-schema:
158
+ specifier: ^3.24.5
159
+ version: 3.24.5(zod@3.25.62)
160
+ devDependencies:
161
+ '@types/bun':
162
+ specifier: ^1.2.9
163
+ version: 1.2.16
164
+ typescript:
165
+ specifier: ^5.8.3
166
+ version: 5.8.3
167
+
168
examples/langchain:
169
dependencies:
170
'@composio/core':
@@ -408,8 +427,8 @@ importers:
427
packages/core:
428
dependencies:
429
'@composio/client':
411
- specifier: 0.1.0-alpha.17
412
- version: 0.1.0-alpha.17
430
+ specifier: 0.1.0-alpha.22
431
+ version: 0.1.0-alpha.22
432
'@composio/json-schema-to-zod':
433
specifier: 0.1.6
434
version: 0.1.6
@@ -854,8 +873,8 @@ packages:
873
'@cloudflare/workers-types@4.20250612.0':
874
resolution: {integrity: sha512-3VsbEh0nqOWWH+jsJ2W41Ty6qlN1jQ+4R3lBA3gPor0U6LB3e4OA04jg7wyCyJmikBN6KsBcPRp3kj0es/9q2w==}
875
857
- '@composio/client@0.1.0-alpha.17':
858
- resolution: {integrity: sha512-iNCDSgdwfFVsjbbyZIMknMPy4uO8Xw5+MP2aI+yoQo34VXF17Fi6ZHYirrJPf8RbdoRROZTDJjC/rU18mMzC2Q==}
876
+ '@composio/client@0.1.0-alpha.22':
877
+ resolution: {integrity: sha512-b9KCO5gy0EsCG+nXikOdm17PiZZ85rw3vwu9aNRIse9rEj2FA1SScpP+P9GN4G0lQHl+QPyDuVvGa6U9AATFeg==}
878
879
'@composio/json-schema-to-zod@0.1.6':
880
resolution: {integrity: sha512-Eso0rvvdCAxgcjejXXdyJsG4jB3ScUaxkrMaytG4B9Y6uwKJ/uxFrzWqRcwMl5wwQ7nd1vtpJUW/nzr8iRcQMg==}
@@ -5248,7 +5267,7 @@ snapshots:
5267
5268
'@cloudflare/workers-types@4.20250612.0': {}
5269
5251
- '@composio/client@0.1.0-alpha.17': {}
5270
+ '@composio/client@0.1.0-alpha.22': {}
5271
5272
'@composio/json-schema-to-zod@0.1.6':
5273
dependencies:
@@ -7028,7 +7047,7 @@ snapshots:
7047
sirv: 3.0.1
7048
tinyglobby: 0.2.14
7049
tinyrainbow: 2.0.0
7031
- 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)
7050
+ vitest: 3.2.3(@types/node@24.0.1)(@vitest/ui@3.2.3)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0)
7051
7052
'@vitest/utils@3.2.3':
7053
dependencies:
ts/docs/api/toolkits.md
+147
-37
@@ -33,12 +33,12 @@ const allToolkits = await composio.toolkits.get({});
33
34
// Get toolkits by category
35
const devToolkits = await composio.toolkits.get({
36
- category: 'developer-tools'
36
+ category: 'developer-tools',
37
});
38
39
// Get local toolkits
40
const localToolkits = await composio.toolkits.get({
41
- isLocal: true
41
+ isLocal: true,
42
});
43
```
44
@@ -79,16 +79,121 @@ console.log(connectionRequest.redirectUrl); // URL to redirect the user for auth
79
80
**Returns:** Promise<ConnectionRequest> - The connection request object
81
82
+### getAuthConfigCreationFields(toolkitSlug, options)
83
+
84
+Retrieves the fields required for creating an auth config for a toolkit.
85
+
86
+```typescript
87
+// Get all fields for creating an auth config
88
+const fields = await composio.toolkits.getAuthConfigCreationFields('github');
89
+
90
+// Get only required fields for a specific auth scheme
91
+const requiredFields = await composio.toolkits.getAuthConfigCreationFields('github', {
92
+ authScheme: 'OAUTH2',
93
+ requiredOnly: true,
94
+});
95
+```
96
+
97
+Example Response:
98
+
99
+```json
100
+{
101
+ "authScheme": "OAUTH2",
102
+ "fields": [
103
+ {
104
+ "name": "client_id",
105
+ "displayName": "Client id",
106
+ "type": "string",
107
+ "required": true
108
+ },
109
+ {
110
+ "name": "client_secret",
111
+ "displayName": "Client secret",
112
+ "type": "string",
113
+ "required": true
114
+ },
115
+ {
116
+ "name": "oauth_redirect_uri",
117
+ "displayName": "Redirect URI",
118
+ "type": "string",
119
+ "default": "https://backend.composio.dev/api/v1/auth-apps/add",
120
+ "required": false
121
+ },
122
+ {
123
+ "name": "scopes",
124
+ "displayName": "Scopes",
125
+ "type": "string",
126
+ "default": "read_products,write_products,read_orders,write_orders",
127
+ "required": false
128
+ }
129
+ ]
130
+}
131
+```
132
+
133
+**Parameters:**
134
+
135
+- `toolkitSlug` (string): The slug of the toolkit to retrieve the fields for
136
+- `options` (object, optional):
137
+ - `authScheme` (string, optional): The auth scheme to retrieve the fields for (e.g., 'OAUTH2', 'API_KEY')
138
+ - `requiredOnly` (boolean, optional): Whether to only return the required fields (default: false)
139
+
140
+**Returns:** Promise<ToolkitAuthFieldsResponse> - The authschem and fields required for creating an auth config
141
+
142
+**Throws:** ComposioAuthConfigNotFoundError if no auth config is found for the toolkit or the specified auth scheme
143
+
144
+### getConnectedAccountInitiationFields(toolkitSlug, options)
145
+
146
+Retrieves the fields required for initiating a connected account for a toolkit.
147
+
148
+```typescript
149
+// Get all fields for initiating a connected account
150
+const fields = await composio.toolkits.getConnectedAccountInitiationFields('github');
151
+
152
+// Get only required fields for a specific auth scheme
153
+const requiredFields = await composio.toolkits.getConnectedAccountInitiationFields('github', {
154
+ authScheme: 'OAUTH2',
155
+ requiredOnly: true,
156
+});
157
+```
158
+
159
+Example Response:
160
+
161
+```json
162
+{
163
+ "authScheme": "OAUTH2",
164
+ "fields": [
165
+ {
166
+ "name": "shop",
167
+ "displayName": "Store Subdomain",
168
+ "type": "string",
169
+ "default": null,
170
+ "required": true
171
+ }
172
+ ]
173
+}
174
+```
175
+
176
+**Parameters:**
177
+
178
+- `toolkitSlug` (string): The slug of the toolkit to retrieve the fields for
179
+- `options` (object, optional):
180
+ - `authScheme` (string, optional): The auth scheme to retrieve the fields for (e.g., 'OAUTH2', 'API_KEY')
181
+ - `requiredOnly` (boolean, optional): Whether to only return the required fields (default: false)
182
+
183
+**Returns:** Promise<ToolkitAuthFieldsResponse> - The auth schemes and fields required for initiating a connected account
184
+
185
+**Throws:** ComposioAuthConfigNotFoundError if no auth config is found for the toolkit or the specified auth scheme
186
+
187
## Types
188
189
### ToolkitListParams
190
191
```typescript
192
interface ToolkitListParams {
88
- category?: string; // Filter by category
89
- isLocal?: boolean; // Filter for local toolkits
90
- managedBy?: string; // Filter by manager
91
- sortBy?: string; // Sort results by this field
193
+ category?: string; // Filter by category
194
+ isLocal?: boolean; // Filter for local toolkits
195
+ managedBy?: string; // Filter by manager
196
+ sortBy?: string; // Sort results by this field
197
}
198
```
199
@@ -96,9 +201,9 @@ interface ToolkitListParams {
201
202
```typescript
203
interface ToolKitListResponse {
99
- items: ToolKitItem[]; // List of toolkits
204
+ items: ToolKitItem[]; // List of toolkits
205
nextCursor?: string | null; // Pagination cursor
101
- totalPages: number; // Total number of pages
206
+ totalPages: number; // Total number of pages
207
}
208
```
209
@@ -106,18 +211,19 @@ interface ToolKitListResponse {
211
212
```typescript
213
interface ToolKitItem {
109
- name: string; // Name of the toolkit
110
- slug: string; // Unique slug identifier
111
- meta: { // Metadata about the toolkit
112
- createdAt: string; // When the toolkit was created
113
- updatedAt: string; // When the toolkit was last updated
114
- toolsCount: number; // Number of tools in the toolkit
115
- triggersCount: number; // Number of triggers in the toolkit
214
+ name: string; // Name of the toolkit
215
+ slug: string; // Unique slug identifier
216
+ meta: {
217
+ // Metadata about the toolkit
218
+ createdAt: string; // When the toolkit was created
219
+ updatedAt: string; // When the toolkit was last updated
220
+ toolsCount: number; // Number of tools in the toolkit
221
+ triggersCount: number; // Number of triggers in the toolkit
222
};
117
- isLocalToolkit: boolean; // Whether this is a local toolkit
118
- authSchemes: string[]; // Available authentication schemes
223
+ isLocalToolkit: boolean; // Whether this is a local toolkit
224
+ authSchemes: string[]; // Available authentication schemes
225
composioManagedAuthSchemes: string[]; // Managed auth schemes
120
- noAuth: boolean; // Whether authentication is required
226
+ noAuth: boolean; // Whether authentication is required
227
}
228
```
229
@@ -125,25 +231,29 @@ interface ToolKitItem {
231
232
```typescript
233
interface ToolkitRetrieveResponse {
128
- name: string; // Name of the toolkit
129
- slug: string; // Unique slug identifier
130
- meta: { // Metadata about the toolkit
131
- createdAt: string; // When the toolkit was created
132
- updatedAt: string; // When the toolkit was last updated
133
- toolsCount: number; // Number of tools in the toolkit
134
- triggersCount: number; // Number of triggers in the toolkit
234
+ name: string; // Name of the toolkit
235
+ slug: string; // Unique slug identifier
236
+ meta: {
237
+ // Metadata about the toolkit
238
+ createdAt: string; // When the toolkit was created
239
+ updatedAt: string; // When the toolkit was last updated
240
+ toolsCount: number; // Number of tools in the toolkit
241
+ triggersCount: number; // Number of triggers in the toolkit
242
};
136
- isLocalToolkit: boolean; // Whether this is a local toolkit
243
+ isLocalToolkit: boolean; // Whether this is a local toolkit
244
composioManagedAuthSchemes: string[]; // Managed auth schemes
138
- authConfigDetails: { // Authentication configuration details
139
- name: string; // Name of the auth configuration
140
- mode: string; // Auth mode (e.g., "OAUTH2")
141
- fields: { // Required fields
142
- authConfigCreation: Record<string, unknown>; // Fields for creating auth config
245
+ authConfigDetails: {
246
+ // Authentication configuration details
247
+ name: string; // Name of the auth configuration
248
+ mode: string; // Auth mode (e.g., "OAUTH2")
249
+ fields: {
250
+ // Required fields
251
+ authConfigCreation: Record<string, unknown>; // Fields for creating auth config
252
connectedAccountInitiation: Record<string, unknown>; // Fields for initiating connection
253
};
145
- proxy?: { // Proxy configuration (if any)
146
- baseUrl: string; // Base URL for proxied requests
254
+ proxy?: {
255
+ // Proxy configuration (if any)
256
+ baseUrl: string; // Base URL for proxied requests
257
};
258
}[];
259
}
@@ -155,7 +265,7 @@ interface ToolkitRetrieveResponse {
265
interface ToolkitRetrieveCategoriesResponse {
266
items: ToolkitCategory[]; // List of categories
267
nextCursor?: string | null; // Pagination cursor
158
- totalPages: number; // Total number of pages
268
+ totalPages: number; // Total number of pages
269
}
270
```
271
@@ -163,7 +273,7 @@ interface ToolkitRetrieveCategoriesResponse {
273
274
```typescript
275
interface ToolkitCategory {
166
- id: string; // Category ID
167
- name: string; // Category name
276
+ id: string; // Category ID
277
+ name: string; // Category name
278
}
169
-```
\ No newline at end of file
279
+```