@devries-cameron20 / composio Mirror · read-only
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.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 04:45 UTC

next
md 712 lines 20.1 KB
Rendered Raw
1 # Modifiers
2
3 Composio SDK provides powerful middleware capabilities through modifiers that allow you to customize and extend the behavior of tools. This guide explains how to use modifiers to transform tool schemas, modify inputs before execution, and transform outputs after execution.
4
5 > **Important:** Not all modifiers are supported by all provider types. Schema modifiers work with all providers, but execution modifiers (beforeExecute and afterExecute) are only supported by agentic providers. See the [Provider-Specific Modifier Support](#provider-specific-modifier-support) section for details.
6
7 ## What are Modifiers?
8
9 Modifiers are functions that intercept and modify the normal flow of tool operations. Composio supports three types of modifiers:
10
11 1. **Schema Modifiers**: Transform a tool's schema before it's wrapped for the provider (supported by all providers)
12 2. **Before Execution Modifiers**: Modify inputs before a tool is executed (supported by agentic providers only)
13 3. **After Execution Modifiers**: Transform outputs after a tool has executed (supported by agentic providers only)
14
15 ### Schema Modifiers
16
17 Schema modifiers allow you to transform a tool's schema before it's wrapped for the provider. This is useful for customizing tool descriptions, parameter definitions, or adding metadata.
18
19 ```typescript
20 // Modify tool schema when getting tools
21 const tools = await composio.tools.get(
22 'default',
23 {
24 toolkits: ['github'],
25 },
26 {
27 modifySchema: ({ toolSlug, toolkitSlug, schema }) => {
28 // Add a prefix to all tool descriptions
29 if (tool.description) {
30 tool.description = `[Enhanced] ${tool.description}`;
31 }
32
33 // Modify parameters for a specific tool
34 if (toolSlug === 'GITHUB_GET_REPO') {
35 if (tool.inputParameters?.properties?.owner) {
36 // Add more detailed description
37 tool.inputParameters.properties.owner.description =
38 'GitHub organization or user name (e.g., "composio")';
39 }
40 }
41
42 return tool;
43 },
44 }
45 );
46 ```
47
48 ### Before Execution Modifiers
49
50 Before execution modifiers allow you to modify the input parameters before a tool is executed. This is useful for parameter validation, transformation, or adding default values.
51
52 ```typescript
53 // Modify parameters before execution
54 const result = await composio.tools.execute(
55 'GITHUB_GET_REPO',
56 {
57 userId: 'default',
58 arguments: {
59 owner: 'composio',
60 repo: 'sdk',
61 },
62 },
63 {
64 beforeExecute: ({ toolSlug, toolkitSlug, params }) => {
65 // Convert owner names to lowercase
66 if (params.arguments.owner) {
67 params.arguments.owner = params.arguments.owner.toLowerCase();
68 }
69
70 // Add a default branch parameter
71 if (toolSlug === 'GITHUB_GET_REPO' && !params.arguments.branch) {
72 params.arguments.branch = 'main';
73 }
74
75 // Add tracing for debugging
76 console.log(`Executing ${toolSlug} from ${toolkitSlug} toolkit`);
77
78 return params;
79 },
80 }
81 );
82 ```
83
84 ### After Execution Modifiers
85
86 After execution modifiers allow you to transform the output after a tool has executed. This is useful for data formatting, filtering, or enrichment.
87
88 ```typescript
89 // Modify results after execution
90 const result = await composio.tools.execute(
91 'GITHUB_GET_REPO',
92 {
93 userId: 'default',
94 arguments: {
95 owner: 'composio',
96 repo: 'sdk',
97 },
98 },
99 {
100 afterExecute: ({ toolSlug, toolkitSlug, result }) => {
101 // Only when execution was successful
102 if (result.successful) {
103 // Filter out sensitive data
104 if (result.data.token) {
105 delete result.data.token;
106 }
107
108 // Add a timestamp
109 result.data.fetchedAt = new Date().toISOString();
110
111 // Transform data formats
112 if (result.data.created_at) {
113 result.data.createdAt = new Date(result.data.created_at).toLocaleString();
114 delete result.data.created_at;
115 }
116 }
117
118 return result;
119 },
120 }
121 );
122 ```
123
124 ### Using Multiple Modifiers
125
126 You can use multiple modifiers together, but remember that execution modifiers (beforeExecute and afterExecute) only work with agentic providers:
127
128 ```typescript
129 // With an agentic provider (e.g., Vercel, Langchain)
130 const agenticProvider = new VercelProvider();
131 const composio = new Composio({
132 apiKey: 'your-api-key',
133 provider: agenticProvider,
134 });
135
136 // All modifiers work with agentic providers
137 const tools = await composio.tools.get(
138 'default',
139 {
140 toolkits: ['github'],
141 },
142 {
143 // Schema modifier
144 modifySchema: ({ toolSlug, toolkitSlug, schema }) => {
145 // Enhance tool schema
146 return schema;
147 },
148
149 // Before execution modifier (only works with agentic providers)
150 beforeExecute: ({ toolSlug, toolkitSlug, params }) => {
151 // Modify execution parameters
152 return params;
153 },
154
155 // After execution modifier (only works with agentic providers)
156 afterExecute: ({ toolSlug, toolkitSlug, result }) => {
157 // Transform execution results
158 return result;
159 },
160 }
161 );
162
163 // With a non-agentic provider (e.g., OpenAI)
164 const nonAgenticProvider = new OpenAIProvider();
165 const composioNonAgentic = new Composio({
166 apiKey: 'your-api-key',
167 provider: nonAgenticProvider,
168 });
169
170 // Only schema modifiers work with non-agentic providers
171 const openaiTools = await composioNonAgentic.tools.get(
172 'default',
173 {
174 toolkits: ['github'],
175 },
176 {
177 // Schema modifier (works with all providers)
178 modifySchema: (toolSlug, toolkitSlug, tool) => {
179 // Enhance tool schema
180 return tool;
181 },
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
186 }
187 );
188 ```
189
190 ## Creating Reusable Modifiers
191
192 For better code organization, you can create reusable modifier functions:
193
194 ```typescript
195 // Define reusable modifiers
196 const addTimestamps = ({ toolSlug, toolkitSlug, result }) => {
197 if (result.successful) {
198 result.data.executedAt = new Date().toISOString();
199 }
200 return result;
201 };
202
203 const logExecutions = ({ toolSlug, toolkitSlug, params }) => {
204 console.log(`Executing ${toolSlug} from ${toolkitSlug} at ${new Date().toISOString()}`);
205 return params;
206 };
207
208 const sanitizeInputs = ({ toolSlug, toolkitSlug, params }) => {
209 // Sanitize input parameters to prevent injection attacks
210 if (params.arguments) {
211 Object.keys(params.arguments).forEach(key => {
212 if (typeof params.arguments[key] === 'string') {
213 params.arguments[key] = sanitizeString(params.arguments[key]);
214 }
215 });
216 }
217 return params;
218 };
219
220 // Use the reusable modifiers
221 const result = await composio.tools.execute(
222 'GITHUB_GET_REPO',
223 {
224 userId: 'default',
225 arguments: {
226 owner: 'composio',
227 repo: 'sdk',
228 },
229 },
230 {
231 beforeExecute: sanitizeInputs,
232 afterExecute: addTimestamps,
233 }
234 );
235 ```
236
237 ## Practical Use Cases
238
239 ### Comparing Agentic and Non-Agentic Provider Usage
240
241 Here's a side-by-side comparison of how to use modifiers with different provider types:
242
243 ```typescript
244 // Example from examples/modifiers/src/index.ts
245
246 // Non-agentic provider example (OpenAI)
247 const openai = new Composio({
248 apiKey: process.env.COMPOSIO_API_KEY,
249 provider: new OpenAIProvider(),
250 });
251
252 // Schema modifiers work with non-agentic providers
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({
266 apiKey: process.env.COMPOSIO_API_KEY,
267 provider: new VercelProvider(),
268 });
269
270 // All modifiers work with agentic providers
271 const agenticTools = await vercel.tools.get('default', 'HACKERNEWS_GET_USER', {
272 // Schema modifier
273 modifySchema: ({ toolSlug, toolkitSlug, schema }) => {
274 if (tool.inputParameters?.properties?.userId) {
275 tool.inputParameters.properties.userId.description = 'HackerNews username (e.g., "pg")';
276 }
277 return schema;
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
294
295 For non-agentic providers, you can use the provider's helper methods to apply execution modifiers:
296
297 ```typescript
298 // Get the OpenAI provider instance
299 const openaiProvider = composio.provider as OpenAIProvider;
300
301 // When handling a tool call from OpenAI
302 const toolOutputs = await openaiProvider.handleToolCalls(
303 'default', // userId
304 completion, // OpenAI completion object
305 { connectedAccountId: 'account_123' }, // Options
306 {
307 // Manually apply execution modifiers
308 beforeExecute: ({ toolSlug, toolkitSlug, params }) => {
309 console.log(`Executing ${toolSlug}`);
310 return params;
311 },
312 afterExecute: ({ toolSlug, toolkitSlug, result }) => {
313 result.data.processedAt = new Date().toISOString();
314 return result;
315 },
316 }
317 );
318 ```
319
320 ### Caching Tool Results (Agentic Providers Only)
321
322 > Note: This example uses execution modifiers and will only work with agentic providers.
323
324 ```typescript
325 // Simple in-memory cache
326 const cache = new Map();
327
328 const cacheModifier = ({ toolSlug, toolkitSlug, params }) => {
329 // Create a cache key based on tool slug and arguments
330 const cacheKey = `${toolSlug}-${JSON.stringify(params.arguments)}`;
331
332 // Add cache key to params for the after modifier to use
333 params.__cacheKey = cacheKey;
334
335 // Check if we have a cached result
336 if (cache.has(cacheKey)) {
337 const cachedResult = cache.get(cacheKey);
338 if (Date.now() - cachedResult.timestamp < 60000) {
339 // 1 minute cache
340 // Throw a special error to short-circuit execution
341 throw { __cached: true, result: cachedResult.result };
342 }
343 }
344
345 return params;
346 };
347
348 const cacheAfterModifier = ({ toolSlug, toolkitSlug, result }) => {
349 if (result.successful && result.__cacheKey) {
350 // Store in cache
351 cache.set(result.__cacheKey, {
352 result,
353 timestamp: Date.now(),
354 });
355
356 // Remove the cache key from the result
357 delete result.__cacheKey;
358 }
359
360 return result;
361 };
362
363 // Use with try/catch to handle the cache hit
364 try {
365 const result = await composio.tools.execute(
366 'GITHUB_GET_REPO',
367 {
368 userId: 'default',
369 arguments: {
370 owner: 'composio',
371 repo: 'sdk',
372 },
373 },
374 {
375 beforeExecute: cacheModifier,
376 afterExecute: cacheAfterModifier,
377 }
378 );
379
380 console.log('Fresh result:', result);
381 } catch (error) {
382 if (error.__cached) {
383 console.log('Cached result:', error.result);
384 } else {
385 throw error; // Re-throw if it's a real error
386 }
387 }
388 ```
389
390 ### Adding Authentication Headers
391
392 ```typescript
393 const authModifier = ({ toolSlug, toolkitSlug, params }) => {
394 // Add authentication parameters for specific toolkits
395 if (toolkitSlug === 'custom-api') {
396 if (!params.customAuthParams) {
397 params.customAuthParams = {};
398 }
399
400 if (!params.customAuthParams.parameters) {
401 params.customAuthParams.parameters = [];
402 }
403
404 // Add an API key to the headers
405 params.customAuthParams.parameters.push({
406 in: 'header',
407 name: 'X-API-Key',
408 value: process.env.CUSTOM_API_KEY,
409 });
410 }
411
412 return params;
413 };
414
415 // Apply the auth modifier to all tools from a specific toolkit
416 const tools = await composio.tools.get(
417 'default',
418 {
419 toolkits: ['custom-api'],
420 },
421 {
422 beforeExecute: authModifier,
423 }
424 );
425 ```
426
427 ### Data Transformation Pipeline
428
429 ```typescript
430 // Create a pipeline of modifiers
431 const pipeModifiers = (...modifiers) => {
432 return ({ toolSlug, toolkitSlug, result }) => {
433 return modifiers.reduce((modifiedResult, modifier) => {
434 return modifier({ toolSlug, toolkitSlug, result: modifiedResult });
435 }, result);
436 };
437 };
438
439 // Individual transformation steps
440 const addMetadata = ({ toolSlug, toolkitSlug, result }) => {
441 if (result.successful) {
442 result.data.metadata = { source: toolkitSlug, tool: toolSlug };
443 }
444 return result;
445 };
446
447 const formatDates = ({ toolSlug, toolkitSlug, result }) => {
448 if (result.successful) {
449 // Convert all dates to a consistent format
450 Object.keys(result.data).forEach(key => {
451 if (key.includes('date') || key.includes('time') || key.endsWith('At')) {
452 if (result.data[key]) {
453 result.data[key] = new Date(result.data[key]).toLocaleString();
454 }
455 }
456 });
457 }
458 return result;
459 };
460
461 const removeNulls = ({ toolSlug, toolkitSlug, result }) => {
462 if (result.successful) {
463 // Remove null and undefined values
464 Object.keys(result.data).forEach(key => {
465 if (result.data[key] === null || result.data[key] === undefined) {
466 delete result.data[key];
467 }
468 });
469 }
470 return result;
471 };
472
473 // Apply the pipeline
474 const result = await composio.tools.execute(
475 'GITHUB_GET_REPO',
476 {
477 userId: 'default',
478 arguments: {
479 owner: 'composio',
480 repo: 'sdk',
481 },
482 },
483 {
484 afterExecute: pipeModifiers(addMetadata, formatDates, removeNulls),
485 }
486 );
487 ```
488
489 ## Provider-Specific Modifier Support
490
491 Composio SDK supports two types of providers:
492
493 1. **Agentic Providers**: Providers that have control over tool execution (e.g., Vercel, Langchain)
494 2. **Non-Agentic Providers**: Providers that only format tools but don't control execution (e.g., OpenAI)
495
496 ### Technical Differences
497
498 The key technical distinction between these provider types affects which modifiers they support:
499
500 - **Agentic Providers** receive an `ExecuteToolFn` parameter in their `wrapTool`/`wrapTools` methods, allowing them to embed execution modifiers directly into the wrapped tools. This means they support all three types of modifiers: schema, beforeExecute, and afterExecute.
501
502 - **Non-Agentic Providers** only format tools for external consumption and don't control execution. When tools are wrapped by non-agentic providers, the context is lost, making it impossible to automatically apply execution modifiers. These providers only support schema modifiers.
503
504 Here's how the provider implementations differ:
505
506 ```typescript
507 // Non-Agentic Provider (e.g., OpenAI)
508 class OpenAIProvider extends BaseNonAgenticProvider<OpenAiToolCollection, OpenAiTool> {
509 // No executeToolFn parameter
510 override wrapTool(tool: Tool): OpenAiTool {
511 // Simply formats the tool for OpenAI
512 return {
513 type: 'function',
514 function: {
515 name: tool.slug,
516 description: tool.description,
517 parameters: tool.inputParameters,
518 },
519 };
520 }
521 }
522
523 // Agentic Provider (e.g., Vercel)
524 class VercelProvider extends BaseAgenticProvider<VercelToolCollection, VercelTool> {
525 // Receives executeToolFn parameter
526 wrapTool(tool: Tool, executeTool: ExecuteToolFn): VercelTool {
527 return tool({
528 description: tool.description,
529 parameters: jsonSchema(tool.inputParameters ?? {}),
530 execute: async params => {
531 // Can apply modifiers through executeTool
532 return await executeTool(tool.slug, params);
533 },
534 });
535 }
536 }
537 ```
538
539 ### Using Modifiers with Non-Agentic Providers
540
541 For non-agentic providers like OpenAI, you can still apply execution modifiers manually using the provider's helper methods:
542
543 ```typescript
544 // Get OpenAI provider instance
545 const openaiProvider = composio.provider as OpenAIProvider;
546
547 // Execute a tool call with modifiers
548 const result = await openaiProvider.executeToolCall(
549 'default', // userId
550 toolCall, // OpenAI tool call object
551 { connectedAccountId: 'account_123' }, // Options
552 {
553 // Manually apply execution modifiers
554 beforeExecute: ({ toolSlug, toolkitSlug, params }) => {
555 console.log(`Executing ${toolSlug}`);
556 return params;
557 },
558 afterExecute: ({ toolSlug, toolkitSlug, result }) => {
559 result.data.processedAt = new Date().toISOString();
560 return result;
561 },
562 }
563 );
564 ```
565
566 ## Tool Router Modifiers (v0.4.0+)
567
568 Tool Router sessions support enhanced modifier types that include session context. This is useful for tracking and managing tool execution across different user sessions.
569
570 ### Using Session Modifiers with Tool Router
571
572 ```typescript
573 import { Composio } from '@composio/core';
574 import { SessionExecuteMetaModifiers } from '@composio/core';
575
576 const composio = new Composio();
577
578 const session = await composio.create('user_123', {
579 toolkits: ['gmail', 'slack'],
580 });
581
582 // Use session-specific modifiers
583 const tools = await session.tools({
584 modifySchema: ({ toolSlug, toolkitSlug, schema }) => {
585 // Customize tool schemas
586 console.log(`Modifying schema for ${toolSlug} from ${toolkitSlug}`);
587 return schema;
588 },
589 beforeExecute: ({ toolSlug, toolkitSlug, sessionId, params }) => {
590 // Access session ID for tracking
591 console.log(`[Session: ${sessionId}] Executing ${toolSlug} from ${toolkitSlug}`);
592
593 // Add session-specific metadata
594 params.sessionMetadata = {
595 sessionId,
596 timestamp: new Date().toISOString(),
597 };
598
599 return params;
600 },
601 afterExecute: ({ toolSlug, toolkitSlug, sessionId, result }) => {
602 // Transform results with session context
603 console.log(`[Session: ${sessionId}] Completed ${toolSlug}`);
604
605 if (result.successful) {
606 result.data.sessionId = sessionId;
607 result.data.executedAt = new Date().toISOString();
608 }
609
610 return result;
611 },
612 });
613 ```
614
615 ### Session-Specific Modifier Benefits
616
617 The session-specific modifiers provide several advantages:
618
619 1. **Session Tracking**: Access to `sessionId` allows you to track which session executed which tools
620 2. **User Context**: Associate tool executions with specific users through session IDs
621 3. **Audit Logging**: Log tool executions with session context for compliance and debugging
622 4. **Performance Monitoring**: Track tool execution performance per session
623
624 ### Getting Meta Tools Directly
625
626 You can also fetch tool router meta tools directly using the new method:
627
628 ```typescript
629 import { Composio } from '@composio/core';
630
631 const composio = new Composio();
632
633 // Get raw meta tools for a session
634 const metaTools = await composio.tools.getRawToolRouterMetaTools('session_123', {
635 modifySchema: ({ toolSlug, toolkitSlug, schema }) => {
636 // Customize meta tool schemas
637 if (toolSlug === 'composio_authorize_toolkit') {
638 schema.description = 'Custom description for authorization';
639 }
640 return schema;
641 }
642 });
643
644 // Use the meta tools with your AI framework
645 console.log('Available meta tools:', metaTools.map(t => t.name));
646 ```
647
648 ## Type Definitions
649
650 ```typescript
651 // Schema Modifier (supported by all providers)
652 type TransformToolSchemaModifier = (toolSlug: string, toolkitSlug: string, tool: Tool) => Tool;
653
654 // Before Execution Modifier (supported by agentic providers only)
655 type beforeExecuteModifier = (
656 toolSlug: string,
657 toolkitSlug: string,
658 params: ToolExecuteParams
659 ) => ToolExecuteParams;
660
661 // After Execution Modifier (supported by agentic providers only)
662 type afterExecuteModifier = (
663 toolSlug: string,
664 toolkitSlug: string,
665 result: ToolExecuteResponse
666 ) => ToolExecuteResponse;
667
668 // Modifiers Object
669 interface ExecuteToolModifiers {
670 beforeExecute?: beforeExecuteModifier;
671 afterExecute?: afterExecuteModifier;
672 }
673
674 // Provider Options
675 interface ProviderOptions<TProvider> {
676 modifySchema?: TransformToolSchemaModifier;
677 beforeExecute?: beforeExecuteModifier; // Only applied by agentic providers
678 afterExecute?: afterExecuteModifier; // Only applied by agentic providers
679 }
680
681 // Session-Specific Modifiers (v0.4.0+)
682 interface SessionExecuteMetaModifiers {
683 modifySchema?: (context: {
684 toolSlug: string;
685 toolkitSlug: string;
686 schema: any;
687 }) => any;
688
689 beforeExecute?: (context: {
690 toolSlug: string;
691 toolkitSlug: string;
692 sessionId: string;
693 params: any;
694 }) => any;
695
696 afterExecute?: (context: {
697 toolSlug: string;
698 toolkitSlug: string;
699 sessionId: string;
700 result: any;
701 }) => any;
702 }
703
704 // Session Meta Tool Options (v0.4.0+)
705 interface SessionMetaToolOptions {
706 modifySchema?: (context: {
707 toolSlug: string;
708 toolkitSlug: string;
709 schema: any;
710 }) => any;
711 }
712 ```