Skip to content

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

Fix triggers

haxziecc9561ade9f9
diff --git a/docs/advanced/modifiers.md b/docs/advanced/modifiers.md
index 6bac540a0..8c9b01b6f 100644
--- a/docs/advanced/modifiers.md
+++ b/docs/advanced/modifiers.md
@@ -179,10 +179,10 @@ const openaiTools = await composioNonAgentic.tools.get(
// Enhance tool schema
return tool;
},
-
+
// These will be ignored by non-agentic providers
beforeExecute: () => {}, // No effect with non-agentic providers
- afterExecute: () => {}, // No effect with non-agentic providers
+ afterExecute: () => {}, // No effect with non-agentic providers
}
);
```
@@ -250,20 +250,16 @@ const openai = new Composio({
});
// Schema modifiers work with non-agentic providers
-const nonAgenticTools = await openai.tools.get(
- 'default',
- 'HACKERNEWS_GET_USER',
- {
- // Schema modifier works with all providers
- modifySchema: (toolSlug, toolkitSlug, tool) => {
- // Customize the input parameters
- if (tool.inputParameters?.properties?.userId) {
- tool.inputParameters.properties.userId.description = 'HackerNews username (e.g., "pg")';
- }
- return tool;
- },
- }
-);
+const nonAgenticTools = await openai.tools.get('default', 'HACKERNEWS_GET_USER', {
+ // Schema modifier works with all providers
+ modifySchema: (toolSlug, toolkitSlug, tool) => {
+ // Customize the input parameters
+ if (tool.inputParameters?.properties?.userId) {
+ tool.inputParameters.properties.userId.description = 'HackerNews username (e.g., "pg")';
+ }
+ return tool;
+ },
+});
// Agentic provider example (Vercel)
const vercel = new Composio({
@@ -272,30 +268,26 @@ const vercel = new Composio({
});
// All modifiers work with agentic providers
-const agenticTools = await vercel.tools.get(
- 'default',
- 'HACKERNEWS_GET_USER',
- {
- // Schema modifier
- modifySchema: (toolSlug, toolkitSlug, tool) => {
- if (tool.inputParameters?.properties?.userId) {
- tool.inputParameters.properties.userId.description = 'HackerNews username (e.g., "pg")';
- }
- return tool;
- },
- // Execution modifiers (only work with agentic providers)
- beforeExecute: (toolSlug, toolkitSlug, params) => {
- console.log(`Executing ${toolSlug} from ${toolkitSlug}`);
- return params;
- },
- afterExecute: (toolSlug, toolkitSlug, result) => {
- if (result.successful) {
- result.data.processedAt = new Date().toISOString();
- }
- return result;
- },
- }
-);
+const agenticTools = await vercel.tools.get('default', 'HACKERNEWS_GET_USER', {
+ // Schema modifier
+ modifySchema: (toolSlug, toolkitSlug, tool) => {
+ if (tool.inputParameters?.properties?.userId) {
+ tool.inputParameters.properties.userId.description = 'HackerNews username (e.g., "pg")';
+ }
+ return tool;
+ },
+ // Execution modifiers (only work with agentic providers)
+ beforeExecute: (toolSlug, toolkitSlug, params) => {
+ console.log(`Executing ${toolSlug} from ${toolkitSlug}`);
+ return params;
+ },
+ afterExecute: (toolSlug, toolkitSlug, result) => {
+ if (result.successful) {
+ result.data.processedAt = new Date().toISOString();
+ }
+ return result;
+ },
+});
```
### 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
const openaiProvider = composio.provider as OpenAIProvider;
// When handling a tool call from OpenAI
-const toolOutputs = await openaiProvider.handleToolCall(
+const toolOutputs = await openaiProvider.handleToolCalls(
'default', // userId
completion, // OpenAI completion object
{ connectedAccountId: 'account_123' }, // Options
@@ -320,7 +312,7 @@ const toolOutputs = await openaiProvider.handleToolCall(
afterExecute: (toolSlug, toolkitSlug, result) => {
result.data.processedAt = new Date().toISOString();
return result;
- }
+ },
}
);
```
@@ -566,7 +558,7 @@ const result = await openaiProvider.executeToolCall(
afterExecute: (toolSlug, toolkitSlug, result) => {
result.data.processedAt = new Date().toISOString();
return result;
- }
+ },
}
);
```
@@ -601,6 +593,6 @@ interface ExecuteToolModifiers {
interface ProviderOptions<TProvider> {
modifySchema?: TransformToolSchemaModifier;
beforeExecute?: beforeExecuteModifier; // Only applied by agentic providers
- afterExecute?: afterExecuteModifier; // Only applied by agentic providers
+ afterExecute?: afterExecuteModifier; // Only applied by agentic providers
}
```
diff --git a/docs/api/providers.md b/docs/api/providers.md
index cf9432477..f13f98fee 100644
--- a/docs/api/providers.md
+++ b/docs/api/providers.md
@@ -117,12 +117,12 @@ const result = await openaiProvider.executeToolCall(
**Returns:** Promise<string> - The result of the tool call as JSON string
-#### handleToolCall(userId, chatCompletion, options?, modifiers?)
+#### handleToolCalls(userId, chatCompletion, options?, modifiers?)
Handles tool calls from an OpenAI chat completion.
```typescript
-const outputs = await openaiProvider.handleToolCall('user123', chatCompletion);
+const outputs = await openaiProvider.handleToolCalls('user123', chatCompletion);
```
**Parameters:**
diff --git a/docs/providers/openai.md b/docs/providers/openai.md
index ba0e3f4d2..b7c1eee3b 100644
--- a/docs/providers/openai.md
+++ b/docs/providers/openai.md
@@ -110,7 +110,7 @@ const completion = await openai.chat.completions.create({
// Check if there are tool calls
if (completion.choices[0].message.tool_calls) {
// Handle the tool calls
- const toolOutputs = await openaiProvider.handleToolCall(
+ const toolOutputs = await openaiProvider.handleToolCalls(
'default', // userId
completion,
{ connectedAccountId: 'connected_account_123' } // Optional
@@ -342,7 +342,7 @@ class OpenAIProvider extends BaseNonAgenticProvider<OpenAiToolCollection, OpenAi
modifiers?: ExecuteToolModifiers
): Promise<string>;
- handleToolCall(
+ handleToolCalls(
userId: string,
chatCompletion: OpenAI.ChatCompletion,
options?: ExecuteToolFnOptions,
diff --git a/examples/openai/src/index.ts b/examples/openai/src/index.ts
index 971546b5d..98a933f8c 100644
--- a/examples/openai/src/index.ts
+++ b/examples/openai/src/index.ts
@@ -46,7 +46,7 @@ const response = await openai.chat.completions.create({
*/
if (response.choices[0].message.tool_calls) {
console.log(`✅ Calling tool ${response.choices[0].message.tool_calls[0].function.name}`);
- const result = await composio.provider.handleToolCall('default', response);
+ const result = await composio.provider.handleToolCalls('default', response);
const data = JSON.parse(result[0]);
console.log(data);
}
diff --git a/examples/openai/src/tools.ts b/examples/openai/src/tools.ts
index 89c2f080b..d53f0536c 100644
--- a/examples/openai/src/tools.ts
+++ b/examples/openai/src/tools.ts
@@ -28,6 +28,6 @@ const response = await openai.chat.completions.create({
tool_choice: 'auto',
});
-const toolCall = await composio.provider.handleToolCall('default', response);
+const toolCall = await composio.provider.handleToolCalls('default', response);
console.log(toolCall);
diff --git a/examples/triggers/src/index.ts b/examples/triggers/src/index.ts
index c1f4a1d80..307257700 100644
--- a/examples/triggers/src/index.ts
+++ b/examples/triggers/src/index.ts
@@ -17,6 +17,7 @@ import 'dotenv/config';
*/
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
+ baseURL: 'http://localhost:9900',
});
/**
diff --git a/packages/core/src/models/Triggers.ts b/packages/core/src/models/Triggers.ts
index a1c1111c2..c7fed696d 100644
--- a/packages/core/src/models/Triggers.ts
+++ b/packages/core/src/models/Triggers.ts
@@ -323,7 +323,7 @@ export class Triggers {
// Check if connectedAccountId filter matches
if (
parsedFilters.data.connectedAccountId &&
- parsedFilters.data.connectedAccountId !== data.metadata.connectedAccountId
+ parsedFilters.data.connectedAccountId !== data.metadata.connectedAccount.id
) {
logger.debug(
'Trigger does not match connectedAccountId filter',
@@ -334,12 +334,14 @@ export class Triggers {
// Check if triggerName filter matches
if (
- parsedFilters.data.triggerName &&
- parsedFilters.data.triggerName !== data.metadata.triggerName
+ parsedFilters.data.triggerSlug?.length &&
+ !parsedFilters.data.triggerSlug
+ .map(triggerSlug => triggerSlug.toLowerCase())
+ .includes(data.triggerSlug.toLowerCase())
) {
logger.debug(
- 'Trigger does not match triggerName filter',
- JSON.stringify(parsedFilters.data.triggerName, null, 2)
+ 'Trigger does not match triggerSlug filter',
+ JSON.stringify(parsedFilters.data.triggerSlug, null, 2)
);
return false;
}
@@ -359,7 +361,7 @@ export class Triggers {
// Check if userId (clientUniqueUserId) filter matches
if (
parsedFilters.data.userId &&
- parsedFilters.data.userId !== data.metadata.connection.clientUniqueUserId
+ parsedFilters.data.userId !== data.metadata.connectedAccount.userId
) {
logger.debug(
'Trigger does not match userId filter',
@@ -375,33 +377,35 @@ export class Triggers {
logger.debug('🔄 Subscribing to triggers with filters: ', JSON.stringify(filters, null, 2));
await this.pusherService.subscribe((_data: Record<string, unknown>) => {
- logger.debug('Received trigger data', JSON.stringify(_data, null, 2));
+ logger.debug('Received raw trigger data', JSON.stringify(_data, null, 2));
// @TODO: This is a temporary fix to get the trigger data
// ideally we should have a type for the trigger data
const data = _data as TriggerData;
const parsedData = IncomingTriggerPayloadSchema.safeParse({
id: data.metadata.id,
- clientId: String(data.clientId),
triggerSlug: data.metadata.triggerName,
toolkitSlug: data.appName,
+ userId: data.metadata.connection.clientUniqueUserId,
payload: data.payload,
originalPayload: data.originalPayload,
metadata: {
- ...data.metadata,
id: data.metadata.id,
- connectedAccountId: data.metadata.connection?.id,
- triggerSlug: data.metadata.triggerName,
- triggerName: data.metadata.triggerName,
- triggerData: data.metadata.triggerData,
triggerConfig: data.metadata.triggerConfig,
- connection: {
- id: data.metadata?.connection?.id,
- integrationId: data.metadata?.connection?.integrationId,
- clientUniqueUserId: data.metadata?.connection?.clientUniqueUserId,
- status: data.metadata?.connection?.status,
+ triggerSlug: data.metadata.triggerName,
+ toolkitSlug: data.appName,
+ connectedAccount: {
+ id: data.metadata.connection.connectedAccountNanoId,
+ uuid: data.metadata.connection.id,
+ authConfigId: data.metadata.connection.authConfigNanoId,
+ authConfigUUID: data.metadata.connection.integrationId,
+ userId: data.metadata.connection.clientUniqueUserId,
+ status: data.metadata.connection.status,
},
},
} as IncomingTriggerPayload);
+
+ logger.debug('Parsed trigger data', JSON.stringify(parsedData.data, null, 2));
+
if (parsedData.error) {
throw new ValidationError(`Invalid trigger payload`, {
cause: parsedData.error,
diff --git a/packages/core/src/provider/OpenAIProvider.ts b/packages/core/src/provider/OpenAIProvider.ts
index 873f7376f..3508a3dba 100644
--- a/packages/core/src/provider/OpenAIProvider.ts
+++ b/packages/core/src/provider/OpenAIProvider.ts
@@ -70,7 +70,7 @@ export class OpenAIProvider extends BaseNonAgenticProvider<OpenAiToolCollection,
* @param {string} userId - The user id.
* @returns {Promise<string[]>} The results of the tool call.
*/
- async handleToolCall(
+ async handleToolCalls(
userId: string,
chatCompletion: OpenAI.ChatCompletion,
options?: ExecuteToolFnOptions,
diff --git a/packages/core/src/services/internal/InternalService.ts b/packages/core/src/services/internal/InternalService.ts
index 352f38401..e222276e3 100644
--- a/packages/core/src/services/internal/InternalService.ts
+++ b/packages/core/src/services/internal/InternalService.ts
@@ -11,7 +11,8 @@ import {
SDKRealtimeCredentialsResponseSchema,
} from './InternalService.types';
import { ValidationError } from '../../errors';
-const SDK_REALTIME_CREDENTIALS_ENDPOINT = '/v3/internal/sdk/realtime/credentials';
+import logger from '../../utils/logger';
+const SDK_REALTIME_CREDENTIALS_ENDPOINT = '/api/v3/internal/sdk/realtime/credentials';
export class InternalService {
constructor(private readonly client: ComposioClitent) {
@@ -31,8 +32,13 @@ export class InternalService {
const parsedResponse = SDKRealtimeCredentialsResponseSchema.safeParse({
pusherKey: response.pusher_key,
projectId: response.project_id,
+ pusherCluster: response.pusher_cluster,
});
+ logger.debug(
+ `[InternalService] SDK realtime credentials: ${JSON.stringify(parsedResponse, null, 2)}`
+ );
+
if (!parsedResponse.success) {
throw new ValidationError(`Failed to parse SDK realtime credentials`, {
cause: parsedResponse.error,
diff --git a/packages/core/src/services/internal/InternalService.types.ts b/packages/core/src/services/internal/InternalService.types.ts
index 7e50603b5..c89b613e3 100644
--- a/packages/core/src/services/internal/InternalService.types.ts
+++ b/packages/core/src/services/internal/InternalService.types.ts
@@ -3,11 +3,12 @@ import { z } from 'zod';
export interface ComposioSDKRealtimeCredentialsResponse {
pusher_key: string;
project_id: string;
+ pusher_cluster: string;
}
export const SDKRealtimeCredentialsResponseSchema = z.object({
+ projectId: z.string().describe('The project ID'),
pusherKey: z.string().describe('The Pusher key'),
pusherCluster: z.string().describe('The Pusher cluster'),
- projectId: z.string().describe('The project ID'),
});
export type SDKRealtimeCredentialsResponse = z.infer<typeof SDKRealtimeCredentialsResponseSchema>;
diff --git a/packages/core/src/services/pusher/Pusher.ts b/packages/core/src/services/pusher/Pusher.ts
index faaba0d20..bb62fb1bf 100644
--- a/packages/core/src/services/pusher/Pusher.ts
+++ b/packages/core/src/services/pusher/Pusher.ts
@@ -55,7 +55,9 @@ export class PusherService {
this.pusherCluster = sdkRealtimeCredentials.pusherCluster;
this.pusherChannel = `private-${this.clientId}_triggers`;
- logger.debug(`[PusherService] Creating Pusher client for client ID: ${this.clientId}`);
+ logger.debug(
+ `[PusherService] Creating Pusher client for client ID: ${this.clientId} in cluster ${this.pusherCluster}`
+ );
// create the Pusher client
try {
@@ -63,7 +65,7 @@ export class PusherService {
this.pusherClient = new Pusher(this.pusherKey, {
cluster: this.pusherCluster,
channelAuthorization: {
- endpoint: `${this.pusherBaseURL}/api/v1/client/auth/pusher_auth`,
+ endpoint: `${this.pusherBaseURL}/api/v3/internal/sdk/realtime/auth`,
headers: {
'x-api-key': this.apiKey,
},
@@ -170,9 +172,12 @@ export class PusherService {
// add subscription error handling
channel.bind('pusher:subscription_error', (data: Record<string, unknown>) => {
const error = data.error ? String(data.error) : 'Unknown subscription error';
- throw new ComposioFailedToSubscribeToPusherChannelError(`Trigger subscription error`, {
- cause: error,
- });
+ throw new ComposioFailedToSubscribeToPusherChannelError(
+ `Trigger subscription error: ${error}`,
+ {
+ cause: error,
+ }
+ );
});
// wrap the callback to handle errors
diff --git a/packages/core/src/types/triggers.types.ts b/packages/core/src/types/triggers.types.ts
index fb0f51285..4e06c2eee 100644
--- a/packages/core/src/types/triggers.types.ts
+++ b/packages/core/src/types/triggers.types.ts
@@ -12,7 +12,7 @@ export const TriggerSubscribeParamSchema = z.object({
triggerId: z.string().optional(),
connectedAccountId: z.string().optional(),
authConfigId: z.string().optional(),
- triggerName: z.string().optional(),
+ triggerSlug: z.array(z.string()).optional(),
triggerData: z.string().optional(),
userId: z.string().optional(),
});
@@ -94,23 +94,24 @@ export type TriggerInstanceManageDeleteResponse = z.infer<
export const IncomingTriggerPayloadSchema = z.object({
id: z.string().describe('The ID of the trigger'),
- clientId: z.string().describe('The ID of the client that triggered the event'),
triggerSlug: z.string().describe('The slug of the trigger that triggered the event'),
toolkitSlug: z.string().describe('The slug of the toolkit that triggered the event'),
+ userId: z.string().describe('The ID of the user that triggered the event'),
payload: z.record(z.unknown()).describe('The payload of the trigger'),
originalPayload: z.record(z.unknown()).describe('The original payload of the trigger'),
metadata: z.object({
id: z.string(),
- connectedAccountId: z.string(),
+ toolkitSlug: z.string(),
triggerSlug: z.string(),
- triggerName: z.string(),
triggerData: z.string().optional(),
triggerConfig: z.record(z.unknown()),
- connection: z.object({
+ connectedAccount: z.object({
id: z.string(),
- integrationId: z.string(),
- clientUniqueUserId: z.string(),
- status: z.enum(['enable', 'disable']),
+ uuid: z.string(),
+ authConfigId: z.string(),
+ authConfigUUID: z.string(),
+ userId: z.string(),
+ status: z.enum(['ACTIVE', 'INACTIVE']),
}),
}),
});
diff --git a/packages/core/src/utils/pusher.ts b/packages/core/src/utils/pusher.ts
index 1f2688474..2de283c25 100644
--- a/packages/core/src/utils/pusher.ts
+++ b/packages/core/src/utils/pusher.ts
@@ -16,9 +16,16 @@ type PusherClient = {
bind: (event: string, callback: (data: Record<string, unknown>) => void) => unknown;
connection: {
bind: (event: string, callback: (error: Error) => void) => void;
+ socket_id?: string;
};
};
+type AuthOptions = {
+ endpoint: string;
+ headers: Record<string, string>;
+ params?: Record<string, string>;
+};
+
type TChunkedTriggerData = {
id: string;
index: number;
@@ -33,13 +40,14 @@ export type TriggerData = {
originalPayload: Record<string, unknown>;
metadata: {
id: string;
- connectionId: string;
triggerName: string;
triggerData: string;
triggerConfig: Record<string, unknown>;
connection: {
id: string;
+ connectedAccountNanoId: string;
integrationId: string;
+ authConfigNanoId: string;
clientUniqueUserId: string;
status: string;
};
@@ -64,6 +72,29 @@ export class PusherUtils {
'x-api-key': apiKey,
},
transport: 'ajax',
+ customHandler: async (authOptions: AuthOptions) => {
+ try {
+ const response = await fetch(authOptions.endpoint, {
+ method: 'POST',
+ headers: {
+ ...authOptions.headers,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(authOptions.params),
+ });
+ const data = await response.text();
+ logger.debug('Pusher auth response:', data);
+ try {
+ return JSON.parse(data);
+ } catch (e) {
+ logger.error('Failed to parse auth response:', data);
+ throw new Error('Invalid auth response format');
+ }
+ } catch (error) {
+ logger.error('Pusher auth request failed:', error);
+ throw error;
+ }
+ },
},
});
@@ -247,7 +278,7 @@ export class PusherUtils {
if (!PusherUtils.pusherClient) {
throw new Error('Pusher client not initialized');
}
- PusherUtils.pusherClient.unsubscribe(`${clientId}_triggers`);
+ PusherUtils.pusherClient.unsubscribe(`private-${clientId}_triggers`);
logger.info('Successfully unsubscribed from triggers');
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : String(error);
diff --git a/packages/core/test/provider/openai-provider.test.ts b/packages/core/test/provider/openai-provider.test.ts
index e13f5385a..c3322b43e 100644
--- a/packages/core/test/provider/openai-provider.test.ts
+++ b/packages/core/test/provider/openai-provider.test.ts
@@ -152,7 +152,7 @@ describe('OpenAIProvider', () => {
});
});
- describe('handleToolCall', () => {
+ describe('handleToolCalls', () => {
it('should handle tool calls from chat completion', async () => {
const userId = 'test-user';
const chatCompletion = {
@@ -191,7 +191,7 @@ describe('OpenAIProvider', () => {
const executeToolCallSpy = vi.spyOn(provider, 'executeToolCall');
executeToolCallSpy.mockResolvedValue(JSON.stringify({ result: 'success' }));
- const results = await provider.handleToolCall(userId, chatCompletion);
+ const results = await provider.handleToolCalls(userId, chatCompletion);
expect(executeToolCallSpy).toHaveBeenCalledWith(
userId,
@@ -241,7 +241,7 @@ describe('OpenAIProvider', () => {
const executeToolCallSpy = vi.spyOn(provider, 'executeToolCall');
executeToolCallSpy.mockResolvedValue(JSON.stringify({ result: 'success' }));
- const results = await provider.handleToolCall(userId, chatCompletion);
+ const results = await provider.handleToolCalls(userId, chatCompletion);
expect(executeToolCallSpy).toHaveBeenCalledTimes(1);
expect(results).toEqual([JSON.stringify({ result: 'success' })]);
diff --git a/packages/providers/anthropic/README.md b/packages/providers/anthropic/README.md
index a74149ae8..697cdec1c 100644
--- a/packages/providers/anthropic/README.md
+++ b/packages/providers/anthropic/README.md
@@ -1,12 +1,14 @@
# @composio/anthropic
-Agentic Provider for Anthropic in Composio SDK.
+Non-Agentic Provider for Anthropic in Composio SDK.
## Features
-- **Full Modifier Support**: Support for both schema and execution modifiers
-- **Tool Execution**: Execute tools with proper parameter handling
+- **Tool Integration**: Seamless integration with Anthropic's tool calling capabilities
- **Type Safety**: Full TypeScript support with proper type definitions
+- **Tool Execution**: Execute tools with proper parameter handling and response formatting
+- **Caching Support**: Optional tool caching for improved performance
+- **Modifier Support**: Support for execution modifiers to transform tool inputs and outputs
## Installation
@@ -27,7 +29,8 @@ import { AnthropicProvider } from '@composio/anthropic';
// Initialize Composio with Anthropic provider
const composio = new Composio({
apiKey: 'your-composio-api-key',
- provider: new AnthropicProvider(),
+ // Initialize with optional caching
+ provider: new AnthropicProvider({ cacheTools: true }),
});
// Get available tools
@@ -56,24 +59,97 @@ const tools = await composio.tools.get('user123', {
toolkits: ['gmail'],
});
-// Use tools with Anthropic
-// Add your usage example here
+// Handle tool execution with modifiers
+const modifiers = {
+ beforeExecute: params => {
+ // Transform tool parameters before execution
+ return params;
+ },
+ afterExecute: response => {
+ // Transform tool response after execution
+ return response;
+ },
+};
+
+// Execute a tool with options
+const result = await provider.executeTool(
+ 'tool-name',
+ {
+ userId: 'user123',
+ arguments: { input: 'value' },
+ connectedAccountId: 'account123',
+ customAuthParams: {
+ parameters: [{ name: 'token', value: 'abc123', in: 'header' }],
+ },
+ },
+ modifiers
+);
```
## API Reference
### AnthropicProvider Class
-The `AnthropicProvider` class extends `BaseAgenticProvider` and provides anthropic-specific functionality.
+The `AnthropicProvider` class extends `BaseNonAgenticProvider` and provides Anthropic-specific functionality.
+
+#### Constructor
+
+```typescript
+new AnthropicProvider(options?: { cacheTools?: boolean })
+```
+
+- `options.cacheTools`: Optional boolean to enable tool caching (default: false)
#### Methods
-##### `wrapTool(tool: Tool, executeTool: ExecuteToolFn): AnthropicTool`
+##### `wrapTool(tool: Tool): AnthropicTool`
+
+Wraps a Composio tool in the Anthropic format.
+
+```typescript
+const tool = provider.wrapTool(composioTool);
+```
+
+##### `wrapTools(tools: Tool[]): AnthropicToolCollection`
+
+Wraps multiple Composio tools in the Anthropic format.
+
+```typescript
+const tools = provider.wrapTools(composioTools);
+```
+
+##### `executeToolCall(userId: string, toolUse: AnthropicToolUseBlock, options?: ExecuteToolFnOptions, modifiers?: ExecuteToolModifiers): Promise<string>`
+
+Executes a tool call from Anthropic and returns the result as a string.
+
+```typescript
+const result = await provider.executeToolCall(
+ 'user123',
+ {
+ type: 'tool_use',
+ id: 'tu_123',
+ name: 'tool-name',
+ input: { param: 'value' },
+ },
+ {
+ connectedAccountId: 'account123',
+ customAuthParams: {
+ /* ... */
+ },
+ },
+ {
+ beforeExecute: params => params,
+ afterExecute: response => response,
+ }
+);
+```
+
+##### `handleToolCalls(userId: string, message: Message, options?: ExecuteToolFnOptions, modifiers?: ExecuteToolModifiers): Promise<string[]>`
-Wraps a tool in the anthropic format.
+Handles tool calls from an Anthropic message response.
```typescript
-const tool = provider.wrapTool(composioTool, executeTool);
+const results = await provider.handleToolCalls('user123', message, options, modifiers);
```
## Contributing
diff --git a/packages/providers/google/README.md b/packages/providers/google/README.md
index d6e7c2fa0..872be7521 100644
--- a/packages/providers/google/README.md
+++ b/packages/providers/google/README.md
@@ -6,8 +6,9 @@ Google GenAI Provider for Composio SDK.
- **Google GenAI Integration**: Seamless integration with Google's Generative AI models (Gemini)
- **Function Calling Support**: Convert Composio tools to Google GenAI function declarations
-- **Multiple Authentication Methods**: Support for both API key and Vertex AI authentication
- **Type Safety**: Full TypeScript support with proper type definitions
+- **Execution Modifiers**: Support for transforming tool inputs and outputs
+- **Flexible Authentication**: Support for custom authentication parameters
## Installation
@@ -24,12 +25,10 @@ pnpm add @composio/google @google/genai
```typescript
import { Composio } from '@composio/core';
import { GoogleProvider } from '@composio/google';
-import { GoogleGenAI } from '@google/genai';
+import { GoogleGenerativeAI } from '@google/genai';
// Initialize Google GenAI
-const ai = new GoogleGenAI({
- apiKey: process.env.GEMINI_API_KEY,
-});
+const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
// Initialize Composio with Google provider
const composio = new Composio({
@@ -38,7 +37,10 @@ const composio = new Composio({
});
// Get available tools
-const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER');
+const tools = await composio.tools.get('user123', {
+ toolkits: ['gmail', 'calendar'],
+ limit: 10,
+});
```
## Usage Examples
@@ -48,12 +50,10 @@ const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER');
```typescript
import { Composio } from '@composio/core';
import { GoogleProvider } from '@composio/google';
-import { GoogleGenAI } from '@google/genai';
+import { GoogleGenerativeAI } from '@google/genai';
// Initialize Google GenAI
-const ai = new GoogleGenAI({
- apiKey: process.env.GEMINI_API_KEY,
-});
+const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
// Initialize Composio
const composio = new Composio({
@@ -61,29 +61,52 @@ const composio = new Composio({
provider: new GoogleProvider(),
});
-// Get tools
-const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER');
-
-// Define task
-const task = "Fetch the details of the user 'haxzie'";
-
-// Generate content with function calling
-const response = await ai.models.generateContent({
- model: 'gemini-2.0-flash-001',
- contents: task,
- config: {
- tools: [{ functionDeclarations: tools }],
+// Handle tool execution with modifiers
+const modifiers = {
+ beforeExecute: params => {
+ // Transform tool parameters before execution
+ return params;
},
-});
-
-// Handle function calls
-if (response.functionCalls) {
- const result = await composio.tools.execute(response.functionCalls[0].name, {
- userId: 'default',
- arguments: response.functionCalls[0].args,
- });
- console.log(result.data);
-}
+ afterExecute: response => {
+ // Transform tool response after execution
+ return response;
+ },
+};
+
+// Execute a tool with options
+const result = await provider.executeTool(
+ 'tool-name',
+ {
+ userId: 'user123',
+ arguments: { input: 'value' },
+ connectedAccountId: 'account123',
+ customAuthParams: {
+ parameters: [{ name: 'token', value: 'abc123', in: 'header' }],
+ },
+ },
+ modifiers
+);
+
+// Handle function calls from Google GenAI
+const functionCall = {
+ name: 'tool-name',
+ args: { param: 'value' },
+};
+
+const toolResult = await provider.executeToolCall(
+ 'user123',
+ functionCall,
+ {
+ connectedAccountId: 'account123',
+ customAuthParams: {
+ /* ... */
+ },
+ },
+ {
+ beforeExecute: params => params,
+ afterExecute: response => response,
+ }
+);
```
## API Reference
@@ -94,7 +117,7 @@ The `GoogleProvider` class extends `BaseNonAgenticProvider` and provides Google
#### Methods
-##### `wrapTool(tool: Tool): GoogleGenAIFunctionDeclaration`
+##### `wrapTool(tool: Tool): GoogleTool`
Wraps a Composio tool in the Google GenAI function declaration format.
@@ -104,12 +127,37 @@ const wrappedTool = provider.wrapTool(composioTool);
##### `wrapTools(tools: Tool[]): GoogleGenAIToolCollection`
-Wraps a list of Composio tools in the Google GenAI function declaration format.
+Wraps multiple Composio tools in the Google GenAI function declaration format.
```typescript
const wrappedTools = provider.wrapTools(composioTools);
```
+##### `executeToolCall(userId: string, tool: GoogleGenAIFunctionCall, options?: ExecuteToolFnOptions, modifiers?: ExecuteToolModifiers): Promise<string>`
+
+Executes a tool call from Google GenAI and returns the result as a JSON string.
+
+```typescript
+const result = await provider.executeToolCall('user123', functionCall, options, modifiers);
+```
+
+#### Types
+
+```typescript
+interface GoogleGenAIFunctionCall {
+ name: string;
+ args: Record<string, unknown>;
+}
+
+type GoogleTool = {
+ name: string;
+ description: string;
+ parameters: Schema;
+};
+
+type GoogleGenAIToolCollection = GoogleTool[];
+```
+
## Contributing
We welcome contributions! Please see our [Contributing Guide](../../CONTRIBUTING.md) for more details.
diff --git a/packages/providers/openai/test/openai.test.ts b/packages/providers/openai/test/openai.test.ts
index 36d83ae99..86783b663 100644
--- a/packages/providers/openai/test/openai.test.ts
+++ b/packages/providers/openai/test/openai.test.ts
@@ -233,7 +233,7 @@ describe('OpenAIProvider', () => {
});
});
- describe('handleToolCall', () => {
+ describe('handleToolCalls', () => {
it('should handle tool calls from chat completion', async () => {
const userId = 'test-user';
const chatCompletion = {
@@ -271,7 +271,7 @@ describe('OpenAIProvider', () => {
const executeToolCallSpy = vi.spyOn(provider, 'executeToolCall');
executeToolCallSpy.mockResolvedValue(JSON.stringify({ result: 'success' }));
- const results = await provider.handleToolCall(userId, chatCompletion);
+ const results = await provider.handleToolCalls(userId, chatCompletion);
expect(executeToolCallSpy).toHaveBeenCalledWith(
userId,
@@ -339,7 +339,7 @@ describe('OpenAIProvider', () => {
.mockResolvedValueOnce(JSON.stringify({ result: 'success-1' }))
.mockResolvedValueOnce(JSON.stringify({ result: 'success-2' }));
- const results = await provider.handleToolCall(userId, chatCompletion);
+ const results = await provider.handleToolCalls(userId, chatCompletion);
expect(executeToolCallSpy).toHaveBeenCalledTimes(2);
expect(executeToolCallSpy).toHaveBeenNthCalledWith(