Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Fix triggers
haxzie committed
May 28, 2025 at 15:36 UTC
cc9561ade9f9b08cbd85337fcf7bf9d3ed08f57e
17 files changed
+301
-136
docs/advanced/modifiers.md
+36
-44
@@ -179,10 +179,10 @@ const openaiTools = await composioNonAgentic.tools.get(
179
// Enhance tool schema
180
return tool;
181
},
182
-
182
+
183
// These will be ignored by non-agentic providers
184
beforeExecute: () => {}, // No effect with non-agentic providers
185
- afterExecute: () => {}, // No effect with non-agentic providers
185
+ afterExecute: () => {}, // No effect with non-agentic providers
186
}
187
);
188
```
@@ -250,20 +250,16 @@ const openai = new Composio({
250
});
251
252
// Schema modifiers work with non-agentic providers
253
-const nonAgenticTools = await openai.tools.get(
254
- 'default',
255
- 'HACKERNEWS_GET_USER',
256
- {
257
- // Schema modifier works with all providers
258
- modifySchema: (toolSlug, toolkitSlug, tool) => {
259
- // Customize the input parameters
260
- if (tool.inputParameters?.properties?.userId) {
261
- tool.inputParameters.properties.userId.description = 'HackerNews username (e.g., "pg")';
262
- }
263
- return tool;
264
- },
265
- }
266
-);
253
+const nonAgenticTools = await openai.tools.get('default', 'HACKERNEWS_GET_USER', {
254
+ // Schema modifier works with all providers
255
+ modifySchema: (toolSlug, toolkitSlug, tool) => {
256
+ // Customize the input parameters
257
+ if (tool.inputParameters?.properties?.userId) {
258
+ tool.inputParameters.properties.userId.description = 'HackerNews username (e.g., "pg")';
259
+ }
260
+ return tool;
261
+ },
262
+});
263
264
// Agentic provider example (Vercel)
265
const vercel = new Composio({
@@ -272,30 +268,26 @@ const vercel = new Composio({
268
});
269
270
// All modifiers work with agentic providers
275
-const agenticTools = await vercel.tools.get(
276
- 'default',
277
- 'HACKERNEWS_GET_USER',
278
- {
279
- // Schema modifier
280
- modifySchema: (toolSlug, toolkitSlug, tool) => {
281
- if (tool.inputParameters?.properties?.userId) {
282
- tool.inputParameters.properties.userId.description = 'HackerNews username (e.g., "pg")';
283
- }
284
- return tool;
285
- },
286
- // Execution modifiers (only work with agentic providers)
287
- beforeExecute: (toolSlug, toolkitSlug, params) => {
288
- console.log(`Executing ${toolSlug} from ${toolkitSlug}`);
289
- return params;
290
- },
291
- afterExecute: (toolSlug, toolkitSlug, result) => {
292
- if (result.successful) {
293
- result.data.processedAt = new Date().toISOString();
294
- }
295
- return result;
296
- },
297
- }
298
-);
271
+const agenticTools = await vercel.tools.get('default', 'HACKERNEWS_GET_USER', {
272
+ // Schema modifier
273
+ modifySchema: (toolSlug, toolkitSlug, tool) => {
274
+ if (tool.inputParameters?.properties?.userId) {
275
+ tool.inputParameters.properties.userId.description = 'HackerNews username (e.g., "pg")';
276
+ }
277
+ return tool;
278
+ },
279
+ // Execution modifiers (only work with agentic providers)
280
+ beforeExecute: (toolSlug, toolkitSlug, params) => {
281
+ console.log(`Executing ${toolSlug} from ${toolkitSlug}`);
282
+ return params;
283
+ },
284
+ afterExecute: (toolSlug, toolkitSlug, result) => {
285
+ if (result.successful) {
286
+ result.data.processedAt = new Date().toISOString();
287
+ }
288
+ return result;
289
+ },
290
+});
291
```
292
293
### Manual Execution Modifiers with Non-Agentic Providers
@@ -307,7 +299,7 @@ For non-agentic providers, you can use the provider's helper methods to apply ex
299
const openaiProvider = composio.provider as OpenAIProvider;
300
301
// When handling a tool call from OpenAI
310
-const toolOutputs = await openaiProvider.handleToolCall(
302
+const toolOutputs = await openaiProvider.handleToolCalls(
303
'default', // userId
304
completion, // OpenAI completion object
305
{ connectedAccountId: 'account_123' }, // Options
@@ -320,7 +312,7 @@ const toolOutputs = await openaiProvider.handleToolCall(
312
afterExecute: (toolSlug, toolkitSlug, result) => {
313
result.data.processedAt = new Date().toISOString();
314
return result;
323
- }
315
+ },
316
}
317
);
318
```
@@ -566,7 +558,7 @@ const result = await openaiProvider.executeToolCall(
558
afterExecute: (toolSlug, toolkitSlug, result) => {
559
result.data.processedAt = new Date().toISOString();
560
return result;
569
- }
561
+ },
562
}
563
);
564
```
@@ -601,6 +593,6 @@ interface ExecuteToolModifiers {
593
interface ProviderOptions<TProvider> {
594
modifySchema?: TransformToolSchemaModifier;
595
beforeExecute?: beforeExecuteModifier; // Only applied by agentic providers
604
- afterExecute?: afterExecuteModifier; // Only applied by agentic providers
596
+ afterExecute?: afterExecuteModifier; // Only applied by agentic providers
597
}
598
```
docs/api/providers.md
+2
-2
@@ -117,12 +117,12 @@ const result = await openaiProvider.executeToolCall(
117
118
**Returns:** Promise<string> - The result of the tool call as JSON string
119
120
-#### handleToolCall(userId, chatCompletion, options?, modifiers?)
120
+#### handleToolCalls(userId, chatCompletion, options?, modifiers?)
121
122
Handles tool calls from an OpenAI chat completion.
123
124
```typescript
125
-const outputs = await openaiProvider.handleToolCall('user123', chatCompletion);
125
+const outputs = await openaiProvider.handleToolCalls('user123', chatCompletion);
126
```
127
128
**Parameters:**
docs/providers/openai.md
+2
-2
@@ -110,7 +110,7 @@ const completion = await openai.chat.completions.create({
110
// Check if there are tool calls
111
if (completion.choices[0].message.tool_calls) {
112
// Handle the tool calls
113
- const toolOutputs = await openaiProvider.handleToolCall(
113
+ const toolOutputs = await openaiProvider.handleToolCalls(
114
'default', // userId
115
completion,
116
{ connectedAccountId: 'connected_account_123' } // Optional
@@ -342,7 +342,7 @@ class OpenAIProvider extends BaseNonAgenticProvider<OpenAiToolCollection, OpenAi
342
modifiers?: ExecuteToolModifiers
343
): Promise<string>;
344
345
- handleToolCall(
345
+ handleToolCalls(
346
userId: string,
347
chatCompletion: OpenAI.ChatCompletion,
348
options?: ExecuteToolFnOptions,
examples/openai/src/index.ts
+1
-1
@@ -46,7 +46,7 @@ const response = await openai.chat.completions.create({
46
*/
47
if (response.choices[0].message.tool_calls) {
48
console.log(`✅ Calling tool ${response.choices[0].message.tool_calls[0].function.name}`);
49
- const result = await composio.provider.handleToolCall('default', response);
49
+ const result = await composio.provider.handleToolCalls('default', response);
50
const data = JSON.parse(result[0]);
51
console.log(data);
52
}
examples/openai/src/tools.ts
+1
-1
@@ -28,6 +28,6 @@ const response = await openai.chat.completions.create({
28
tool_choice: 'auto',
29
});
30
31
-const toolCall = await composio.provider.handleToolCall('default', response);
31
+const toolCall = await composio.provider.handleToolCalls('default', response);
32
33
console.log(toolCall);
examples/triggers/src/index.ts
+1
@@ -17,6 +17,7 @@ import 'dotenv/config';
17
*/
18
const composio = new Composio({
19
apiKey: process.env.COMPOSIO_API_KEY,
20
+ baseURL: 'http://localhost:9900',
21
});
22
23
/**
packages/core/src/models/Triggers.ts
+22
-18
@@ -323,7 +323,7 @@ export class Triggers {
323
// Check if connectedAccountId filter matches
324
if (
325
parsedFilters.data.connectedAccountId &&
326
- parsedFilters.data.connectedAccountId !== data.metadata.connectedAccountId
326
+ parsedFilters.data.connectedAccountId !== data.metadata.connectedAccount.id
327
) {
328
logger.debug(
329
'Trigger does not match connectedAccountId filter',
@@ -334,12 +334,14 @@ export class Triggers {
334
335
// Check if triggerName filter matches
336
if (
337
- parsedFilters.data.triggerName &&
338
- parsedFilters.data.triggerName !== data.metadata.triggerName
337
+ parsedFilters.data.triggerSlug?.length &&
338
+ !parsedFilters.data.triggerSlug
339
+ .map(triggerSlug => triggerSlug.toLowerCase())
340
+ .includes(data.triggerSlug.toLowerCase())
341
) {
342
logger.debug(
341
- 'Trigger does not match triggerName filter',
342
- JSON.stringify(parsedFilters.data.triggerName, null, 2)
343
+ 'Trigger does not match triggerSlug filter',
344
+ JSON.stringify(parsedFilters.data.triggerSlug, null, 2)
345
);
346
return false;
347
}
@@ -359,7 +361,7 @@ export class Triggers {
361
// Check if userId (clientUniqueUserId) filter matches
362
if (
363
parsedFilters.data.userId &&
362
- parsedFilters.data.userId !== data.metadata.connection.clientUniqueUserId
364
+ parsedFilters.data.userId !== data.metadata.connectedAccount.userId
365
) {
366
logger.debug(
367
'Trigger does not match userId filter',
@@ -375,33 +377,35 @@ export class Triggers {
377
378
logger.debug('🔄 Subscribing to triggers with filters: ', JSON.stringify(filters, null, 2));
379
await this.pusherService.subscribe((_data: Record<string, unknown>) => {
378
- logger.debug('Received trigger data', JSON.stringify(_data, null, 2));
380
+ logger.debug('Received raw trigger data', JSON.stringify(_data, null, 2));
381
// @TODO: This is a temporary fix to get the trigger data
382
// ideally we should have a type for the trigger data
383
const data = _data as TriggerData;
384
const parsedData = IncomingTriggerPayloadSchema.safeParse({
385
id: data.metadata.id,
384
- clientId: String(data.clientId),
386
triggerSlug: data.metadata.triggerName,
387
toolkitSlug: data.appName,
388
+ userId: data.metadata.connection.clientUniqueUserId,
389
payload: data.payload,
390
originalPayload: data.originalPayload,
391
metadata: {
390
- ...data.metadata,
392
id: data.metadata.id,
392
- connectedAccountId: data.metadata.connection?.id,
393
- triggerSlug: data.metadata.triggerName,
394
- triggerName: data.metadata.triggerName,
395
- triggerData: data.metadata.triggerData,
393
triggerConfig: data.metadata.triggerConfig,
397
- connection: {
398
- id: data.metadata?.connection?.id,
399
- integrationId: data.metadata?.connection?.integrationId,
400
- clientUniqueUserId: data.metadata?.connection?.clientUniqueUserId,
401
- status: data.metadata?.connection?.status,
394
+ triggerSlug: data.metadata.triggerName,
395
+ toolkitSlug: data.appName,
396
+ connectedAccount: {
397
+ id: data.metadata.connection.connectedAccountNanoId,
398
+ uuid: data.metadata.connection.id,
399
+ authConfigId: data.metadata.connection.authConfigNanoId,
400
+ authConfigUUID: data.metadata.connection.integrationId,
401
+ userId: data.metadata.connection.clientUniqueUserId,
402
+ status: data.metadata.connection.status,
403
},
404
},
405
} as IncomingTriggerPayload);
406
+
407
+ logger.debug('Parsed trigger data', JSON.stringify(parsedData.data, null, 2));
408
+
409
if (parsedData.error) {
410
throw new ValidationError(`Invalid trigger payload`, {
411
cause: parsedData.error,
packages/core/src/provider/OpenAIProvider.ts
+1
-1
@@ -70,7 +70,7 @@ export class OpenAIProvider extends BaseNonAgenticProvider<OpenAiToolCollection,
70
* @param {string} userId - The user id.
71
* @returns {Promise<string[]>} The results of the tool call.
72
*/
73
- async handleToolCall(
73
+ async handleToolCalls(
74
userId: string,
75
chatCompletion: OpenAI.ChatCompletion,
76
options?: ExecuteToolFnOptions,
packages/core/src/services/internal/InternalService.ts
+7
-1
@@ -11,7 +11,8 @@ import {
11
SDKRealtimeCredentialsResponseSchema,
12
} from './InternalService.types';
13
import { ValidationError } from '../../errors';
14
-const SDK_REALTIME_CREDENTIALS_ENDPOINT = '/v3/internal/sdk/realtime/credentials';
14
+import logger from '../../utils/logger';
15
+const SDK_REALTIME_CREDENTIALS_ENDPOINT = '/api/v3/internal/sdk/realtime/credentials';
16
17
export class InternalService {
18
constructor(private readonly client: ComposioClitent) {
@@ -31,8 +32,13 @@ export class InternalService {
32
const parsedResponse = SDKRealtimeCredentialsResponseSchema.safeParse({
33
pusherKey: response.pusher_key,
34
projectId: response.project_id,
35
+ pusherCluster: response.pusher_cluster,
36
});
37
38
+ logger.debug(
39
+ `[InternalService] SDK realtime credentials: ${JSON.stringify(parsedResponse, null, 2)}`
40
+ );
41
+
42
if (!parsedResponse.success) {
43
throw new ValidationError(`Failed to parse SDK realtime credentials`, {
44
cause: parsedResponse.error,
packages/core/src/services/internal/InternalService.types.ts
+2
-1
@@ -3,11 +3,12 @@ import { z } from 'zod';
3
export interface ComposioSDKRealtimeCredentialsResponse {
4
pusher_key: string;
5
project_id: string;
6
+ pusher_cluster: string;
7
}
8
9
export const SDKRealtimeCredentialsResponseSchema = z.object({
10
+ projectId: z.string().describe('The project ID'),
11
pusherKey: z.string().describe('The Pusher key'),
12
pusherCluster: z.string().describe('The Pusher cluster'),
11
- projectId: z.string().describe('The project ID'),
13
});
14
export type SDKRealtimeCredentialsResponse = z.infer<typeof SDKRealtimeCredentialsResponseSchema>;
packages/core/src/services/pusher/Pusher.ts
+10
-5
@@ -55,7 +55,9 @@ export class PusherService {
55
this.pusherCluster = sdkRealtimeCredentials.pusherCluster;
56
this.pusherChannel = `private-${this.clientId}_triggers`;
57
58
- logger.debug(`[PusherService] Creating Pusher client for client ID: ${this.clientId}`);
58
+ logger.debug(
59
+ `[PusherService] Creating Pusher client for client ID: ${this.clientId} in cluster ${this.pusherCluster}`
60
+ );
61
62
// create the Pusher client
63
try {
@@ -63,7 +65,7 @@ export class PusherService {
65
this.pusherClient = new Pusher(this.pusherKey, {
66
cluster: this.pusherCluster,
67
channelAuthorization: {
66
- endpoint: `${this.pusherBaseURL}/api/v1/client/auth/pusher_auth`,
68
+ endpoint: `${this.pusherBaseURL}/api/v3/internal/sdk/realtime/auth`,
69
headers: {
70
'x-api-key': this.apiKey,
71
},
@@ -170,9 +172,12 @@ export class PusherService {
172
// add subscription error handling
173
channel.bind('pusher:subscription_error', (data: Record<string, unknown>) => {
174
const error = data.error ? String(data.error) : 'Unknown subscription error';
173
- throw new ComposioFailedToSubscribeToPusherChannelError(`Trigger subscription error`, {
174
- cause: error,
175
- });
175
+ throw new ComposioFailedToSubscribeToPusherChannelError(
176
+ `Trigger subscription error: ${error}`,
177
+ {
178
+ cause: error,
179
+ }
180
+ );
181
});
182
183
// wrap the callback to handle errors
packages/core/src/types/triggers.types.ts
+9
-8
@@ -12,7 +12,7 @@ export const TriggerSubscribeParamSchema = z.object({
12
triggerId: z.string().optional(),
13
connectedAccountId: z.string().optional(),
14
authConfigId: z.string().optional(),
15
- triggerName: z.string().optional(),
15
+ triggerSlug: z.array(z.string()).optional(),
16
triggerData: z.string().optional(),
17
userId: z.string().optional(),
18
});
@@ -94,23 +94,24 @@ export type TriggerInstanceManageDeleteResponse = z.infer<
94
95
export const IncomingTriggerPayloadSchema = z.object({
96
id: z.string().describe('The ID of the trigger'),
97
- clientId: z.string().describe('The ID of the client that triggered the event'),
97
triggerSlug: z.string().describe('The slug of the trigger that triggered the event'),
98
toolkitSlug: z.string().describe('The slug of the toolkit that triggered the event'),
99
+ userId: z.string().describe('The ID of the user that triggered the event'),
100
payload: z.record(z.unknown()).describe('The payload of the trigger'),
101
originalPayload: z.record(z.unknown()).describe('The original payload of the trigger'),
102
metadata: z.object({
103
id: z.string(),
104
- connectedAccountId: z.string(),
104
+ toolkitSlug: z.string(),
105
triggerSlug: z.string(),
106
- triggerName: z.string(),
106
triggerData: z.string().optional(),
107
triggerConfig: z.record(z.unknown()),
109
- connection: z.object({
108
+ connectedAccount: z.object({
109
id: z.string(),
111
- integrationId: z.string(),
112
- clientUniqueUserId: z.string(),
113
- status: z.enum(['enable', 'disable']),
110
+ uuid: z.string(),
111
+ authConfigId: z.string(),
112
+ authConfigUUID: z.string(),
113
+ userId: z.string(),
114
+ status: z.enum(['ACTIVE', 'INACTIVE']),
115
}),
116
}),
117
});
packages/core/src/utils/pusher.ts
+33
-2
@@ -16,9 +16,16 @@ type PusherClient = {
16
bind: (event: string, callback: (data: Record<string, unknown>) => void) => unknown;
17
connection: {
18
bind: (event: string, callback: (error: Error) => void) => void;
19
+ socket_id?: string;
20
};
21
};
22
23
+type AuthOptions = {
24
+ endpoint: string;
25
+ headers: Record<string, string>;
26
+ params?: Record<string, string>;
27
+};
28
+
29
type TChunkedTriggerData = {
30
id: string;
31
index: number;
@@ -33,13 +40,14 @@ export type TriggerData = {
40
originalPayload: Record<string, unknown>;
41
metadata: {
42
id: string;
36
- connectionId: string;
43
triggerName: string;
44
triggerData: string;
45
triggerConfig: Record<string, unknown>;
46
connection: {
47
id: string;
48
+ connectedAccountNanoId: string;
49
integrationId: string;
50
+ authConfigNanoId: string;
51
clientUniqueUserId: string;
52
status: string;
53
};
@@ -64,6 +72,29 @@ export class PusherUtils {
72
'x-api-key': apiKey,
73
},
74
transport: 'ajax',
75
+ customHandler: async (authOptions: AuthOptions) => {
76
+ try {
77
+ const response = await fetch(authOptions.endpoint, {
78
+ method: 'POST',
79
+ headers: {
80
+ ...authOptions.headers,
81
+ 'Content-Type': 'application/json',
82
+ },
83
+ body: JSON.stringify(authOptions.params),
84
+ });
85
+ const data = await response.text();
86
+ logger.debug('Pusher auth response:', data);
87
+ try {
88
+ return JSON.parse(data);
89
+ } catch (e) {
90
+ logger.error('Failed to parse auth response:', data);
91
+ throw new Error('Invalid auth response format');
92
+ }
93
+ } catch (error) {
94
+ logger.error('Pusher auth request failed:', error);
95
+ throw error;
96
+ }
97
+ },
98
},
99
});
100
@@ -247,7 +278,7 @@ export class PusherUtils {
278
if (!PusherUtils.pusherClient) {
279
throw new Error('Pusher client not initialized');
280
}
250
- PusherUtils.pusherClient.unsubscribe(`${clientId}_triggers`);
281
+ PusherUtils.pusherClient.unsubscribe(`private-${clientId}_triggers`);
282
logger.info('Successfully unsubscribed from triggers');
283
} catch (error: unknown) {
284
const errorMessage = error instanceof Error ? error.message : String(error);
packages/core/test/provider/openai-provider.test.ts
+3
-3
@@ -152,7 +152,7 @@ describe('OpenAIProvider', () => {
152
});
153
});
154
155
- describe('handleToolCall', () => {
155
+ describe('handleToolCalls', () => {
156
it('should handle tool calls from chat completion', async () => {
157
const userId = 'test-user';
158
const chatCompletion = {
@@ -191,7 +191,7 @@ describe('OpenAIProvider', () => {
191
const executeToolCallSpy = vi.spyOn(provider, 'executeToolCall');
192
executeToolCallSpy.mockResolvedValue(JSON.stringify({ result: 'success' }));
193
194
- const results = await provider.handleToolCall(userId, chatCompletion);
194
+ const results = await provider.handleToolCalls(userId, chatCompletion);
195
196
expect(executeToolCallSpy).toHaveBeenCalledWith(
197
userId,
@@ -241,7 +241,7 @@ describe('OpenAIProvider', () => {
241
const executeToolCallSpy = vi.spyOn(provider, 'executeToolCall');
242
executeToolCallSpy.mockResolvedValue(JSON.stringify({ result: 'success' }));
243
244
- const results = await provider.handleToolCall(userId, chatCompletion);
244
+ const results = await provider.handleToolCalls(userId, chatCompletion);
245
246
expect(executeToolCallSpy).toHaveBeenCalledTimes(1);
247
expect(results).toEqual([JSON.stringify({ result: 'success' })]);
packages/providers/anthropic/README.md
+86
-10
@@ -1,12 +1,14 @@
1
# @composio/anthropic
2
3
-Agentic Provider for Anthropic in Composio SDK.
3
+Non-Agentic Provider for Anthropic in Composio SDK.
4
5
## Features
6
7
-- **Full Modifier Support**: Support for both schema and execution modifiers
8
-- **Tool Execution**: Execute tools with proper parameter handling
7
+- **Tool Integration**: Seamless integration with Anthropic's tool calling capabilities
8
- **Type Safety**: Full TypeScript support with proper type definitions
9
+- **Tool Execution**: Execute tools with proper parameter handling and response formatting
10
+- **Caching Support**: Optional tool caching for improved performance
11
+- **Modifier Support**: Support for execution modifiers to transform tool inputs and outputs
12
13
## Installation
14
@@ -27,7 +29,8 @@ import { AnthropicProvider } from '@composio/anthropic';
29
// Initialize Composio with Anthropic provider
30
const composio = new Composio({
31
apiKey: 'your-composio-api-key',
30
- provider: new AnthropicProvider(),
32
+ // Initialize with optional caching
33
+ provider: new AnthropicProvider({ cacheTools: true }),
34
});
35
36
// Get available tools
@@ -56,24 +59,97 @@ const tools = await composio.tools.get('user123', {
59
toolkits: ['gmail'],
60
});
61
59
-// Use tools with Anthropic
60
-// Add your usage example here
62
+// Handle tool execution with modifiers
63
+const modifiers = {
64
+ beforeExecute: params => {
65
+ // Transform tool parameters before execution
66
+ return params;
67
+ },
68
+ afterExecute: response => {
69
+ // Transform tool response after execution
70
+ return response;
71
+ },
72
+};
73
+
74
+// Execute a tool with options
75
+const result = await provider.executeTool(
76
+ 'tool-name',
77
+ {
78
+ userId: 'user123',
79
+ arguments: { input: 'value' },
80
+ connectedAccountId: 'account123',
81
+ customAuthParams: {
82
+ parameters: [{ name: 'token', value: 'abc123', in: 'header' }],
83
+ },
84
+ },
85
+ modifiers
86
+);
87
```
88
89
## API Reference
90
91
### AnthropicProvider Class
92
67
-The `AnthropicProvider` class extends `BaseAgenticProvider` and provides anthropic-specific functionality.
93
+The `AnthropicProvider` class extends `BaseNonAgenticProvider` and provides Anthropic-specific functionality.
94
+
95
+#### Constructor
96
+
97
+```typescript
98
+new AnthropicProvider(options?: { cacheTools?: boolean })
99
+```
100
+
101
+- `options.cacheTools`: Optional boolean to enable tool caching (default: false)
102
103
#### Methods
104
71
-##### `wrapTool(tool: Tool, executeTool: ExecuteToolFn): AnthropicTool`
105
+##### `wrapTool(tool: Tool): AnthropicTool`
106
+
107
+Wraps a Composio tool in the Anthropic format.
108
+
109
+```typescript
110
+const tool = provider.wrapTool(composioTool);
111
+```
112
+
113
+##### `wrapTools(tools: Tool[]): AnthropicToolCollection`
114
+
115
+Wraps multiple Composio tools in the Anthropic format.
116
+
117
+```typescript
118
+const tools = provider.wrapTools(composioTools);
119
+```
120
+
121
+##### `executeToolCall(userId: string, toolUse: AnthropicToolUseBlock, options?: ExecuteToolFnOptions, modifiers?: ExecuteToolModifiers): Promise<string>`
122
+
123
+Executes a tool call from Anthropic and returns the result as a string.
124
+
125
+```typescript
126
+const result = await provider.executeToolCall(
127
+ 'user123',
128
+ {
129
+ type: 'tool_use',
130
+ id: 'tu_123',
131
+ name: 'tool-name',
132
+ input: { param: 'value' },
133
+ },
134
+ {
135
+ connectedAccountId: 'account123',
136
+ customAuthParams: {
137
+ /* ... */
138
+ },
139
+ },
140
+ {
141
+ beforeExecute: params => params,
142
+ afterExecute: response => response,
143
+ }
144
+);
145
+```
146
+
147
+##### `handleToolCalls(userId: string, message: Message, options?: ExecuteToolFnOptions, modifiers?: ExecuteToolModifiers): Promise<string[]>`
148
73
-Wraps a tool in the anthropic format.
149
+Handles tool calls from an Anthropic message response.
150
151
```typescript
76
-const tool = provider.wrapTool(composioTool, executeTool);
152
+const results = await provider.handleToolCalls('user123', message, options, modifiers);
153
```
154
155
## Contributing
packages/providers/google/README.md
+82
-34
@@ -6,8 +6,9 @@ Google GenAI Provider for Composio SDK.
6
7
- **Google GenAI Integration**: Seamless integration with Google's Generative AI models (Gemini)
8
- **Function Calling Support**: Convert Composio tools to Google GenAI function declarations
9
-- **Multiple Authentication Methods**: Support for both API key and Vertex AI authentication
9
- **Type Safety**: Full TypeScript support with proper type definitions
10
+- **Execution Modifiers**: Support for transforming tool inputs and outputs
11
+- **Flexible Authentication**: Support for custom authentication parameters
12
13
## Installation
14
@@ -24,12 +25,10 @@ pnpm add @composio/google @google/genai
25
```typescript
26
import { Composio } from '@composio/core';
27
import { GoogleProvider } from '@composio/google';
27
-import { GoogleGenAI } from '@google/genai';
28
+import { GoogleGenerativeAI } from '@google/genai';
29
30
// Initialize Google GenAI
30
-const ai = new GoogleGenAI({
31
- apiKey: process.env.GEMINI_API_KEY,
32
-});
31
+const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
32
33
// Initialize Composio with Google provider
34
const composio = new Composio({
@@ -38,7 +37,10 @@ const composio = new Composio({
37
});
38
39
// Get available tools
41
-const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER');
40
+const tools = await composio.tools.get('user123', {
41
+ toolkits: ['gmail', 'calendar'],
42
+ limit: 10,
43
+});
44
```
45
46
## Usage Examples
@@ -48,12 +50,10 @@ const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER');
50
```typescript
51
import { Composio } from '@composio/core';
52
import { GoogleProvider } from '@composio/google';
51
-import { GoogleGenAI } from '@google/genai';
53
+import { GoogleGenerativeAI } from '@google/genai';
54
55
// Initialize Google GenAI
54
-const ai = new GoogleGenAI({
55
- apiKey: process.env.GEMINI_API_KEY,
56
-});
56
+const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
57
58
// Initialize Composio
59
const composio = new Composio({
@@ -61,29 +61,52 @@ const composio = new Composio({
61
provider: new GoogleProvider(),
62
});
63
64
-// Get tools
65
-const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER');
66
-
67
-// Define task
68
-const task = "Fetch the details of the user 'haxzie'";
69
-
70
-// Generate content with function calling
71
-const response = await ai.models.generateContent({
72
- model: 'gemini-2.0-flash-001',
73
- contents: task,
74
- config: {
75
- tools: [{ functionDeclarations: tools }],
64
+// Handle tool execution with modifiers
65
+const modifiers = {
66
+ beforeExecute: params => {
67
+ // Transform tool parameters before execution
68
+ return params;
69
},
77
-});
78
-
79
-// Handle function calls
80
-if (response.functionCalls) {
81
- const result = await composio.tools.execute(response.functionCalls[0].name, {
82
- userId: 'default',
83
- arguments: response.functionCalls[0].args,
84
- });
85
- console.log(result.data);
86
-}
70
+ afterExecute: response => {
71
+ // Transform tool response after execution
72
+ return response;
73
+ },
74
+};
75
+
76
+// Execute a tool with options
77
+const result = await provider.executeTool(
78
+ 'tool-name',
79
+ {
80
+ userId: 'user123',
81
+ arguments: { input: 'value' },
82
+ connectedAccountId: 'account123',
83
+ customAuthParams: {
84
+ parameters: [{ name: 'token', value: 'abc123', in: 'header' }],
85
+ },
86
+ },
87
+ modifiers
88
+);
89
+
90
+// Handle function calls from Google GenAI
91
+const functionCall = {
92
+ name: 'tool-name',
93
+ args: { param: 'value' },
94
+};
95
+
96
+const toolResult = await provider.executeToolCall(
97
+ 'user123',
98
+ functionCall,
99
+ {
100
+ connectedAccountId: 'account123',
101
+ customAuthParams: {
102
+ /* ... */
103
+ },
104
+ },
105
+ {
106
+ beforeExecute: params => params,
107
+ afterExecute: response => response,
108
+ }
109
+);
110
```
111
112
## API Reference
@@ -94,7 +117,7 @@ The `GoogleProvider` class extends `BaseNonAgenticProvider` and provides Google
117
118
#### Methods
119
97
-##### `wrapTool(tool: Tool): GoogleGenAIFunctionDeclaration`
120
+##### `wrapTool(tool: Tool): GoogleTool`
121
122
Wraps a Composio tool in the Google GenAI function declaration format.
123
@@ -104,12 +127,37 @@ const wrappedTool = provider.wrapTool(composioTool);
127
128
##### `wrapTools(tools: Tool[]): GoogleGenAIToolCollection`
129
107
-Wraps a list of Composio tools in the Google GenAI function declaration format.
130
+Wraps multiple Composio tools in the Google GenAI function declaration format.
131
132
```typescript
133
const wrappedTools = provider.wrapTools(composioTools);
134
```
135
136
+##### `executeToolCall(userId: string, tool: GoogleGenAIFunctionCall, options?: ExecuteToolFnOptions, modifiers?: ExecuteToolModifiers): Promise<string>`
137
+
138
+Executes a tool call from Google GenAI and returns the result as a JSON string.
139
+
140
+```typescript
141
+const result = await provider.executeToolCall('user123', functionCall, options, modifiers);
142
+```
143
+
144
+#### Types
145
+
146
+```typescript
147
+interface GoogleGenAIFunctionCall {
148
+ name: string;
149
+ args: Record<string, unknown>;
150
+}
151
+
152
+type GoogleTool = {
153
+ name: string;
154
+ description: string;
155
+ parameters: Schema;
156
+};
157
+
158
+type GoogleGenAIToolCollection = GoogleTool[];
159
+```
160
+
161
## Contributing
162
163
We welcome contributions! Please see our [Contributing Guide](../../CONTRIBUTING.md) for more details.
packages/providers/openai/test/openai.test.ts
+3
-3
@@ -233,7 +233,7 @@ describe('OpenAIProvider', () => {
233
});
234
});
235
236
- describe('handleToolCall', () => {
236
+ describe('handleToolCalls', () => {
237
it('should handle tool calls from chat completion', async () => {
238
const userId = 'test-user';
239
const chatCompletion = {
@@ -271,7 +271,7 @@ describe('OpenAIProvider', () => {
271
const executeToolCallSpy = vi.spyOn(provider, 'executeToolCall');
272
executeToolCallSpy.mockResolvedValue(JSON.stringify({ result: 'success' }));
273
274
- const results = await provider.handleToolCall(userId, chatCompletion);
274
+ const results = await provider.handleToolCalls(userId, chatCompletion);
275
276
expect(executeToolCallSpy).toHaveBeenCalledWith(
277
userId,
@@ -339,7 +339,7 @@ describe('OpenAIProvider', () => {
339
.mockResolvedValueOnce(JSON.stringify({ result: 'success-1' }))
340
.mockResolvedValueOnce(JSON.stringify({ result: 'success-2' }));
341
342
- const results = await provider.handleToolCall(userId, chatCompletion);
342
+ const results = await provider.handleToolCalls(userId, chatCompletion);
343
344
expect(executeToolCallSpy).toHaveBeenCalledTimes(2);
345
expect(executeToolCallSpy).toHaveBeenNthCalledWith(