@devries-cameron20 / composio-1 / commits / 6f8da6f8e
Fork 0

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

Cleanup modifiers

haxzie committed May 13, 2025 at 14:25 UTC 6f8da6f8e9e659eb5283aa09ff7c6ac5705d98f7
17 files changed +198 -416
examples/pre-processors/src/index.ts
+8 -14
@@ -8,6 +8,12 @@ const composio = new Composio({
8 apiKey: process.env.COMPOSIO_API_KEY,
9 });
10
11 +const tools = await composio.getTools(
12 + {
13 + toolkitSlug: 'HACKERNEWS',
14 + },
15 + {}
16 +);
17 // Local modifiers
18 const tool = await composio.getToolBySlug('HACKERNEWS_GET_USER', {
19 schema: (toolSlug, toolSchema) => {
@@ -26,19 +32,6 @@ composio.toolset.handleToolCall({}, '', {
32 return toolExecuteParams;
33 },
34 });
29 -// global modifiers, with toolslug as helper
30 -composio.useTransformToolSchema('HACKERNEWS_GET_USER', toolSchema => {
31 - toolSchema.inputParameters = {};
32 - return toolSchema;
33 -});
34 -
35 -// global modifiers
36 -composio.useTransformToolSchema((toolSlug, toolSchema) => {
37 - if (toolSlug === 'HACKERNEWS_GET_USER') {
38 - toolSchema.inputParameters = {};
39 - }
40 - return toolSchema;
41 -});
35
36 /**
37 * Agentic toolset
@@ -48,7 +41,7 @@ const vercelComposio = new Composio({
41 toolset: new VercelToolset(),
42 });
43
51 -const tools = await vercelComposio.getTools(
44 +const verceltools = await vercelComposio.getTools(
45 {
46 toolkitSlug: 'HACKERNEWS',
47 },
@@ -67,3 +60,4 @@ const tools = await vercelComposio.getTools(
60 },
61 }
62 );
63 +console.log(verceltools);
examples/vercel/src/index.ts
+42 -42
@@ -1,58 +1,58 @@
1 -import { Composio } from "@composio/core";
2 -import { generateText } from "ai";
3 -import { openai } from "@ai-sdk/openai";
4 -import { VercelToolset } from "@composio/vercel";
1 +import { Composio } from '@composio/core';
2 +import { generateText } from 'ai';
3 +import { openai } from '@ai-sdk/openai';
4 +import { VercelToolset } from '@composio/vercel';
5
6 const composio = new Composio({
7 - apiKey: process.env.COMPOSIO_API_KEY,
8 - toolset: new VercelToolset()
7 + apiKey: process.env.COMPOSIO_API_KEY,
8 + toolset: new VercelToolset(),
9 });
10
11 -const hackerNewsTool = await composio.toolset.getToolBySlug("HACKERNEWS_GET_FRONTPAGE");
11 +const hackerNewsTool = await composio.toolset.getToolBySlug('HACKERNEWS_GET_FRONTPAGE');
12
13 const MessageRoles = {
14 - USER: "user",
15 - ASSISTANT: "assistant",
16 - TOOL: "tool"
14 + USER: 'user',
15 + ASSISTANT: 'assistant',
16 + TOOL: 'tool',
17 } as const;
18
19 -type MessageRole = typeof MessageRoles[keyof typeof MessageRoles];
19 +type MessageRole = (typeof MessageRoles)[keyof typeof MessageRoles];
20 type Message = { role: MessageRole; content: string | any };
21
22 -const messages: Message[] = [{
22 +const messages: Message[] = [
23 + {
24 role: MessageRoles.USER,
24 - content: "Summarize the front page of HackerNews"
25 -}];
25 + content: 'Summarize the front page of HackerNews',
26 + },
27 +];
28
29 const chatCompletion = async () => {
30 + const { text, toolCalls, toolResults } = await generateText({
31 + model: openai('gpt-4o-mini'),
32 + tools: { ['HACKERNEWS_GET_FRONTPAGE']: hackerNewsTool },
33 + messages,
34 + });
35 +
36 + if (toolResults.length > 0 && toolCalls.length > 0) {
37 + toolCalls.forEach(async toolCall => {
38 + console.log(`Executing tool call: ${toolCall.toolName}`);
39 + });
40 +
41 + messages.push({
42 + role: MessageRoles.ASSISTANT,
43 + content: toolCalls,
44 + });
45
29 - const { text, toolCalls, toolResults } = await generateText({
30 - model: openai("gpt-4o-mini"),
31 - tools: { ["HACKERNEWS_GET_FRONTPAGE"]: hackerNewsTool },
32 - messages,
46 + messages.push({
47 + role: MessageRoles.TOOL,
48 + content: toolResults,
49 });
50
35 - if (toolResults.length > 0 && toolCalls.length > 0) {
36 - toolCalls.forEach(async (toolCall) => {
37 - console.log(`Executing tool call: ${toolCall.toolName}`);
38 - });
39 -
40 - messages.push({
41 - role: MessageRoles.ASSISTANT,
42 - content: toolCalls,
43 - })
44 -
45 - messages.push({
46 - role: MessageRoles.TOOL,
47 - content: toolResults,
48 - })
49 -
50 -
51 - await chatCompletion();
52 - } else {
53 - messages.push({ role: MessageRoles.ASSISTANT, content: text })
54 - console.log(`Assistant: ${text}\n`)
55 - }
56 -}
57 -
58 -chatCompletion();
\ No newline at end of file
51 + await chatCompletion();
52 + } else {
53 + messages.push({ role: MessageRoles.ASSISTANT, content: text });
54 + console.log(`Assistant: ${text}\n`);
55 + }
56 +};
57 +
58 +chatCompletion();
packages/core/src/composio.ts
+41 -71
@@ -4,11 +4,11 @@ import { Toolkits } from './models/Toolkits';
4 import { Triggers } from './models/Triggers';
5 import { AuthConfigs } from './models/AuthConfigs';
6 import { ConnectedAccounts } from './models/ConnectedAccounts';
7 -import { BaseAgenticToolset, BaseNonAgenticToolset } from './toolset/BaseToolset';
7 +import { BaseComposioToolset } from './toolset/BaseToolset';
8 import { Telemetry } from './telemetry/Telemetry';
9 import { BaseTelemetryTransport } from './telemetry/TelemetryTransport';
10 import type { TelemetryMetadata } from './types/telemetry.types';
11 -import type { ModifiersParams } from './types/modifiers.types';
11 +import type { ToolsetModifierType } from './types/modifiers.types';
12 import type { ToolListParams } from './types/tool.types';
13 import { getSDKConfig } from './utils/sdk';
14 import logger from './utils/logger';
@@ -16,39 +16,24 @@ import { IS_DEVELOPMENT_OR_CI } from './utils/constants';
16 import { checkForLatestVersionFromNPM } from './utils/version';
17 import { OpenAIToolset } from './toolset/OpenAIToolset';
18 import { version } from '../package.json';
19 -import { Modifiers } from './models/Modifiers';
20 -
21 -export type ComposioConfig<
22 - TToolset extends
23 - | BaseAgenticToolset<unknown, unknown>
24 - | BaseNonAgenticToolset<unknown, unknown> = OpenAIToolset,
25 -> = {
26 - apiKey?: string;
27 - baseURL?: string;
28 - allowTracking?: boolean;
29 - allowTracing?: boolean;
30 - toolset?: TToolset;
31 - userId?: string;
32 - connectedAccountIds?: Record<string, string>;
33 - telemetryTransport?: BaseTelemetryTransport;
34 -};
19
36 -type ToolsetModifierType<
37 - T extends BaseAgenticToolset<unknown, unknown> | BaseNonAgenticToolset<unknown, unknown>,
38 -> =
39 - T extends BaseAgenticToolset<unknown, unknown>
40 - ? ModifiersParams
41 - : Pick<ModifiersParams, 'schema'>;
20 +export type ComposioConfig<TToolset extends BaseComposioToolset<unknown, unknown> = OpenAIToolset> =
21 + {
22 + apiKey?: string;
23 + baseURL?: string;
24 + allowTracking?: boolean;
25 + allowTracing?: boolean;
26 + toolset?: TToolset;
27 + userId?: string;
28 + connectedAccountIds?: Record<string, string>;
29 + telemetryTransport?: BaseTelemetryTransport;
30 + };
31
32 /**
33 * This is the core class for Composio.
34 * It is used to initialize the Composio SDK and provide a global configuration.
35 */
47 -export class Composio<
48 - TToolset extends
49 - | BaseAgenticToolset<unknown, unknown>
50 - | BaseNonAgenticToolset<unknown, unknown> = OpenAIToolset,
51 -> {
36 +export class Composio<TToolset extends BaseComposioToolset<unknown, unknown> = OpenAIToolset> {
37 private readonly DEFAULT_USER_ID = 'default';
38 /**
39 * The Composio API client.
@@ -81,22 +66,6 @@ export class Composio<
66 // connected accounts
67 connectedAccounts: ConnectedAccounts;
68 createConnectedAccount: ConnectedAccounts['createConnectedAccount'];
84 - // global modifiers
85 - modifiers: Modifiers;
86 - useBeforeToolExecute: Modifiers['useBeforeToolExecute'];
87 - useAfterToolExecute: Modifiers['useAfterToolExecute'];
88 - useTransformToolSchema: Modifiers['useTransformToolSchema'];
89 - // toolset modifiers
90 - getToolBySlug!: <T extends TToolset>(
91 - slug: string,
92 - modifiers?: ToolsetModifierType<T>
93 - ) => Promise<ReturnType<T['getToolBySlug']>>;
94 - getTools!: <T extends TToolset>(
95 - params?: ToolListParams,
96 - modifiers?: ToolsetModifierType<T>
97 - ) => Promise<ReturnType<T['getTools']>>;
98 - // getToolBySlug: TToolset['getToolBySlug'];
99 - // getTools: TToolset['getTools'];
69
70 /**
71 * @param {Object} config Configuration for the Composio SDK.
@@ -151,34 +120,10 @@ export class Composio<
120 */
121 this.toolset = (config.toolset ?? new OpenAIToolset()) as TToolset;
122 this.toolset.setComposio(this);
154 -
155 - this.getToolBySlug = (async <T extends TToolset>(
156 - slug: string,
157 - modifiers?: ToolsetModifierType<T>
158 - ) => {
159 - return this.toolset.getToolBySlug(slug, modifiers as ToolsetModifierType<TToolset>);
160 - }) as typeof this.getToolBySlug;
161 -
162 - this.getTools = (async <T extends TToolset>(
163 - params?: ToolListParams,
164 - modifiers?: ToolsetModifierType<T>
165 - ) => {
166 - return this.toolset.getTools(params, modifiers as ToolsetModifierType<TToolset>);
167 - }) as typeof this.getTools;
168 -
169 - /**
170 - * Modifiers are used to modify the tools and toolkits.
171 - * Initialize the modifiers into global scope.
172 - */
173 - this.modifiers = new Modifiers();
174 - this.useBeforeToolExecute = this.modifiers.useBeforeToolExecute;
175 - this.useAfterToolExecute = this.modifiers.useAfterToolExecute;
176 - this.useTransformToolSchema = this.modifiers.useTransformToolSchema;
177 -
123 /**
124 * Initialize all the models with composio client.
125 */
181 - this.tools = new Tools(this.client, this.modifiers);
126 + this.tools = new Tools(this.client);
127 this.toolkits = new Toolkits(this.client);
128 this.triggers = new Triggers(this.client);
129 this.authConfigs = new AuthConfigs(this.client);
@@ -221,7 +166,6 @@ export class Composio<
166 */
167 this.telemetry.instrumentTelemetry(this);
168 this.telemetry.instrumentTelemetry(this.tools);
224 - this.telemetry.instrumentTelemetry(this.modifiers);
169 this.telemetry.instrumentTelemetry(this.toolkits);
170 this.telemetry.instrumentTelemetry(this.triggers);
171 this.telemetry.instrumentTelemetry(this.authConfigs);
@@ -248,4 +192,30 @@ export class Composio<
192 }
193 return this.client;
194 }
195 +
196 + /**
197 + * Fetch all the tools from Composio.
198 + * @param {ToolListParams} params Parameters to fetch the tools.
199 + * @param {ToolsetModifierType<TToolset>} modifiers Modifiers to apply to the tools.
200 + * @returns {Promise<ReturnType<TToolset['getTools']>>} The tools from the toolset.
201 + */
202 + getTools<T extends TToolset>(
203 + params?: ToolListParams,
204 + modifiers?: ToolsetModifierType<T>
205 + ): Promise<ReturnType<T['getTools']>> {
206 + return this.toolset.getTools(params, modifiers) as Promise<ReturnType<T['getTools']>>;
207 + }
208 +
209 + /**
210 + * Fetch a tool from Composio by its slug.
211 + * @param {string} slug slug of the tool
212 + * @param {ToolsetModifierType<TToolset>} modifiers to be applied to the tool
213 + * @returns {Promise<ReturnType<TToolset['getToolBySlug']>>} The tool from the toolset.
214 + */
215 + getToolBySlug<T extends TToolset>(
216 + slug: string,
217 + modifiers?: ToolsetModifierType<T>
218 + ): Promise<ReturnType<T['getToolBySlug']>> {
219 + return this.toolset.getToolBySlug(slug, modifiers) as Promise<ReturnType<T['getToolBySlug']>>;
220 + }
221 }
packages/core/src/index.ts
+1 -2
@@ -7,11 +7,10 @@ export { BaseTelemetryTransport } from './telemetry/TelemetryTransport';
7 export { jsonSchemaToModel } from './utils/jsonSchema';
8 export { Tool, ToolListParams, ToolListParamsSchema } from './types/tool.types';
9 export { Toolset } from './types/toolset.types';
10 -
10 // Type exports
11 export type {
12 ModifiersParams,
13 TransformToolSchemaModifier,
15 - BeforeToolExecuteModifer,
14 + BeforeToolExecuteModifier,
15 AfterToolExecuteModifier,
16 } from './types/modifiers.types';
packages/core/src/models/Modifiers.ts deleted
-193
@@ -1,193 +0,0 @@
1 -/**
2 - * @fileoverview Modifiers class for Composio SDK, used to manage tool execution modifiers.
3 - *
4 - * @author Musthaq Ahamad <musthaq@composio.dev>
5 - * @date 2025-05-05
6 - * @module Modifiers
7 - */
8 -import {
9 - AfterToolExecuteModifier,
10 - BeforeToolExecuteModifer,
11 - GlobalAfterToolExecuteModifier,
12 - GlobalBeforeToolExecuteModifier,
13 - GlobalTransformToolSchemaModifier,
14 - TransformToolSchemaModifier,
15 -} from '../types/modifiers.types';
16 -import { Tool, ToolExecuteParams, ToolExecuteResponse } from '../types/tool.types';
17 -
18 -/**
19 - * Modifiers class
20 - *
21 - * This class is used to manage the modifiers for the tools in the Composio SDK.
22 - * It provides methods to add before and after execution modifiers, as well as schema transformation modifiers.
23 - */
24 -export class Modifiers {
25 - private beforeToolExecuteModifiers: Map<string, Set<BeforeToolExecuteModifer>> = new Map();
26 - private globalBeforeToolExecuteModifiers: Set<GlobalBeforeToolExecuteModifier> = new Set();
27 - private afterToolExecuteModifiers: Map<string, Set<AfterToolExecuteModifier>> = new Map();
28 - private globalAfterToolExecuteModifiers: Set<GlobalAfterToolExecuteModifier> = new Set();
29 - private transformToolSchemaModifiers: Map<string, Set<TransformToolSchemaModifier>> = new Map();
30 - private globalTransformToolSchemaModifiers: Set<GlobalTransformToolSchemaModifier> = new Set();
31 -
32 - constructor() {}
33 -
34 - /**
35 - * Function signature for modifying the tool execution parameters.
36 - * We support two ways to register modifiers:
37 - * 1. useBeforeToolExecute(globalModifier: GlobalBeforeToolExecuteModifier): void
38 - * 2. useBeforeToolExecute(toolSlug: string, modifier: BeforeToolExecuteModifer): void
39 - */
40 - useBeforeToolExecute(globalModifier: GlobalBeforeToolExecuteModifier): void;
41 - useBeforeToolExecute(toolSlug: string, modifier: BeforeToolExecuteModifer): void;
42 - /**
43 - * Method to modify the tool schema before it is executed.
44 - * We provide two methods to register modifiers:
45 - * 1. useBeforeToolExecute(modifier: GlobalBeforeToolExecuteModifier): void
46 - * 2. useBeforeToolExecute(toolSlug: string, modifier: BeforeToolExecuteModifer): void
47 - * @param {string} toolSlug slug of the tool to be modified
48 - * @param modifier function to modify the tool execution parameters
49 - */
50 - useBeforeToolExecute(
51 - arg1: string | GlobalBeforeToolExecuteModifier,
52 - modifier?: BeforeToolExecuteModifer
53 - ): void {
54 - if (typeof arg1 === 'string' && modifier) {
55 - const toolSlug = arg1;
56 - if (!this.beforeToolExecuteModifiers.has(toolSlug)) {
57 - this.beforeToolExecuteModifiers.set(toolSlug, new Set());
58 - }
59 - this.beforeToolExecuteModifiers.get(toolSlug)?.add(modifier);
60 - } else if (typeof arg1 === 'function') {
61 - const globalModifier = arg1;
62 - this.globalBeforeToolExecuteModifiers.add(globalModifier);
63 - }
64 - }
65 -
66 - /**
67 - * Method to apply the before tool execute modifiers.
68 - * @param {string} toolSlug slug of the tool to be modified
69 - * @param {ToolExecuteParams} toolExecuteParams parameters to be passed to the tool
70 - * @returns {ToolExecuteParams} modified parameters
71 - */
72 - applyBeforeToolExecute(
73 - toolSlug: string,
74 - toolExecuteParams: ToolExecuteParams
75 - ): ToolExecuteParams {
76 - // Apply global modifiers
77 - let modifiedToolExecuteParams = { ...toolExecuteParams };
78 - for (const globalModifier of this.globalBeforeToolExecuteModifiers) {
79 - modifiedToolExecuteParams = globalModifier(toolSlug, modifiedToolExecuteParams);
80 - }
81 - // Apply tool-specific modifiers
82 - const modifiers = this.beforeToolExecuteModifiers.get(toolSlug);
83 - if (modifiers) {
84 - for (const modifier of modifiers) {
85 - modifiedToolExecuteParams = modifier(modifiedToolExecuteParams);
86 - }
87 - }
88 - return modifiedToolExecuteParams;
89 - }
90 -
91 - /**
92 - * Function signature for modifying the tool execution response.
93 - */
94 - useAfterToolExecute(globalModifier: GlobalAfterToolExecuteModifier): void;
95 - useAfterToolExecute(toolSlug: string, modifier: AfterToolExecuteModifier): void;
96 -
97 - /**
98 - * Method to modify the tool schema after it is executed.
99 - * @param {string} toolSlug slug of the tool to be modified
100 - * @param modifier function to modify the tool execution response
101 - */
102 - useAfterToolExecute(
103 - arg1: string | GlobalAfterToolExecuteModifier,
104 - modifier?: AfterToolExecuteModifier
105 - ) {
106 - if (typeof arg1 === 'string' && modifier) {
107 - const toolSlug = arg1;
108 - if (!this.afterToolExecuteModifiers.has(toolSlug)) {
109 - this.afterToolExecuteModifiers.set(toolSlug, new Set());
110 - }
111 - this.afterToolExecuteModifiers.get(toolSlug)?.add(modifier);
112 - } else if (typeof arg1 === 'function') {
113 - const globalModifier = arg1;
114 - this.globalAfterToolExecuteModifiers.add(globalModifier);
115 - }
116 - }
117 -
118 - /**
119 - * Method to apply the after tool execute modifiers.
120 - * @param {string} toolSlug slug of the tool to be modified
121 - * @param {ToolExecuteResponse} toolExecuteResponse response from the tool execution
122 - * @returns {ToolExecuteResponse} modified response
123 - */
124 - applyAfterToolExecute(
125 - toolSlug: string,
126 - toolExecuteResponse: ToolExecuteResponse
127 - ): ToolExecuteResponse {
128 - // Apply global modifiers
129 - let modifiedToolExecuteResponse = { ...toolExecuteResponse };
130 - for (const globalModifier of this.globalAfterToolExecuteModifiers) {
131 - modifiedToolExecuteResponse = globalModifier(toolSlug, modifiedToolExecuteResponse);
132 - }
133 - // Apply tool-specific modifiers
134 - const modifiers = this.afterToolExecuteModifiers.get(toolSlug);
135 - if (modifiers) {
136 - for (const modifier of modifiers) {
137 - modifiedToolExecuteResponse = modifier(modifiedToolExecuteResponse);
138 - }
139 - }
140 - return modifiedToolExecuteResponse;
141 - }
142 -
143 - /**
144 - * Function signatures for modifying the tool schema.
145 - * We support two ways to register modifiers:
146 - * 1. useTransformToolSchema(globalModifier: GlobalTransformToolSchemaModifier): void
147 - * 2. useTransformToolSchema(toolSlug: string, modifier: TransformToolSchemaModifier): void
148 - */
149 - useTransformToolSchema(globalModifier: GlobalTransformToolSchemaModifier): void;
150 - useTransformToolSchema(toolSlug: string, modifier: TransformToolSchemaModifier): void;
151 - /**
152 - * Method to register modifiers for the tool schema.
153 - * @param {string} toolSlug slug of the tool to be modified
154 - * @param modifier function to modify the tool schema
155 - */
156 - useTransformToolSchema(
157 - arg1: string | GlobalTransformToolSchemaModifier,
158 - modifier?: TransformToolSchemaModifier
159 - ) {
160 - if (typeof arg1 === 'string' && modifier) {
161 - const toolSlug = arg1;
162 - if (!this.transformToolSchemaModifiers.has(toolSlug)) {
163 - this.transformToolSchemaModifiers.set(toolSlug, new Set());
164 - }
165 - this.transformToolSchemaModifiers.get(toolSlug)?.add(modifier);
166 - } else if (typeof arg1 === 'function') {
167 - const globalModifier = arg1;
168 - this.globalTransformToolSchemaModifiers.add(globalModifier);
169 - }
170 - }
171 -
172 - /**
173 - * Method to apply the transform tool schema modifiers.
174 - * @param toolSlug slug of the tool to be modified
175 - * @param toolSchema schema of the tool to be modified
176 - * @returns {Tool}
177 - */
178 - applyTransformToolSchema(toolSlug: string, toolSchema: Tool): Tool {
179 - // Apply global modifiers
180 - let modifiedToolSchema = { ...toolSchema };
181 - for (const globalModifier of this.globalTransformToolSchemaModifiers) {
182 - modifiedToolSchema = globalModifier(toolSlug, modifiedToolSchema);
183 - }
184 - // Apply tool-specific modifiers
185 - const modifiers = this.transformToolSchemaModifiers.get(toolSlug);
186 - if (modifiers) {
187 - for (const modifier of modifiers) {
188 - modifiedToolSchema = modifier(modifiedToolSchema);
189 - }
190 - }
191 - return modifiedToolSchema;
192 - }
193 -}
packages/core/src/models/Tools.ts
+31 -47
@@ -6,6 +6,7 @@ import {
6 ToolExecuteResponse,
7 ToolList,
8 ToolSchema,
9 + ToolExecuteResponseSchema,
10 } from '../types/tool.types';
11 import {
12 ToolGetInputParams,
@@ -16,14 +17,11 @@ import {
17 ToolRetrieveEnumResponse,
18 ToolRetrieveResponse,
19 ToolListResponse as ComposioToolListResponse,
20 + ToolExecuteResponse as ComposioToolExecuteResponse,
21 } from '@composio/client/resources/tools';
20 -import { Modifiers } from './Modifiers';
22 import { CustomTools } from './CustomTools';
23 import { CustomToolOptions } from '../types/customTool.types';
23 -import {
24 - ExecuteToolModifiersParams,
25 - GlobalTransformToolSchemaModifier,
26 -} from '../types/modifiers.types';
24 +import { ExecuteToolModifiersParams, TransformToolSchemaModifier } from '../types/modifiers.types';
25
26 /**
27 * This class is used to manage tools in the Composio SDK.
@@ -31,12 +29,10 @@ import {
29 */
30 export class Tools {
31 private client: ComposioClient;
34 - private modifiers: Modifiers;
35 - private customTools: CustomTools;
32 + customTools: CustomTools;
33
37 - constructor(client: ComposioClient, modifiers: Modifiers) {
34 + constructor(client: ComposioClient) {
35 this.client = client;
39 - this.modifiers = modifiers || new Modifiers();
36 this.customTools = new CustomTools(client);
37 }
38
@@ -50,6 +46,16 @@ export class Tools {
46 });
47 }
48
49 + private transformToolExecuteResponse(response: ComposioToolExecuteResponse): ToolExecuteResponse {
50 + return ToolExecuteResponseSchema.parse({
51 + data: response.data,
52 + error: response.error,
53 + successful: response.successful,
54 + logId: response.log_id,
55 + sessionInfo: response.session_info,
56 + });
57 + }
58 +
59 /**
60 * Lists all tools available in the Composio SDK as well as custom tools.
61 * This method fetches the tools from the Composio API and wraps them using the toolset.
@@ -57,7 +63,7 @@ export class Tools {
63 */
64 async getTools(
65 query: ToolListParams = {},
60 - modifier?: GlobalTransformToolSchemaModifier
66 + modifier?: TransformToolSchemaModifier
67 ): Promise<ToolList> {
68 const queryParams = ToolListParamsSchema.safeParse(query);
69 if (queryParams.error) {
@@ -79,18 +85,7 @@ export class Tools {
85 toolSlugs: queryParams.data.toolSlugs,
86 });
87
82 - const composioToolList = [
83 - ...tools.items.map(tool => this.transformToolCases(tool)),
84 - ...customTools,
85 - ];
86 -
87 - let modifiedTools = composioToolList.map(tool => {
88 - return this.modifiers.applyTransformToolSchema(tool.slug, {
89 - ...tool,
90 - inputParameters: tool.inputParameters,
91 - outputParameters: tool.outputParameters,
92 - });
93 - });
88 + let modifiedTools = [...tools.items.map(tool => this.transformToolCases(tool)), ...customTools];
89
90 // apply local modifiers if they are provided
91 if (modifier) {
@@ -111,7 +106,7 @@ export class Tools {
106 * @param slug The ID of the tool to be retrieved
107 * @returns {Promise<Tool>} The tool
108 */
114 - async getToolBySlug(slug: string, modifier?: GlobalTransformToolSchemaModifier): Promise<Tool> {
109 + async getToolBySlug(slug: string, modifier?: TransformToolSchemaModifier): Promise<Tool> {
110 // check if the tool is a custom tool
111 const customTool = await this.customTools.getCustomToolBySlug(slug);
112 if (customTool) {
@@ -123,18 +118,16 @@ export class Tools {
118 throw new Error(`Tool with slug ${slug} not found`);
119 }
120 // change the case of the tool to camel case
126 - const casedTool = this.transformToolCases(tool);
127 - // apply the global modifiers
128 - let modifiedTool = this.modifiers.applyTransformToolSchema(slug, casedTool);
121 + let modifiedToool = this.transformToolCases(tool);
122 // apply local modifiers if they are provided
123 if (modifier) {
124 if (typeof modifier === 'function') {
132 - modifiedTool = modifier(slug, modifiedTool);
125 + modifiedToool = modifier(slug, modifiedToool);
126 } else {
127 throw new Error('Invalid schema modifier. Not a function.');
128 }
129 }
137 - return modifiedTool;
130 + return modifiedToool;
131 }
132
133 /**
@@ -151,35 +144,26 @@ export class Tools {
144 body: ToolExecuteParams,
145 modifiers?: ExecuteToolModifiersParams
146 ): Promise<ToolExecuteResponse> {
154 - // before tool execute modifier, apply all the global modifiers
155 - let modifiedBody = this.modifiers.applyBeforeToolExecute(slug, body);
156 -
147 // apply local modifiers if they are provided
148 if (modifiers && modifiers.beforeToolExecute) {
149 if (typeof modifiers.beforeToolExecute === 'function') {
160 - modifiedBody = modifiers.beforeToolExecute(slug, modifiedBody);
150 + body = modifiers.beforeToolExecute(slug, body);
151 } else {
152 throw new Error('Invalid beforeToolExecute modifier. Not a function.');
153 }
154 }
155
156 let result = await this.client.tools.execute(slug, {
167 - allow_tracing: modifiedBody.allowTracing,
168 - connected_account_id: modifiedBody.connectedAccountId,
169 - custom_auth_params: modifiedBody.customAuthParams,
170 - arguments: modifiedBody.arguments,
171 - entity_id: modifiedBody.userId,
172 - version: modifiedBody.version,
173 - text: modifiedBody.text,
174 - });
175 - // apply gloafter tool execute modifier
176 - result = this.modifiers.applyAfterToolExecute(slug, {
177 - data: result.data,
178 - error: result.error,
179 - successful: result.successful,
180 - logId: result.log_id,
181 - sessionInfo: result.session_info,
157 + allow_tracing: body.allowTracing,
158 + connected_account_id: body.connectedAccountId,
159 + custom_auth_params: body.customAuthParams,
160 + arguments: body.arguments,
161 + entity_id: body.userId,
162 + version: body.version,
163 + text: body.text,
164 });
165 + // apply transformations to the response
166 + result = this.transformToolExecuteResponse(result);
167
168 // apply local modifiers if they are provided
169 if (modifiers && modifiers.afterToolExecute) {
packages/core/src/toolset/BaseToolset.ts
+2 -2
@@ -25,7 +25,7 @@ export abstract class BaseNonAgenticToolset<TToolCollection, TTool>
25
26 abstract getToolBySlug(slug: string, modifiers?: Pick<ModifiersParams, 'schema'>): Promise<TTool>;
27
28 - abstract _wrapTool(tool: Tool): TTool;
28 + abstract wrapTool(tool: Tool): TTool;
29
30 protected getComposio(): Composio<BaseComposioToolset<TToolCollection, TTool>> {
31 if (!this.composio) {
@@ -56,7 +56,7 @@ export abstract class BaseAgenticToolset<TToolCollection, TTool>
56
57 abstract getToolBySlug(slug: string, modifiers?: ModifiersParams): Promise<TTool>;
58
59 - abstract _wrapTool(tool: Tool): TTool;
59 + abstract wrapTool(tool: Tool): TTool;
60
61 protected getComposio(): Composio<BaseComposioToolset<TToolCollection, TTool>> {
62 if (!this.composio) {
packages/core/src/toolset/ComposioToolset.ts
+3 -3
@@ -19,13 +19,13 @@ export class ComposioToolset extends BaseNonAgenticToolset<Array<CustomTool>, Cu
19 super();
20 }
21
22 - _wrapTool = (tool: Tool): CustomTool => {
22 + wrapTool = (tool: Tool): CustomTool => {
23 return tool as CustomTool;
24 };
25
26 async getTools(params?: ToolListParams): Promise<Array<CustomTool>> {
27 const tools = await this.getComposio().tools.getTools(params);
28 - return tools?.map(tool => this._wrapTool(tool as Tool)) ?? [];
28 + return tools?.map(tool => this.wrapTool(tool as Tool)) ?? [];
29 }
30
31 async getToolBySlug(
@@ -33,7 +33,7 @@ export class ComposioToolset extends BaseNonAgenticToolset<Array<CustomTool>, Cu
33 modifiers?: Pick<ModifiersParams, 'schema'>
34 ): Promise<CustomTool> {
35 const tool = await this.getComposio().tools.getToolBySlug(slug, modifiers?.schema);
36 - return this._wrapTool(tool as Tool);
36 + return this.wrapTool(tool as Tool);
37 }
38
39 async test() {}
packages/core/src/toolset/OpenAIToolset.ts
+10 -9
@@ -12,7 +12,11 @@ import { Stream } from 'openai/streaming';
12 import { BaseNonAgenticToolset } from './BaseToolset';
13 import { Tool, ToolListParams } from '../types/tool.types';
14 import logger from '../utils/logger';
15 -import { ExecuteToolModifiersParams, ModifiersParams } from '../types/modifiers.types';
15 +import {
16 + ExecuteToolModifiersParams,
17 + ModifiersParams,
18 + SchemaModifiersParams,
19 +} from '../types/modifiers.types';
20
21 export type OpenAiTool = OpenAI.ChatCompletionTool;
22 export type OpenAiToolCollection = Array<OpenAiTool>;
@@ -23,7 +27,7 @@ export class OpenAIToolset extends BaseNonAgenticToolset<OpenAiToolCollection, O
27 * @param tool - The tool to wrap.
28 * @returns The wrapped tool.
29 */
26 - override _wrapTool = (tool: Tool): OpenAiTool => {
30 + override wrapTool = (tool: Tool): OpenAiTool => {
31 const formattedSchema: OpenAI.FunctionDefinition = {
32 name: tool.slug,
33 description: tool.description,
@@ -43,18 +47,15 @@ export class OpenAIToolset extends BaseNonAgenticToolset<OpenAiToolCollection, O
47 */
48 async getTools(
49 params?: ToolListParams,
46 - modifiers?: Pick<ModifiersParams, 'schema'>
50 + modifiers?: SchemaModifiersParams
51 ): Promise<OpenAiToolCollection> {
52 const tools = await this.getComposio()?.tools.getTools(params, modifiers?.schema);
49 - return tools?.map(tool => this._wrapTool(tool as Tool)) ?? [];
53 + return tools?.map(tool => this.wrapTool(tool as Tool)) ?? [];
54 }
55
52 - async getToolBySlug(
53 - slug: string,
54 - modifiers?: Pick<ModifiersParams, 'schema'>
55 - ): Promise<OpenAiTool> {
56 + async getToolBySlug(slug: string, modifiers?: SchemaModifiersParams): Promise<OpenAiTool> {
57 const tool = await this.getComposio().tools.getToolBySlug(slug, modifiers?.schema);
57 - return this._wrapTool(tool);
58 + return this.wrapTool(tool);
59 }
60
61 /**
packages/core/src/types/modifiers.types.ts
+39 -16
@@ -1,33 +1,56 @@
1 +import { BaseAgenticToolset, BaseComposioToolset } from '../toolset/BaseToolset';
2 import { ToolExecuteParams, ToolExecuteResponse, Tool } from './tool.types';
3
3 -export type BeforeToolExecuteModifer = (toolExecuteParams: ToolExecuteParams) => ToolExecuteParams;
4 -export type GlobalBeforeToolExecuteModifier = (
4 +/**
5 + * Modifier for altering the tool execute params
6 + * Called before the tool execute call
7 + */
8 +export type BeforeToolExecuteModifier = (
9 toolSlug: string,
10 toolExecuteParams: ToolExecuteParams
11 ) => ToolExecuteParams;
12 +
13 +/**
14 + * Modifier for altering the tool execute response
15 + * Called after the tool execute call
16 + */
17 export type AfterToolExecuteModifier = (
9 - toolExecuteResponse: ToolExecuteResponse
10 -) => ToolExecuteResponse;
11 -export type GlobalAfterToolExecuteModifier = (
18 toolSlug: string,
19 toolExecuteResponse: ToolExecuteResponse
20 ) => ToolExecuteResponse;
15 -export type TransformToolSchemaModifier = (toolSchemModifier: Tool) => Tool;
16 -export type GlobalTransformToolSchemaModifier = (toolSlug: string, toolSchema: Tool) => Tool;
21
22 +/**
23 + * Modifier for altering the tool schema
24 + * Called after the tool schema is retrieved
25 + */
26 +export type TransformToolSchemaModifier = (toolSlug: string, toolSchema: Tool) => Tool;
27 +
28 +/**
29 + * Modifiers for the toolset
30 + * This is used by Agentic toolsets
31 + */
32 export type ModifiersParams = {
19 - beforeToolExecute?: GlobalBeforeToolExecuteModifier;
20 - afterToolExecute?: GlobalAfterToolExecuteModifier;
21 - schema?: GlobalTransformToolSchemaModifier;
33 + beforeToolExecute?: BeforeToolExecuteModifier;
34 + afterToolExecute?: AfterToolExecuteModifier;
35 + schema?: TransformToolSchemaModifier;
36 };
37
24 -export type ExecuteToolModifiersParams = {
25 - beforeToolExecute?: GlobalBeforeToolExecuteModifier;
26 - afterToolExecute?: GlobalAfterToolExecuteModifier;
38 +/**
39 + * Modifiers for the tool schema
40 + * This is used by Non-Agentic toolsets
41 + */
42 +export type SchemaModifiersParams = {
43 + schema?: TransformToolSchemaModifier;
44 };
45
29 -export type SingleToolModifiersParams = {
30 - beforeToolExecute?: BeforeToolExecuteModifer;
46 +/**
47 + * Modifiers for the tool execution
48 + * This is used by execute call and handleToolCall of Non-Agentic toolsets
49 + */
50 +export type ExecuteToolModifiersParams = {
51 + beforeToolExecute?: BeforeToolExecuteModifier;
52 afterToolExecute?: AfterToolExecuteModifier;
32 - schema?: TransformToolSchemaModifier;
53 };
54 +
55 +export type ToolsetModifierType<T extends BaseComposioToolset<unknown, unknown>> =
56 + T extends BaseAgenticToolset<unknown, unknown> ? ModifiersParams : SchemaModifiersParams;
packages/core/src/types/toolset.types.ts
+3 -2
@@ -1,3 +1,4 @@
1 +import { Composio } from '../composio';
2 import { Tool, ToolListParams } from './tool.types';
3
4 /**
@@ -5,8 +6,8 @@ import { Tool, ToolListParams } from './tool.types';
6 * This class is used to create a base toolset by implementing this class.
7 * This class also extends InstrumentedInstance, so that the telemetry can be instrumented for the toolset.
8 */
8 -export interface Toolset<TTool = Tool, TToolCollection = TTool[]> {
9 - _wrapTool: (tool: Tool) => TTool;
9 +export interface Toolset<TTool, TToolCollection> {
10 + wrapTool: (tool: Tool) => TTool;
11 getTools: (params?: ToolListParams) => Promise<TToolCollection>;
12 }
13
packages/toolsets/cloudflare/src/index.ts
+6 -6
@@ -13,7 +13,7 @@ import { AiTextGenerationToolInput } from '@cloudflare/workers-types';
13 import { BaseNonAgenticToolset, Tool, ToolListParams } from '@composio/core';
14 import {
15 ExecuteToolModifiersParams,
16 - ModifiersParams,
16 + SchemaModifiersParams,
17 } from 'packages/core/src/types/modifiers.types';
18
19 type AiToolCollection = Record<string, AiTextGenerationToolInput>;
@@ -28,7 +28,7 @@ export class CloudflareToolset extends BaseNonAgenticToolset<
28 * @param tool - The tool to wrap.
29 * @returns The wrapped tool.
30 */
31 - _wrapTool(tool: Tool): AiTextGenerationToolInput {
31 + wrapTool(tool: Tool): AiTextGenerationToolInput {
32 const formattedSchema: AiTextGenerationToolInput['function'] = {
33 name: tool.slug!,
34 description: tool.description!,
@@ -57,7 +57,7 @@ export class CloudflareToolset extends BaseNonAgenticToolset<
57 */
58 override async getTools(
59 query?: ToolListParams,
60 - modifiers?: Pick<ModifiersParams, 'schema'>
60 + modifiers?: SchemaModifiersParams
61 ): Promise<AiToolCollection> {
62 if (!this.getComposio()) {
63 throw new Error('Client not set');
@@ -67,7 +67,7 @@ export class CloudflareToolset extends BaseNonAgenticToolset<
67 return tools.reduce(
68 (tools, tool) => ({
69 ...tools,
70 - [tool.slug]: this._wrapTool(tool),
70 + [tool.slug]: this.wrapTool(tool),
71 }),
72 {}
73 );
@@ -75,13 +75,13 @@ export class CloudflareToolset extends BaseNonAgenticToolset<
75
76 override async getToolBySlug(
77 slug: string,
78 - modifiers?: Pick<ModifiersParams, 'schema'>
78 + modifiers?: SchemaModifiersParams
79 ): Promise<AiTextGenerationToolInput> {
80 if (!this.getComposio()) {
81 throw new Error('Client not set');
82 }
83 const tool = await this.getComposio().tools.getToolBySlug(slug, modifiers?.schema);
84 - return this._wrapTool(tool);
84 + return this.wrapTool(tool);
85 }
86
87 /**
packages/toolsets/cloudflare/tsconfig.json
+2 -1
@@ -9,7 +9,8 @@
9 "strict": true,
10 "esModuleInterop": true,
11 "moduleResolution": "node",
12 - "skipLibCheck": true
12 + "skipLibCheck": true,
13 + "resolveJsonModule": true
14 },
15 "include": ["src"]
16 }
packages/toolsets/langchain/src/index.ts
+3 -3
@@ -24,7 +24,7 @@ export class LangchainToolset extends BaseAgenticToolset<
24 * @param tool - The tool to wrap.
25 * @returns The wrapped tool.
26 */
27 - _wrapTool(tool: Tool, modifiers?: ModifiersParams): DynamicStructuredTool {
27 + wrapTool(tool: Tool, modifiers?: ModifiersParams): DynamicStructuredTool {
28 const toolName = tool.slug;
29 const description = tool.description;
30 const appName = tool.toolkit?.name?.toLowerCase();
@@ -71,7 +71,7 @@ export class LangchainToolset extends BaseAgenticToolset<
71 modifiers?: ModifiersParams
72 ): Promise<LangChainToolCollection> {
73 const tools = await this.getComposio()?.tools.getTools(params, modifiers?.schema);
74 - return tools?.map(tool => this._wrapTool(tool, modifiers)) ?? [];
74 + return tools?.map(tool => this.wrapTool(tool, modifiers)) ?? [];
75 }
76
77 override async getToolBySlug(
@@ -79,6 +79,6 @@ export class LangchainToolset extends BaseAgenticToolset<
79 modifiers?: ModifiersParams
80 ): Promise<DynamicStructuredTool> {
81 const tool = await this.getComposio()?.tools.getToolBySlug(slug, modifiers?.schema);
82 - return this._wrapTool(tool as Tool, modifiers);
82 + return this.wrapTool(tool as Tool, modifiers);
83 }
84 }
packages/toolsets/langchain/tsconfig.json
+2 -1
@@ -9,7 +9,8 @@
9 "strict": true,
10 "esModuleInterop": true,
11 "moduleResolution": "node",
12 - "skipLibCheck": true
12 + "skipLibCheck": true,
13 + "resolveJsonModule": true
14 },
15 "include": ["src"]
16 }
packages/toolsets/vercel/src/index.ts
+3 -3
@@ -39,7 +39,7 @@ export class VercelToolset extends BaseAgenticToolset<VercelToolCollection, Verc
39 return tools.reduce(
40 (tools, tool) => ({
41 ...tools,
42 - [tool.slug]: this._wrapTool(tool as ComposioTool, modifiers),
42 + [tool.slug]: this.wrapTool(tool as ComposioTool, modifiers),
43 }),
44 {}
45 );
@@ -47,7 +47,7 @@ export class VercelToolset extends BaseAgenticToolset<VercelToolCollection, Verc
47
48 override async getToolBySlug(slug: string, modifiers?: ModifiersParams): Promise<VercelTool> {
49 const tool = await this.getComposio().tools.getToolBySlug(slug, modifiers?.schema);
50 - return this._wrapTool(tool as ComposioTool, modifiers);
50 + return this.wrapTool(tool as ComposioTool, modifiers);
51 }
52
53 /**
@@ -82,7 +82,7 @@ export class VercelToolset extends BaseAgenticToolset<VercelToolCollection, Verc
82 return JSON.stringify(results);
83 }
84
85 - _wrapTool(composioTool: ComposioTool, modifiers?: ExecuteToolModifiersParams): VercelTool {
85 + wrapTool(composioTool: ComposioTool, modifiers?: ExecuteToolModifiersParams): VercelTool {
86 return tool({
87 description: composioTool.description,
88 parameters: jsonSchema(composioTool.inputParameters ?? {}),
packages/toolsets/vercel/tsconfig.json
+2 -1
@@ -9,7 +9,8 @@
9 "strict": true,
10 "esModuleInterop": true,
11 "moduleResolution": "node",
12 - "skipLibCheck": true
12 + "skipLibCheck": true,
13 + "resolveJsonModule": true
14 },
15 "include": ["src"]
16 }