@devries-cameron20 / composio Mirror · read-only / commits / 5cd699a42
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 23, 01:45 UTC

Add docs

haxzie committed May 21, 2025 at 16:27 UTC 5cd699a42a5a15e68e65d69b8b82849a32091708
18 files changed +4129 -1
.gitignore
+4 -1
@@ -37,4 +37,7 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
37 .turbo
38
39 # lerna
40 -lerna-debug.log*
\ No newline at end of file
40 +lerna-debug.log*
41 +
42 +# temp files
43 +temp
docs/advanced/custom-providers.md new
+494
@@ -0,0 +1,494 @@
1 +# Creating Custom Providers
2 +
3 +This guide provides a comprehensive walkthrough of creating custom providers for the Composio SDK, enabling integration with different AI frameworks and platforms.
4 +
5 +## Provider Architecture
6 +
7 +The Composio SDK uses a provider architecture to adapt tools for different AI frameworks. The provider handles:
8 +
9 +1. **Tool Format Transformation**: Converting Composio tools into formats compatible with specific AI platforms
10 +2. **Tool Execution**: Managing the flow of tool execution and results
11 +3. **Platform-Specific Integration**: Providing helper methods for seamless integration
12 +
13 +## Types of Providers
14 +
15 +There are two types of providers:
16 +
17 +1. **Non-Agentic Providers**: Transform tools for platforms that don't have their own agency (e.g., OpenAI)
18 +2. **Agentic Providers**: Transform tools for platforms that have their own agency (e.g., LangChain, AutoGPT)
19 +
20 +## Provider Class Hierarchy
21 +
22 +```
23 +BaseProvider (Abstract)
24 +├── BaseNonAgenticProvider (Abstract)
25 +│ └── OpenAIProvider (Concrete)
26 +│ └── [Your Custom Non-Agentic Provider] (Concrete)
27 +└── BaseAgenticProvider (Abstract)
28 + └── [Your Custom Agentic Provider] (Concrete)
29 +```
30 +
31 +## Creating a Non-Agentic Provider
32 +
33 +Non-agentic providers implement the `BaseNonAgenticProvider` abstract class:
34 +
35 +```typescript
36 +import { BaseNonAgenticProvider, Tool } from '@composio/sdk';
37 +
38 +// Define your tool format
39 +interface MyAITool {
40 + name: string;
41 + description: string;
42 + parameters: {
43 + type: string;
44 + properties: Record<string, unknown>;
45 + required?: string[];
46 + };
47 +}
48 +
49 +// Define your tool collection format
50 +type MyAIToolCollection = MyAITool[];
51 +
52 +// Create your provider
53 +export class MyAIProvider extends BaseNonAgenticProvider<MyAIToolCollection, MyAITool> {
54 + // Required: Unique provider name for telemetry
55 + readonly name = 'my-ai-platform';
56 +
57 + // Required: Method to transform a single tool
58 + override wrapTool(tool: Tool): MyAITool {
59 + return {
60 + name: tool.slug,
61 + description: tool.description || '',
62 + parameters: {
63 + type: 'object',
64 + properties: tool.inputParameters?.properties || {},
65 + required: tool.inputParameters?.required || [],
66 + },
67 + };
68 + }
69 +
70 + // Required: Method to transform a collection of tools
71 + override wrapTools(tools: Tool[]): MyAIToolCollection {
72 + return tools.map(tool => this.wrapTool(tool));
73 + }
74 +
75 + // Optional: Custom helper methods for your AI platform
76 + async executeMyAIToolCall(
77 + userId: string,
78 + toolCall: {
79 + name: string;
80 + arguments: Record<string, unknown>;
81 + }
82 + ): Promise<string> {
83 + // Use the built-in executeTool method
84 + const result = await this.executeTool(
85 + toolCall.name,
86 + {
87 + userId,
88 + arguments: toolCall.arguments,
89 + }
90 + );
91 +
92 + return JSON.stringify(result.data);
93 + }
94 +}
95 +```
96 +
97 +## Creating an Agentic Provider
98 +
99 +Agentic providers implement the `BaseAgenticProvider` abstract class:
100 +
101 +```typescript
102 +import { BaseAgenticProvider, Tool, ExecuteToolFn } from '@composio/sdk';
103 +
104 +// Define your tool format
105 +interface AgentTool {
106 + name: string;
107 + description: string;
108 + execute: (args: Record<string, unknown>) => Promise<unknown>;
109 + schema: Record<string, unknown>;
110 +}
111 +
112 +// Define your tool collection format
113 +interface AgentToolkit {
114 + tools: AgentTool[];
115 + createAgent: (config: Record<string, unknown>) => unknown;
116 +}
117 +
118 +// Create your provider
119 +export class MyAgentProvider extends BaseAgenticProvider<AgentToolkit, AgentTool> {
120 + // Required: Unique provider name for telemetry
121 + readonly name = 'my-agent-platform';
122 +
123 + // Required: Method to transform a single tool with execute function
124 + override wrapTool(tool: Tool, executeToolFn: ExecuteToolFn): AgentTool {
125 + return {
126 + name: tool.slug,
127 + description: tool.description || '',
128 + schema: tool.inputParameters || {},
129 + execute: async (args: Record<string, unknown>) => {
130 + const result = await executeToolFn(tool.slug, args);
131 + if (!result.successful) {
132 + throw new Error(result.error || 'Tool execution failed');
133 + }
134 + return result.data;
135 + }
136 + };
137 + }
138 +
139 + // Required: Method to transform a collection of tools with execute function
140 + override wrapTools(tools: Tool[], executeToolFn: ExecuteToolFn): AgentToolkit {
141 + const agentTools = tools.map(tool => this.wrapTool(tool, executeToolFn));
142 +
143 + return {
144 + tools: agentTools,
145 + createAgent: (config) => {
146 + // Create an agent using the tools
147 + return {
148 + run: async (prompt: string) => {
149 + // Implementation depends on your agent framework
150 + console.log(`Running agent with prompt: ${prompt}`);
151 + // The agent would use the tools.execute method to run tools
152 + }
153 + };
154 + }
155 + };
156 + }
157 +
158 + // Optional: Custom helper methods for your agent platform
159 + async runAgent(agentToolkit: AgentToolkit, prompt: string): Promise<unknown> {
160 + const agent = agentToolkit.createAgent({});
161 + return await agent.run(prompt);
162 + }
163 +}
164 +```
165 +
166 +## Using Your Custom Provider
167 +
168 +After creating your provider, use it with the Composio SDK:
169 +
170 +```typescript
171 +import { Composio } from '@composio/sdk';
172 +import { MyAIProvider } from './my-ai-provider';
173 +
174 +// Create your provider instance
175 +const myProvider = new MyAIProvider();
176 +
177 +// Initialize Composio with your provider
178 +const composio = new Composio({
179 + apiKey: 'your-composio-api-key',
180 + provider: myProvider,
181 +});
182 +
183 +// Get tools - they will be transformed by your provider
184 +const tools = await composio.tools.get('default', {
185 + toolkits: ['github'],
186 +});
187 +
188 +// Use the tools with your AI platform
189 +console.log(tools); // These will be in your custom format
190 +```
191 +
192 +## Provider State and Context
193 +
194 +Your provider can maintain state and context:
195 +
196 +```typescript
197 +export class StatefulProvider extends BaseNonAgenticProvider<ToolCollection, Tool> {
198 + readonly name = 'stateful-provider';
199 +
200 + // Provider state
201 + private requestCount = 0;
202 + private toolCache = new Map<string, any>();
203 + private config: ProviderConfig;
204 +
205 + constructor(config: ProviderConfig) {
206 + super();
207 + this.config = config;
208 + }
209 +
210 + override wrapTool(tool: Tool): ProviderTool {
211 + this.requestCount++;
212 +
213 + // Use the provider state/config
214 + const enhancedTool = {
215 + // Transform the tool
216 + name: this.config.useUpperCase ? tool.slug.toUpperCase() : tool.slug,
217 + description: tool.description,
218 + schema: tool.inputParameters,
219 + };
220 +
221 + // Cache the transformed tool
222 + this.toolCache.set(tool.slug, enhancedTool);
223 +
224 + return enhancedTool;
225 + }
226 +
227 + override wrapTools(tools: Tool[]): ProviderToolCollection {
228 + return tools.map(tool => this.wrapTool(tool));
229 + }
230 +
231 + // Custom methods that use provider state
232 + getRequestCount(): number {
233 + return this.requestCount;
234 + }
235 +
236 + getCachedTool(slug: string): ProviderTool | undefined {
237 + return this.toolCache.get(slug);
238 + }
239 +}
240 +```
241 +
242 +## Advanced: Provider Composition
243 +
244 +You can compose functionality by extending existing providers:
245 +
246 +```typescript
247 +import { OpenAIProvider } from '@composio/sdk';
248 +
249 +// Extend the OpenAI provider with custom functionality
250 +export class EnhancedOpenAIProvider extends OpenAIProvider {
251 + // Add properties
252 + private analytics = {
253 + toolCalls: 0,
254 + errors: 0,
255 + };
256 +
257 + // Override methods to add functionality
258 + override async executeToolCall(userId, tool, options, modifiers) {
259 + this.analytics.toolCalls++;
260 +
261 + try {
262 + // Call the parent implementation
263 + const result = await super.executeToolCall(userId, tool, options, modifiers);
264 + return result;
265 + } catch (error) {
266 + this.analytics.errors++;
267 + throw error;
268 + }
269 + }
270 +
271 + // Add new methods
272 + getAnalytics() {
273 + return this.analytics;
274 + }
275 +
276 + async executeWithRetry(userId, tool, options, modifiers, maxRetries = 3) {
277 + let attempts = 0;
278 + let lastError;
279 +
280 + while (attempts < maxRetries) {
281 + try {
282 + return await this.executeToolCall(userId, tool, options, modifiers);
283 + } catch (error) {
284 + lastError = error;
285 + attempts++;
286 + await new Promise(resolve => setTimeout(resolve, 1000 * attempts));
287 + }
288 + }
289 +
290 + throw lastError;
291 + }
292 +}
293 +```
294 +
295 +## Example: Anthropic Claude Provider
296 +
297 +Here's a more complete example for Anthropic's Claude:
298 +
299 +```typescript
300 +import { BaseNonAgenticProvider, Tool } from '@composio/sdk';
301 +import Anthropic from '@anthropic-ai/sdk';
302 +
303 +interface ClaudeTool {
304 + name: string;
305 + description: string;
306 + input_schema: {
307 + type: string;
308 + properties: Record<string, unknown>;
309 + required?: string[];
310 + };
311 +}
312 +
313 +type ClaudeToolCollection = ClaudeTool[];
314 +
315 +export class ClaudeProvider extends BaseNonAgenticProvider<ClaudeToolCollection, ClaudeTool> {
316 + readonly name = 'claude';
317 + private client: Anthropic;
318 +
319 + constructor(apiKey: string) {
320 + super();
321 + this.client = new Anthropic({
322 + apiKey,
323 + });
324 + }
325 +
326 + override wrapTool(tool: Tool): ClaudeTool {
327 + return {
328 + name: tool.slug,
329 + description: tool.description || '',
330 + input_schema: {
331 + type: 'object',
332 + properties: tool.inputParameters?.properties || {},
333 + required: tool.inputParameters?.required || [],
334 + },
335 + };
336 + }
337 +
338 + override wrapTools(tools: Tool[]): ClaudeToolCollection {
339 + return tools.map(tool => this.wrapTool(tool));
340 + }
341 +
342 + // Helper method to create a Claude message with tools
343 + async createMessage(prompt: string, tools: ClaudeToolCollection, userId: string) {
344 + const response = await this.client.messages.create({
345 + model: 'claude-3-opus-20240229',
346 + max_tokens: 1024,
347 + system: 'You are a helpful assistant with access to tools.',
348 + messages: [
349 + { role: 'user', content: prompt }
350 + ],
351 + tools,
352 + });
353 +
354 + // Process tool calls if any
355 + if (response.content.some(content =>
356 + content.type === 'tool_use' &&
357 + 'name' in content &&
358 + 'input' in content
359 + )) {
360 + const toolResponses = await Promise.all(
361 + response.content
362 + .filter(content => content.type === 'tool_use')
363 + .map(async (content: any) => {
364 + const result = await this.executeTool(
365 + content.name,
366 + {
367 + userId,
368 + arguments: content.input,
369 + }
370 + );
371 +
372 + return {
373 + type: 'tool_result',
374 + tool_use_id: content.id,
375 + content: JSON.stringify(result.data),
376 + };
377 + })
378 + );
379 +
380 + // Continue the conversation with tool results
381 + const followupResponse = await this.client.messages.create({
382 + model: 'claude-3-opus-20240229',
383 + max_tokens: 1024,
384 + system: 'You are a helpful assistant with access to tools.',
385 + messages: [
386 + { role: 'user', content: prompt },
387 + { role: 'assistant', content: response.content },
388 + { role: 'user', content: toolResponses }
389 + ],
390 + tools,
391 + });
392 +
393 + return followupResponse;
394 + }
395 +
396 + return response;
397 + }
398 +}
399 +```
400 +
401 +## Example: LangChain Provider
402 +
403 +Here's an example for LangChain:
404 +
405 +```typescript
406 +import { BaseAgenticProvider, Tool, ExecuteToolFn } from '@composio/sdk';
407 +import { DynamicTool } from 'langchain/tools';
408 +import { ChatOpenAI } from 'langchain/chat_models/openai';
409 +import { initializeAgentExecutorWithOptions } from 'langchain/agents';
410 +
411 +interface LangChainTool extends DynamicTool {
412 + name: string;
413 + description: string;
414 + func: (input: Record<string, unknown>) => Promise<string>;
415 +}
416 +
417 +interface LangChainToolkit {
418 + tools: LangChainTool[];
419 + createExecutor: (options: { model: string }) => Promise<any>;
420 +}
421 +
422 +export class LangChainProvider extends BaseAgenticProvider<LangChainToolkit, LangChainTool> {
423 + readonly name = 'langchain';
424 +
425 + override wrapTool(tool: Tool, executeToolFn: ExecuteToolFn): LangChainTool {
426 + return new DynamicTool({
427 + name: tool.slug,
428 + description: tool.description || '',
429 + func: async (input: string) => {
430 + try {
431 + // Parse input from string to object
432 + const args = typeof input === 'string' ? JSON.parse(input) : input;
433 +
434 + // Execute the tool
435 + const result = await executeToolFn(tool.slug, args);
436 +
437 + if (!result.successful) {
438 + throw new Error(result.error || 'Tool execution failed');
439 + }
440 +
441 + // Return the result
442 + return JSON.stringify(result.data);
443 + } catch (error) {
444 + return `Error: ${error.message}`;
445 + }
446 + }
447 + }) as LangChainTool;
448 + }
449 +
450 + override wrapTools(tools: Tool[], executeToolFn: ExecuteToolFn): LangChainToolkit {
451 + const langchainTools = tools.map(tool => this.wrapTool(tool, executeToolFn));
452 +
453 + return {
454 + tools: langchainTools,
455 + createExecutor: async ({ model }) => {
456 + const llm = new ChatOpenAI({
457 + modelName: model || 'gpt-4',
458 + temperature: 0,
459 + });
460 +
461 + return await initializeAgentExecutorWithOptions(
462 + langchainTools,
463 + llm,
464 + {
465 + agentType: 'chat-zero-shot-react-description',
466 + verbose: true,
467 + }
468 + );
469 + }
470 + };
471 + }
472 +
473 + // Helper method to run the agent
474 + async runAgent(
475 + toolkit: LangChainToolkit,
476 + prompt: string,
477 + model = 'gpt-4'
478 + ): Promise<string> {
479 + const executor = await toolkit.createExecutor({ model });
480 + const result = await executor.call({ input: prompt });
481 + return result.output;
482 + }
483 +}
484 +```
485 +
486 +## Best Practices
487 +
488 +1. **Keep providers focused**: Each provider should integrate with one specific platform
489 +2. **Handle errors gracefully**: Catch and transform errors from tool execution
490 +3. **Follow platform conventions**: Adopt naming and structural conventions of the target platform
491 +4. **Optimize for performance**: Cache transformed tools when possible
492 +5. **Add helper methods**: Provide convenient methods for common platform-specific operations
493 +6. **Provide clear documentation**: Document your provider's unique features and usage
494 +7. **Use telemetry**: Set a meaningful provider name for telemetry insights
\ No newline at end of file
docs/advanced/error-handling.md new
+242
@@ -0,0 +1,242 @@
1 +# Error Handling in Composio SDK
2 +
3 +Proper error handling is essential for building robust applications with the Composio SDK. This guide explains the error classes provided by the SDK and how to handle errors effectively.
4 +
5 +## Error Hierarchy
6 +
7 +Composio SDK provides a structured error hierarchy:
8 +
9 +- `ComposioError`: The base error class for all Composio errors
10 + - `AuthConfigErrors`: Errors related to authentication configurations
11 + - `ConnectedAccountsError`: Errors related to connected accounts
12 + - `ConnectionRequestError`: Errors related to connection requests
13 + - `ToolErrors`: Errors related to tools and tool execution
14 + - `ToolkitErrors`: Errors related to toolkits
15 + - `ValidationError`: Errors related to input validation
16 +
17 +## Common Error Types
18 +
19 +### Validation Errors
20 +
21 +Validation errors occur when the input to a method doesn't match the expected schema:
22 +
23 +```typescript
24 +try {
25 + await composio.tools.get('default', {
26 + invalidParam: 'value', // This will cause a validation error
27 + });
28 +} catch (error) {
29 + if (error instanceof ValidationError) {
30 + console.error('Validation error:', error.message);
31 + console.error('Validation details:', error.validationError);
32 + }
33 +}
34 +```
35 +
36 +### Tool Execution Errors
37 +
38 +Errors that occur during tool execution:
39 +
40 +```typescript
41 +try {
42 + const result = await composio.tools.execute('GITHUB_GET_REPO', {
43 + userId: 'default',
44 + arguments: {
45 + owner: 'composio',
46 + // Missing 'repo' parameter will cause an error
47 + },
48 + });
49 +} catch (error) {
50 + if (error instanceof ComposioToolExecutionError) {
51 + console.error('Tool execution error:', error.message);
52 + console.error('Tool:', error.context.toolSlug);
53 + console.error('Execution params:', error.context.body);
54 + }
55 +}
56 +```
57 +
58 +### Not Found Errors
59 +
60 +Errors that occur when a resource is not found:
61 +
62 +```typescript
63 +try {
64 + await composio.tools.get('default', 'NON_EXISTENT_TOOL');
65 +} catch (error) {
66 + if (error instanceof ComposioToolNotFoundError) {
67 + console.error('Tool not found:', error.message);
68 + }
69 +}
70 +```
71 +
72 +## Handling Errors in Tool Execution
73 +
74 +When executing tools, you should handle both SDK errors and execution result errors:
75 +
76 +```typescript
77 +try {
78 + const result = await composio.tools.execute('GITHUB_GET_REPO', {
79 + userId: 'default',
80 + arguments: {
81 + owner: 'composio',
82 + repo: 'sdk',
83 + },
84 + });
85 +
86 + // Check if the execution was successful
87 + if (result.successful) {
88 + console.log('Repository details:', result.data);
89 + } else {
90 + // Handle unsuccessful execution
91 + console.error('Execution failed:', result.error);
92 + }
93 +} catch (error) {
94 + // Handle SDK errors
95 + console.error('SDK error:', error.message);
96 +}
97 +```
98 +
99 +## Error Handling with Connected Accounts
100 +
101 +Handle errors during the connection flow:
102 +
103 +```typescript
104 +try {
105 + // Step 1: Authorize the toolkit
106 + const connectionRequest = await composio.toolkits.authorize('user123', 'github');
107 +
108 + // Step 2: Wait for the connection to be established
109 + try {
110 + const connectedAccount = await composio.connectedAccounts.waitForConnection(
111 + connectionRequest.id,
112 + 60000 // 60 second timeout
113 + );
114 + console.log('Connected account:', connectedAccount);
115 + } catch (timeoutError) {
116 + if (timeoutError instanceof ConnectionRequestTimeoutError) {
117 + console.error('Connection timed out. Please try again.');
118 + } else if (timeoutError instanceof ConnectionRequestFailedError) {
119 + console.error('Connection failed:', timeoutError.message);
120 + }
121 + }
122 +} catch (error) {
123 + if (error instanceof ComposioAuthConfigNotFoundError) {
124 + console.error('Auth config not found:', error.message);
125 + } else {
126 + console.error('Error initiating connection:', error.message);
127 + }
128 +}
129 +```
130 +
131 +## Global Error Handler
132 +
133 +For larger applications, consider implementing a global error handler:
134 +
135 +```typescript
136 +// Define a global error handler function
137 +function handleComposioError(error: unknown): void {
138 + if (error instanceof ValidationError) {
139 + console.error('Validation error:', error.message);
140 + } else if (error instanceof ComposioToolNotFoundError) {
141 + console.error('Tool not found:', error.message);
142 + } else if (error instanceof ComposioToolExecutionError) {
143 + console.error('Tool execution error:', error.message);
144 + } else if (error instanceof ComposioAuthConfigNotFoundError) {
145 + console.error('Auth config not found:', error.message);
146 + } else if (error instanceof ConnectionRequestFailedError) {
147 + console.error('Connection failed:', error.message);
148 + } else if (error instanceof ConnectionRequestTimeoutError) {
149 + console.error('Connection timed out:', error.message);
150 + } else if (error instanceof ComposioError) {
151 + console.error('Composio error:', error.message);
152 + } else {
153 + console.error('Unexpected error:', error);
154 + }
155 +}
156 +
157 +// Use the global error handler
158 +try {
159 + const result = await composio.tools.execute('GITHUB_GET_REPO', {
160 + userId: 'default',
161 + arguments: {
162 + owner: 'composio',
163 + repo: 'sdk',
164 + },
165 + });
166 +
167 + if (!result.successful) {
168 + console.error('Execution failed:', result.error);
169 + }
170 +} catch (error) {
171 + handleComposioError(error);
172 +}
173 +```
174 +
175 +## Error Handling in Custom Tools
176 +
177 +When creating custom tools, implement proper error handling in your handler function:
178 +
179 +```typescript
180 +const customTool = await composio.tools.createCustomTool({
181 + name: 'My Custom Tool',
182 + description: 'A custom tool with error handling',
183 + slug: 'MY_CUSTOM_TOOL',
184 + inputParameters: {
185 + type: 'object',
186 + properties: {
187 + param1: { type: 'string' }
188 + },
189 + required: ['param1']
190 + },
191 + outputParameters: {
192 + type: 'object',
193 + properties: {
194 + result: { type: 'string' }
195 + }
196 + },
197 + handler: async (params, context) => {
198 + try {
199 + // Validate input
200 + const { param1 } = params.arguments;
201 + if (!param1 || param1.trim() === '') {
202 + return {
203 + data: {},
204 + successful: false,
205 + error: 'param1 cannot be empty'
206 + };
207 + }
208 +
209 + // Process the request
210 + // This could throw various errors
211 + const result = await someExternalService(param1);
212 +
213 + return {
214 + data: { result },
215 + successful: true,
216 + error: null
217 + };
218 + } catch (error) {
219 + // Log the error for debugging
220 + console.error('Error in custom tool:', error);
221 +
222 + // Return a user-friendly error message
223 + return {
224 + data: {},
225 + successful: false,
226 + error: error.message || 'An unexpected error occurred'
227 + };
228 + }
229 + }
230 +});
231 +```
232 +
233 +## Best Practices
234 +
235 +1. **Always use try/catch blocks** when calling SDK methods
236 +2. **Check result.successful** after tool execution
237 +3. **Provide specific error handling** for different error types
238 +4. **Log detailed error information** for debugging
239 +5. **Present user-friendly error messages** in your application
240 +6. **Set appropriate timeouts** for operations like waitForConnection
241 +7. **Validate inputs** before calling SDK methods
242 +8. **Implement retry logic** for transient errors
\ No newline at end of file
docs/advanced/middleware.md new
+402
@@ -0,0 +1,402 @@
1 +# Middleware and 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 +## What are Modifiers?
6 +
7 +Modifiers are functions that intercept and modify the normal flow of tool operations. Composio supports three types of modifiers:
8 +
9 +1. **Schema Modifiers**: Transform a tool's schema before it's wrapped for the provider
10 +2. **Before Execution Modifiers**: Modify inputs before a tool is executed
11 +3. **After Execution Modifiers**: Transform outputs after a tool has executed
12 +
13 +### Schema Modifiers
14 +
15 +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.
16 +
17 +```typescript
18 +// Modify tool schema when getting tools
19 +const tools = await composio.tools.get(
20 + 'default',
21 + {
22 + toolkits: ['github'],
23 + },
24 + {
25 + modifyToolSchema: (toolSlug, toolkitSlug, tool) => {
26 + // Add a prefix to all tool descriptions
27 + if (tool.description) {
28 + tool.description = `[Enhanced] ${tool.description}`;
29 + }
30 +
31 + // Modify parameters for a specific tool
32 + if (toolSlug === 'GITHUB_GET_REPO') {
33 + if (tool.inputParameters?.properties?.owner) {
34 + // Add more detailed description
35 + tool.inputParameters.properties.owner.description =
36 + 'GitHub organization or user name (e.g., "composio")';
37 + }
38 + }
39 +
40 + return tool;
41 + },
42 + }
43 +);
44 +```
45 +
46 +### Before Execution Modifiers
47 +
48 +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.
49 +
50 +```typescript
51 +// Modify parameters before execution
52 +const result = await composio.tools.execute(
53 + 'GITHUB_GET_REPO',
54 + {
55 + userId: 'default',
56 + arguments: {
57 + owner: 'composio',
58 + repo: 'sdk',
59 + },
60 + },
61 + {
62 + beforeToolExecute: (toolSlug, toolkitSlug, params) => {
63 + // Convert owner names to lowercase
64 + if (params.arguments.owner) {
65 + params.arguments.owner = params.arguments.owner.toLowerCase();
66 + }
67 +
68 + // Add a default branch parameter
69 + if (toolSlug === 'GITHUB_GET_REPO' && !params.arguments.branch) {
70 + params.arguments.branch = 'main';
71 + }
72 +
73 + // Add tracing for debugging
74 + console.log(`Executing ${toolSlug} from ${toolkitSlug} toolkit`);
75 +
76 + return params;
77 + },
78 + }
79 +);
80 +```
81 +
82 +### After Execution Modifiers
83 +
84 +After execution modifiers allow you to transform the output after a tool has executed. This is useful for data formatting, filtering, or enrichment.
85 +
86 +```typescript
87 +// Modify results after execution
88 +const result = await composio.tools.execute(
89 + 'GITHUB_GET_REPO',
90 + {
91 + userId: 'default',
92 + arguments: {
93 + owner: 'composio',
94 + repo: 'sdk',
95 + },
96 + },
97 + {
98 + afterToolExecute: (toolSlug, toolkitSlug, result) => {
99 + // Only when execution was successful
100 + if (result.successful) {
101 + // Filter out sensitive data
102 + if (result.data.token) {
103 + delete result.data.token;
104 + }
105 +
106 + // Add a timestamp
107 + result.data.fetchedAt = new Date().toISOString();
108 +
109 + // Transform data formats
110 + if (result.data.created_at) {
111 + result.data.createdAt = new Date(result.data.created_at).toLocaleString();
112 + delete result.data.created_at;
113 + }
114 + }
115 +
116 + return result;
117 + },
118 + }
119 +);
120 +```
121 +
122 +### Using Multiple Modifiers
123 +
124 +You can use all three types of modifiers together:
125 +
126 +```typescript
127 +const tools = await composio.tools.get(
128 + 'default',
129 + {
130 + toolkits: ['github'],
131 + },
132 + {
133 + // Schema modifier
134 + modifyToolSchema: (toolSlug, toolkitSlug, tool) => {
135 + // Enhance tool schema
136 + return tool;
137 + },
138 +
139 + // Before execution modifier
140 + beforeToolExecute: (toolSlug, toolkitSlug, params) => {
141 + // Modify execution parameters
142 + return params;
143 + },
144 +
145 + // After execution modifier
146 + afterToolExecute: (toolSlug, toolkitSlug, result) => {
147 + // Transform execution results
148 + return result;
149 + },
150 + }
151 +);
152 +```
153 +
154 +## Creating Reusable Modifiers
155 +
156 +For better code organization, you can create reusable modifier functions:
157 +
158 +```typescript
159 +// Define reusable modifiers
160 +const addTimestamps = (toolSlug, toolkitSlug, result) => {
161 + if (result.successful) {
162 + result.data.executedAt = new Date().toISOString();
163 + }
164 + return result;
165 +};
166 +
167 +const logExecutions = (toolSlug, toolkitSlug, params) => {
168 + console.log(`Executing ${toolSlug} from ${toolkitSlug} at ${new Date().toISOString()}`);
169 + return params;
170 +};
171 +
172 +const sanitizeInputs = (toolSlug, toolkitSlug, params) => {
173 + // Sanitize input parameters to prevent injection attacks
174 + if (params.arguments) {
175 + Object.keys(params.arguments).forEach(key => {
176 + if (typeof params.arguments[key] === 'string') {
177 + params.arguments[key] = sanitizeString(params.arguments[key]);
178 + }
179 + });
180 + }
181 + return params;
182 +};
183 +
184 +// Use the reusable modifiers
185 +const result = await composio.tools.execute(
186 + 'GITHUB_GET_REPO',
187 + {
188 + userId: 'default',
189 + arguments: {
190 + owner: 'composio',
191 + repo: 'sdk',
192 + },
193 + },
194 + {
195 + beforeToolExecute: sanitizeInputs,
196 + afterToolExecute: addTimestamps,
197 + }
198 +);
199 +```
200 +
201 +## Practical Use Cases
202 +
203 +### Caching Tool Results
204 +
205 +```typescript
206 +// Simple in-memory cache
207 +const cache = new Map();
208 +
209 +const cacheModifier = (toolSlug, toolkitSlug, params) => {
210 + // Create a cache key based on tool slug and arguments
211 + const cacheKey = `${toolSlug}-${JSON.stringify(params.arguments)}`;
212 +
213 + // Add cache key to params for the after modifier to use
214 + params.__cacheKey = cacheKey;
215 +
216 + // Check if we have a cached result
217 + if (cache.has(cacheKey)) {
218 + const cachedResult = cache.get(cacheKey);
219 + if (Date.now() - cachedResult.timestamp < 60000) {
220 + // 1 minute cache
221 + // Throw a special error to short-circuit execution
222 + throw { __cached: true, result: cachedResult.result };
223 + }
224 + }
225 +
226 + return params;
227 +};
228 +
229 +const cacheAfterModifier = (toolSlug, toolkitSlug, result) => {
230 + if (result.successful && result.__cacheKey) {
231 + // Store in cache
232 + cache.set(result.__cacheKey, {
233 + result,
234 + timestamp: Date.now(),
235 + });
236 +
237 + // Remove the cache key from the result
238 + delete result.__cacheKey;
239 + }
240 +
241 + return result;
242 +};
243 +
244 +// Use with try/catch to handle the cache hit
245 +try {
246 + const result = await composio.tools.execute(
247 + 'GITHUB_GET_REPO',
248 + {
249 + userId: 'default',
250 + arguments: {
251 + owner: 'composio',
252 + repo: 'sdk',
253 + },
254 + },
255 + {
256 + beforeToolExecute: cacheModifier,
257 + afterToolExecute: cacheAfterModifier,
258 + }
259 + );
260 +
261 + console.log('Fresh result:', result);
262 +} catch (error) {
263 + if (error.__cached) {
264 + console.log('Cached result:', error.result);
265 + } else {
266 + throw error; // Re-throw if it's a real error
267 + }
268 +}
269 +```
270 +
271 +### Adding Authentication Headers
272 +
273 +```typescript
274 +const authModifier = (toolSlug, toolkitSlug, params) => {
275 + // Add authentication parameters for specific toolkits
276 + if (toolkitSlug === 'custom-api') {
277 + if (!params.customAuthParams) {
278 + params.customAuthParams = {};
279 + }
280 +
281 + if (!params.customAuthParams.parameters) {
282 + params.customAuthParams.parameters = [];
283 + }
284 +
285 + // Add an API key to the headers
286 + params.customAuthParams.parameters.push({
287 + in: 'header',
288 + name: 'X-API-Key',
289 + value: process.env.CUSTOM_API_KEY,
290 + });
291 + }
292 +
293 + return params;
294 +};
295 +
296 +// Apply the auth modifier to all tools from a specific toolkit
297 +const tools = await composio.tools.get(
298 + 'default',
299 + {
300 + toolkits: ['custom-api'],
301 + },
302 + {
303 + beforeToolExecute: authModifier,
304 + }
305 +);
306 +```
307 +
308 +### Data Transformation Pipeline
309 +
310 +```typescript
311 +// Create a pipeline of modifiers
312 +const pipeModifiers = (...modifiers) => {
313 + return (toolSlug, toolkitSlug, result) => {
314 + return modifiers.reduce((modifiedResult, modifier) => {
315 + return modifier(toolSlug, toolkitSlug, modifiedResult);
316 + }, result);
317 + };
318 +};
319 +
320 +// Individual transformation steps
321 +const addMetadata = (toolSlug, toolkitSlug, result) => {
322 + if (result.successful) {
323 + result.data.metadata = { source: toolkitSlug, tool: toolSlug };
324 + }
325 + return result;
326 +};
327 +
328 +const formatDates = (toolSlug, toolkitSlug, result) => {
329 + if (result.successful) {
330 + // Convert all dates to a consistent format
331 + Object.keys(result.data).forEach(key => {
332 + if (key.includes('date') || key.includes('time') || key.endsWith('At')) {
333 + if (result.data[key]) {
334 + result.data[key] = new Date(result.data[key]).toLocaleString();
335 + }
336 + }
337 + });
338 + }
339 + return result;
340 +};
341 +
342 +const removeNulls = (toolSlug, toolkitSlug, result) => {
343 + if (result.successful) {
344 + // Remove null and undefined values
345 + Object.keys(result.data).forEach(key => {
346 + if (result.data[key] === null || result.data[key] === undefined) {
347 + delete result.data[key];
348 + }
349 + });
350 + }
351 + return result;
352 +};
353 +
354 +// Apply the pipeline
355 +const result = await composio.tools.execute(
356 + 'GITHUB_GET_REPO',
357 + {
358 + userId: 'default',
359 + arguments: {
360 + owner: 'composio',
361 + repo: 'sdk',
362 + },
363 + },
364 + {
365 + afterToolExecute: pipeModifiers(addMetadata, formatDates, removeNulls),
366 + }
367 +);
368 +```
369 +
370 +## Type Definitions
371 +
372 +```typescript
373 +// Schema Modifier
374 +type TransformToolSchemaModifier = (toolSlug: string, toolkitSlug: string, tool: Tool) => Tool;
375 +
376 +// Before Execution Modifier
377 +type BeforeToolExecuteModifier = (
378 + toolSlug: string,
379 + toolkitSlug: string,
380 + params: ToolExecuteParams
381 +) => ToolExecuteParams;
382 +
383 +// After Execution Modifier
384 +type AfterToolExecuteModifier = (
385 + toolSlug: string,
386 + toolkitSlug: string,
387 + result: ToolExecuteResponse
388 +) => ToolExecuteResponse;
389 +
390 +// Modifiers Object
391 +interface ExecuteToolModifiers {
392 + beforeToolExecute?: BeforeToolExecuteModifier;
393 + afterToolExecute?: AfterToolExecuteModifier;
394 +}
395 +
396 +// Provider Options (includes schema modifier)
397 +interface ProviderOptions<TProvider> {
398 + modifyToolSchema?: TransformToolSchemaModifier;
399 + beforeToolExecute?: BeforeToolExecuteModifier;
400 + afterToolExecute?: AfterToolExecuteModifier;
401 +}
402 +```
docs/advanced/telemetry.md new
+238
@@ -0,0 +1,238 @@
1 +# Telemetry in Composio SDK
2 +
3 +Composio SDK includes a telemetry system to help improve the SDK and provide insights into usage patterns. This guide explains how telemetry works, what data is collected, how to customize it, and how to disable it if needed.
4 +
5 +## Overview
6 +
7 +The telemetry system in Composio SDK is:
8 +
9 +- **Opt-out**: Enabled by default but can be disabled
10 +- **Privacy-focused**: Does not collect personal or sensitive information
11 +- **Transparent**: Clear about what data is collected
12 +- **Configurable**: Custom transports can be provided
13 +
14 +## Telemetry Data
15 +
16 +The telemetry system collects the following types of data:
17 +
18 +- **SDK Usage**: API calls, method invocations, error counts
19 +- **Performance Metrics**: Response times, success/failure rates
20 +- **Environment Information**: SDK version, provider used, runtime context
21 +
22 +No personal or sensitive information such as:
23 +- API keys
24 +- Tool arguments
25 +- Tool responses
26 +- User IDs
27 +- Connected account details
28 +
29 +## Disabling Telemetry
30 +
31 +You can disable telemetry when initializing the SDK:
32 +
33 +```typescript
34 +import { Composio } from '@composio/sdk';
35 +
36 +const composio = new Composio({
37 + apiKey: 'your-api-key',
38 + allowTracking: false, // Disable telemetry
39 +});
40 +```
41 +
42 +Or by setting an environment variable:
43 +
44 +```bash
45 +# In your .env file or environment
46 +COMPOSIO_DISABLE_TELEMETRY=true
47 +```
48 +
49 +## Custom Telemetry Transport
50 +
51 +For advanced use cases, you can provide a custom telemetry transport to process the telemetry data according to your needs:
52 +
53 +```typescript
54 +import { Composio, BaseTelemetryTransport, TelemetryEvent } from '@composio/sdk';
55 +
56 +// Create a custom telemetry transport
57 +class CustomTelemetryTransport extends BaseTelemetryTransport {
58 + async send(event: TelemetryEvent): Promise<void> {
59 + // Process the telemetry event
60 + console.log(`Telemetry event: ${event.name}`, event.properties);
61 +
62 + // You can send it to your own analytics system
63 + await yourAnalyticsSystem.track(event.name, event.properties);
64 + }
65 +
66 + async flush(): Promise<void> {
67 + // Clean up any pending events
68 + await yourAnalyticsSystem.flush();
69 + }
70 +}
71 +
72 +// Use the custom transport
73 +const composio = new Composio({
74 + apiKey: 'your-api-key',
75 + telemetryTransport: new CustomTelemetryTransport(),
76 +});
77 +```
78 +
79 +## Implementing a Custom Transport
80 +
81 +To implement a custom telemetry transport, extend the `BaseTelemetryTransport` class:
82 +
83 +```typescript
84 +import { BaseTelemetryTransport, TelemetryEvent } from '@composio/sdk';
85 +
86 +export class CustomTelemetryTransport extends BaseTelemetryTransport {
87 + // Optional constructor for configuration
88 + constructor(private config: { endpoint: string, batchSize: number }) {
89 + super();
90 + this.events = [];
91 + }
92 +
93 + // Local state for batching events
94 + private events: TelemetryEvent[];
95 +
96 + // Required: Implement the send method
97 + async send(event: TelemetryEvent): Promise<void> {
98 + // Add the event to the batch
99 + this.events.push(event);
100 +
101 + // If batch is full, flush it
102 + if (this.events.length >= this.config.batchSize) {
103 + await this.flush();
104 + }
105 + }
106 +
107 + // Required: Implement the flush method
108 + async flush(): Promise<void> {
109 + if (this.events.length === 0) {
110 + return;
111 + }
112 +
113 + try {
114 + // Send the batch to your endpoint
115 + await fetch(this.config.endpoint, {
116 + method: 'POST',
117 + headers: {
118 + 'Content-Type': 'application/json',
119 + },
120 + body: JSON.stringify({
121 + events: this.events,
122 + timestamp: new Date().toISOString(),
123 + }),
124 + });
125 +
126 + // Clear the batch
127 + this.events = [];
128 + } catch (error) {
129 + console.error('Failed to send telemetry:', error);
130 + }
131 + }
132 +}
133 +```
134 +
135 +## Telemetry Events
136 +
137 +The telemetry system instruments various parts of the SDK and emits events for different operations:
138 +
139 +### SDK Initialization
140 +
141 +```
142 +event: "sdk_initialized"
143 +properties:
144 + framework: string // The provider name
145 + isAgentic: boolean // Whether the provider is agentic
146 + source: string // The runtime environment ("node" or "browser")
147 + version: string // The SDK version
148 + isBrowser: boolean // Whether the SDK is running in a browser
149 +```
150 +
151 +### Tool Operations
152 +
153 +```
154 +event: "tools_get"
155 +properties:
156 + toolkit_slugs: string[] // The toolkit slugs used in the filter
157 + tool_count: number // The number of tools returned
158 + provider: string // The provider name
159 +
160 +event: "tool_execute"
161 +properties:
162 + tool_slug: string // The slug of the executed tool
163 + toolkit_slug: string // The toolkit slug of the executed tool
164 + success: boolean // Whether the execution was successful
165 + duration_ms: number // The execution duration in milliseconds
166 + provider: string // The provider name
167 +```
168 +
169 +### Connected Account Operations
170 +
171 +```
172 +event: "connected_account_initiate"
173 +properties:
174 + toolkit_slug: string // The toolkit slug
175 + auth_config_id: string // The auth config ID
176 +
177 +event: "connected_account_get"
178 +properties:
179 + success: boolean // Whether the operation was successful
180 +
181 +event: "connected_account_list"
182 +properties:
183 + count: number // The number of connected accounts returned
184 + success: boolean // Whether the operation was successful
185 +```
186 +
187 +### Toolkit Operations
188 +
189 +```
190 +event: "toolkit_get"
191 +properties:
192 + success: boolean // Whether the operation was successful
193 + toolkit_slug: string // The toolkit slug (if getting a specific toolkit)
194 + toolkits_count: number // The number of toolkits returned (if getting multiple)
195 +```
196 +
197 +## Telemetry Processor
198 +
199 +The SDK includes a batch processor for telemetry events that:
200 +
201 +1. Buffers events to reduce API calls
202 +2. Sends events in batches
203 +3. Handles retries and failures
204 +4. Automatically flushes at regular intervals
205 +
206 +This ensures that telemetry doesn't impact application performance.
207 +
208 +## Environment Context
209 +
210 +The telemetry system automatically includes environment context with each event:
211 +
212 +```typescript
213 +interface TelemetryMetadata {
214 + apiKey: string; // The Composio API key (first 8 chars only, for identification)
215 + baseUrl: string; // The Composio API base URL
216 + framework: string; // The provider name
217 + isAgentic: boolean; // Whether the provider is agentic
218 + source: string; // The runtime environment
219 + version: string; // The SDK version
220 + isBrowser: boolean; // Whether the SDK is running in a browser
221 + sessionId: string; // A random session ID (changes each init)
222 +}
223 +```
224 +
225 +## Browser vs Node.js
226 +
227 +The SDK automatically detects whether it's running in a browser or Node.js environment and uses the appropriate transport mechanism:
228 +
229 +- In Node.js: Uses ProcessTransport with HTTP requests
230 +- In Browser: Uses BrowserTransport with more browser-friendly approaches
231 +
232 +## Best Practices
233 +
234 +1. **Leave telemetry enabled** if possible to help improve the SDK
235 +2. If you need to **disable telemetry** for compliance reasons, use the `allowTracking: false` option
236 +3. If you want to **process telemetry locally**, implement a custom transport
237 +4. **Never log sensitive data** in your custom transports
238 +5. If you **implement a custom provider**, set a meaningful name to improve telemetry insights
\ No newline at end of file
docs/api/auth-configs.md new
+200
@@ -0,0 +1,200 @@
1 +# Auth Configs API
2 +
3 +The `AuthConfigs` class provides methods to manage authentication configurations for toolkits. Auth configs define how authentication works for a particular toolkit, specifying the auth scheme (OAuth2, API Key, etc.) and other authentication-related details.
4 +
5 +## Methods
6 +
7 +### list(query?)
8 +
9 +Lists all auth configs based on provided filter criteria.
10 +
11 +```typescript
12 +// List all auth configs
13 +const allAuthConfigs = await composio.authConfigs.list();
14 +
15 +// List auth configs for a specific toolkit
16 +const githubAuthConfigs = await composio.authConfigs.list({
17 + toolkitSlug: 'github'
18 +});
19 +```
20 +
21 +**Parameters:**
22 +
23 +- `query` (AuthConfigListParams): Optional query parameters for filtering auth configs
24 +
25 +**Returns:** Promise<AuthConfigListResponse> - A paginated list of auth configs
26 +
27 +**Throws:** ValidationError if the query fails validation against the expected schema
28 +
29 +### get(id)
30 +
31 +Retrieves a specific auth config by its ID.
32 +
33 +```typescript
34 +// Get an auth config by ID
35 +const authConfig = await composio.authConfigs.get('auth_config_123');
36 +console.log(authConfig.name); // Name of the auth config
37 +```
38 +
39 +**Parameters:**
40 +
41 +- `id` (string): The unique identifier of the auth config
42 +
43 +**Returns:** Promise<AuthConfigRetrieveResponse> - The auth config details
44 +
45 +**Throws:** ComposioAuthConfigNotFoundError if the auth config cannot be found
46 +
47 +### create(toolkitSlug, data)
48 +
49 +Creates a new auth config for a toolkit.
50 +
51 +```typescript
52 +// Create an auth config for GitHub
53 +const authConfig = await composio.authConfigs.create('github', {
54 + type: 'use_composio_managed_auth',
55 + name: 'GitHub Auth Config',
56 +});
57 +```
58 +
59 +**Parameters:**
60 +
61 +- `toolkitSlug` (string): The slug of the toolkit to create an auth config for
62 +- `data` (AuthConfigCreateParams): The parameters for creating the auth config
63 +
64 +**Returns:** Promise<AuthConfigCreateResponse> - The created auth config
65 +
66 +**Throws:**
67 +- ValidationError if the parameters fail validation
68 +- ComposioToolNotFoundError if the toolkit cannot be found
69 +
70 +### update(id, data)
71 +
72 +Updates an existing auth config.
73 +
74 +```typescript
75 +// Update an auth config
76 +const updatedAuthConfig = await composio.authConfigs.update('auth_config_123', {
77 + name: 'Updated GitHub Auth Config',
78 + fields: {
79 + client_id: 'new_client_id',
80 + client_secret: 'new_client_secret',
81 + },
82 +});
83 +```
84 +
85 +**Parameters:**
86 +
87 +- `id` (string): The unique identifier of the auth config to update
88 +- `data` (AuthConfigUpdateParams): The parameters for updating the auth config
89 +
90 +**Returns:** Promise<AuthConfigUpdateResponse> - The updated auth config
91 +
92 +**Throws:** ComposioAuthConfigNotFoundError if the auth config cannot be found
93 +
94 +### delete(id)
95 +
96 +Deletes an auth config.
97 +
98 +```typescript
99 +// Delete an auth config
100 +await composio.authConfigs.delete('auth_config_123');
101 +```
102 +
103 +**Parameters:**
104 +
105 +- `id` (string): The unique identifier of the auth config to delete
106 +
107 +**Returns:** Promise<AuthConfigDeleteResponse> - The deletion response
108 +
109 +**Throws:** Error if the auth config doesn't exist or cannot be deleted
110 +
111 +## Types
112 +
113 +### AuthConfigListParams
114 +
115 +```typescript
116 +interface AuthConfigListParams {
117 + cursor?: string; // Pagination cursor
118 + limit?: number; // Limit the number of results
119 + orderBy?: string; // Order by field
120 + toolkitSlug?: string; // Filter by toolkit slug
121 +}
122 +```
123 +
124 +### AuthConfigListResponse
125 +
126 +```typescript
127 +interface AuthConfigListResponse {
128 + items: AuthConfigRetrieveResponse[]; // List of auth configs
129 + nextCursor: string | null; // Pagination cursor
130 + totalPages: number; // Total number of pages
131 +}
132 +```
133 +
134 +### AuthConfigRetrieveResponse
135 +
136 +```typescript
137 +interface AuthConfigRetrieveResponse {
138 + id: string; // Auth config ID
139 + name: string; // Name of the auth config
140 + type: AuthConfigType; // Type of auth config
141 + toolkit: { // Associated toolkit
142 + id: string; // Toolkit ID
143 + slug: string; // Toolkit slug
144 + name: string; // Toolkit name
145 + };
146 + authScheme: AuthSchemeType; // Auth scheme (e.g., 'oauth2', 'api_key')
147 + isDisabled: boolean; // Whether the auth config is disabled
148 + fields: Record<string, unknown>; // Configuration fields
149 + meta: Record<string, unknown>; // Additional metadata
150 + createdAt: string; // Creation timestamp
151 + updatedAt: string; // Last update timestamp
152 +}
153 +```
154 +
155 +### AuthConfigCreateParams
156 +
157 +```typescript
158 +interface AuthConfigCreateParams {
159 + type: AuthConfigType; // Type of auth config
160 + name: string; // Name of the auth config
161 + fields?: Record<string, unknown>; // Configuration fields
162 +}
163 +```
164 +
165 +### AuthConfigUpdateParams
166 +
167 +```typescript
168 +interface AuthConfigUpdateParams {
169 + name?: string; // Name of the auth config
170 + fields?: Record<string, unknown>; // Configuration fields
171 +}
172 +```
173 +
174 +### AuthConfigType
175 +
176 +Auth config types are defined as an enum:
177 +
178 +```typescript
179 +enum AuthConfigTypes {
180 + USE_COMPOSIO_MANAGED_AUTH = 'use_composio_managed_auth',
181 + SERVICE_CONNECTION = 'service_connection',
182 + USER_CREDENTIALS = 'user_credentials',
183 + CUSTOM_AUTH = 'custom_auth',
184 + NO_AUTH = 'no_auth',
185 +}
186 +```
187 +
188 +### AuthSchemeType
189 +
190 +Auth scheme types are defined as an enum:
191 +
192 +```typescript
193 +enum AuthSchemeTypes {
194 + OAUTH2 = 'oauth2',
195 + API_KEY = 'api_key',
196 + BASIC_AUTH = 'basic_auth',
197 + CUSTOM = 'custom',
198 + NO_AUTH = 'no_auth',
199 +}
200 +```
\ No newline at end of file
docs/api/composio.md new
+93
@@ -0,0 +1,93 @@
1 +# Composio Class
2 +
3 +The `Composio` class is the main entry point to the Composio SDK. It initializes the SDK and provides access to all the core functionality.
4 +
5 +## Initialization
6 +
7 +```typescript
8 +import { Composio } from '@composio/sdk';
9 +
10 +const composio = new Composio({
11 + apiKey: 'your-api-key',
12 + baseURL: 'https://api.composio.dev', // Optional: Custom API endpoint
13 + allowTracking: true, // Optional: Enable/disable telemetry
14 + allowTracing: true, // Optional: Enable/disable tracing
15 + provider: new OpenAIProvider(), // Optional: Custom provider
16 + telemetryTransport: customTransport, // Optional: Custom telemetry transport
17 +});
18 +```
19 +
20 +## Configuration Options
21 +
22 +The `Composio` constructor accepts a configuration object with the following properties:
23 +
24 +| Property | Type | Required | Default | Description |
25 +|----------|------|----------|---------|-------------|
26 +| `apiKey` | string | Yes | - | Your Composio API key |
27 +| `baseURL` | string | No | `https://api.composio.dev` | The base URL for the Composio API |
28 +| `allowTracking` | boolean | No | `true` | Whether to allow analytics/tracking |
29 +| `allowTracing` | boolean | No | `true` | Whether to allow tracing |
30 +| `provider` | `BaseComposioProvider` | No | `new OpenAIProvider()` | The provider to use for this Composio instance |
31 +| `telemetryTransport` | `BaseTelemetryTransport` | No | - | Custom transport for telemetry data |
32 +
33 +## Properties
34 +
35 +The `Composio` class provides access to the following core models:
36 +
37 +| Property | Type | Description |
38 +|----------|------|-------------|
39 +| `tools` | `Tools` | Access to tools functionality |
40 +| `toolkits` | `Toolkits` | Access to toolkits functionality |
41 +| `triggers` | `Triggers` | Access to triggers functionality |
42 +| `authConfigs` | `AuthConfigs` | Access to auth configs functionality |
43 +| `connectedAccounts` | `ConnectedAccounts` | Access to connected accounts functionality |
44 +| `provider` | `BaseComposioProvider` | The provider being used |
45 +
46 +## Methods
47 +
48 +### getClient()
49 +
50 +Returns the internal Composio API client.
51 +
52 +```typescript
53 +const client = composio.getClient();
54 +```
55 +
56 +**Returns:** `ComposioClient`
57 +
58 +**Throws:** Error if the client is not initialized
59 +
60 +## Examples
61 +
62 +### Basic Initialization
63 +
64 +```typescript
65 +import { Composio } from '@composio/sdk';
66 +
67 +const composio = new Composio({
68 + apiKey: process.env.COMPOSIO_API_KEY,
69 +});
70 +```
71 +
72 +### Custom Provider
73 +
74 +```typescript
75 +import { Composio, OpenAIProvider } from '@composio/sdk';
76 +
77 +const openaiProvider = new OpenAIProvider();
78 +const composio = new Composio({
79 + apiKey: process.env.COMPOSIO_API_KEY,
80 + provider: openaiProvider,
81 +});
82 +```
83 +
84 +### Disable Tracking
85 +
86 +```typescript
87 +import { Composio } from '@composio/sdk';
88 +
89 +const composio = new Composio({
90 + apiKey: process.env.COMPOSIO_API_KEY,
91 + allowTracking: false,
92 +});
93 +```
\ No newline at end of file
docs/api/connected-accounts.md new
+258
@@ -0,0 +1,258 @@
1 +# Connected Accounts API
2 +
3 +The `ConnectedAccounts` class provides methods to manage user connections to external services (toolkits). Connected accounts store authentication tokens and other information needed to access these services.
4 +
5 +## Methods
6 +
7 +### list(query?)
8 +
9 +Lists all connected accounts based on provided filter criteria.
10 +
11 +```typescript
12 +// List all connected accounts
13 +const allAccounts = await composio.connectedAccounts.list();
14 +
15 +// List accounts for a specific user
16 +const userAccounts = await composio.connectedAccounts.list({
17 + userIds: ['user123'],
18 +});
19 +
20 +// List accounts for a specific toolkit
21 +const githubAccounts = await composio.connectedAccounts.list({
22 + toolkitSlugs: ['github'],
23 +});
24 +```
25 +
26 +**Parameters:**
27 +
28 +- `query` (ConnectedAccountListParams): Optional query parameters for filtering connected accounts
29 +
30 +**Returns:** Promise<ConnectedAccountListResponse> - A paginated list of connected accounts
31 +
32 +**Throws:** ValidationError if the query fails validation against the expected schema
33 +
34 +### initiate(userId, authConfigId, options?)
35 +
36 +Creates a new connected account and returns a connection request. Users can then wait for the connection to be established using the `waitForConnection` method.
37 +
38 +```typescript
39 +const connectionRequest = await composio.connectedAccounts.initiate('user_123', 'auth_config_123', {
40 + data: {
41 + name: 'My GitHub Account',
42 + },
43 + callbackUrl: 'https://myapp.com/auth/callback',
44 +});
45 +
46 +// The redirectUrl is where the user should be redirected to authenticate
47 +console.log(connectionRequest.redirectUrl);
48 +
49 +// wait for the user to connected the acocunt
50 +const connectedAccount = await connectionRequest.waitForConnection();
51 +```
52 +
53 +**Parameters:**
54 +
55 +- `userId` (string): User ID of the connected account
56 +- `authConfigId` (string): Auth config ID of the connected account
57 +- `options` (CreateConnectedAccountOptions): Data for creating a new connected account
58 +
59 +**Returns:** Promise<ConnectionRequest> - Connection request object
60 +
61 +### waitForConnection(connectedAccountId, timeout?)
62 +
63 +Waits for a connection request to complete and become active.
64 +
65 +```typescript
66 +// Wait for a connection to complete with default timeout
67 +const connectedAccount = await composio.connectedAccounts.waitForConnection('conn_123abc');
68 +
69 +// Wait with a custom timeout of 2 minutes
70 +const connectedAccount = await composio.connectedAccounts.waitForConnection('conn_123abc', 120000);
71 +```
72 +
73 +**Parameters:**
74 +
75 +- `connectedAccountId` (string): The ID of the connected account to wait for
76 +- `timeout` (number): Maximum time to wait in milliseconds (default: 60 seconds)
77 +
78 +**Returns:** Promise<ConnectedAccountRetrieveResponse> - The finalized connected account data
79 +
80 +**Throws:**
81 +
82 +- `ComposioConnectedAccountNotFoundError`: If the connected account cannot be found
83 +- `ConnectionRequestFailedError`: If the connection enters a failed, expired, or deleted state
84 +- `ConnectionRequestTimeoutError`: If the connection does not complete within the timeout period
85 +
86 +### get(nanoid)
87 +
88 +Retrieves a specific connected account by its ID.
89 +
90 +```typescript
91 +// Get a connected account by ID
92 +const account = await composio.connectedAccounts.get('conn_abc123');
93 +console.log(account.status); // e.g., 'ACTIVE'
94 +console.log(account.toolkit.slug); // e.g., 'github'
95 +```
96 +
97 +**Parameters:**
98 +
99 +- `nanoid` (string): The unique identifier of the connected account
100 +
101 +**Returns:** Promise<ConnectedAccountRetrieveResponse> - The connected account details
102 +
103 +**Throws:** Error if the connected account cannot be found or an API error occurs
104 +
105 +### delete(nanoid)
106 +
107 +Deletes a connected account.
108 +
109 +```typescript
110 +// Delete a connected account
111 +await composio.connectedAccounts.delete('conn_abc123');
112 +```
113 +
114 +**Parameters:**
115 +
116 +- `nanoid` (string): The unique identifier of the connected account to delete
117 +
118 +**Returns:** Promise<ConnectedAccountDeleteResponse> - The deletion response
119 +
120 +**Throws:** Error if the account doesn't exist or cannot be deleted
121 +
122 +### refresh(nanoid)
123 +
124 +Refreshes a connected account's authentication credentials.
125 +
126 +```typescript
127 +// Refresh a connected account's credentials
128 +const refreshedAccount = await composio.connectedAccounts.refresh('conn_abc123');
129 +```
130 +
131 +**Parameters:**
132 +
133 +- `nanoid` (string): The unique identifier of the connected account to refresh
134 +
135 +**Returns:** Promise<ConnectedAccountRefreshResponse> - The response containing the refreshed account details
136 +
137 +**Throws:** Error if the account doesn't exist or credentials cannot be refreshed
138 +
139 +### updateStatus(nanoid, params)
140 +
141 +Updates the status of a connected account.
142 +
143 +```typescript
144 +// Update the status of a connected account
145 +const updatedAccount = await composio.connectedAccounts.updateStatus('conn_abc123', {
146 + enabled: true,
147 +});
148 +```
149 +
150 +**Parameters:**
151 +
152 +- `nanoid` (string): The unique identifier of the connected account
153 +- `params` (ConnectedAccountUpdateStatusParams): The parameters for updating the status
154 +
155 +**Returns:** Promise<ConnectedAccountUpdateStatusResponse> - The updated account details
156 +
157 +### enable(nanoid)
158 +
159 +Enables a connected account.
160 +
161 +```typescript
162 +// Enable a connected account
163 +const enabledAccount = await composio.connectedAccounts.enable('conn_abc123');
164 +```
165 +
166 +**Parameters:**
167 +
168 +- `nanoid` (string): The unique identifier of the connected account
169 +
170 +**Returns:** Promise<ConnectedAccountUpdateStatusResponse> - The updated account details
171 +
172 +### disable(nanoid)
173 +
174 +Disables a connected account.
175 +
176 +```typescript
177 +// Disable a connected account
178 +const disabledAccount = await composio.connectedAccounts.disable('conn_abc123');
179 +```
180 +
181 +**Parameters:**
182 +
183 +- `nanoid` (string): The unique identifier of the connected account
184 +
185 +**Returns:** Promise<ConnectedAccountUpdateStatusResponse> - The updated account details
186 +
187 +## Types
188 +
189 +### ConnectedAccountListParams
190 +
191 +```typescript
192 +interface ConnectedAccountListParams {
193 + authConfigIds?: string[]; // Filter by auth config IDs
194 + cursor?: string; // Pagination cursor
195 + labels?: string[]; // Filter by labels
196 + limit?: number; // Limit the number of results
197 + orderBy?: string; // Order by field
198 + statuses?: string[]; // Filter by statuses
199 + toolkitSlugs?: string[]; // Filter by toolkit slugs
200 + userIds?: string[]; // Filter by user IDs
201 +}
202 +```
203 +
204 +### ConnectedAccountListResponse
205 +
206 +```typescript
207 +interface ConnectedAccountListResponse {
208 + items: ConnectedAccountRetrieveResponse[]; // List of connected accounts
209 + nextCursor: string | null; // Pagination cursor
210 + totalPages: number; // Total number of pages
211 +}
212 +```
213 +
214 +### ConnectedAccountRetrieveResponse
215 +
216 +```typescript
217 +interface ConnectedAccountRetrieveResponse {
218 + id: string; // Connected account ID
219 + status: string; // Status (e.g., 'ACTIVE', 'PENDING')
220 + statusReason: string | null; // Reason for the status
221 + userId: string; // User ID
222 + toolkit: {
223 + // Associated toolkit
224 + id: string; // Toolkit ID
225 + slug: string; // Toolkit slug
226 + name: string; // Toolkit name
227 + };
228 + authConfig: {
229 + // Associated auth config
230 + id: string; // Auth config ID
231 + authScheme: string; // Auth scheme (e.g., 'oauth2')
232 + isComposioManaged: boolean; // Whether it's managed by Composio
233 + isDisabled: boolean; // Whether it's disabled
234 + };
235 + isDisabled: boolean; // Whether the connected account is disabled
236 + meta: Record<string, unknown>; // Additional metadata
237 + createdAt: string; // Creation timestamp
238 + updatedAt: string; // Last update timestamp
239 + testRequestEndpoint: string | null; // Endpoint for testing the connection
240 +}
241 +```
242 +
243 +### CreateConnectedAccountOptions
244 +
245 +```typescript
246 +interface CreateConnectedAccountOptions {
247 + data?: Record<string, unknown>; // Additional data for the connection
248 + callbackUrl?: string; // URL to redirect after authentication
249 +}
250 +```
251 +
252 +### ConnectedAccountUpdateStatusParams
253 +
254 +```typescript
255 +interface ConnectedAccountUpdateStatusParams {
256 + enabled: boolean; // Whether the account should be enabled
257 +}
258 +```
docs/api/custom-tools.md new
+279
@@ -0,0 +1,279 @@
1 +# Custom Tools API
2 +
3 +Custom Tools allow you to extend Composio's functionality by creating your own tools with custom logic. These tools can be used alongside the built-in tools provided by Composio.
4 +
5 +## Creating Custom Tools
6 +
7 +You can create custom tools using the `createCustomTool` method of the `Tools` class:
8 +
9 +```typescript
10 +const customTool = await composio.tools.createCustomTool({
11 + name: 'My Custom Tool',
12 + description: 'A custom tool that does something specific',
13 + slug: 'MY_CUSTOM_TOOL',
14 + inputParameters: {
15 + type: 'object',
16 + properties: {
17 + param1: {
18 + type: 'string',
19 + description: 'First parameter',
20 + },
21 + param2: {
22 + type: 'number',
23 + description: 'Second parameter',
24 + }
25 + },
26 + required: ['param1']
27 + },
28 + outputParameters: {
29 + type: 'object',
30 + properties: {
31 + result: {
32 + type: 'string',
33 + description: 'The result of the operation'
34 + }
35 + }
36 + },
37 + handler: async (params, context) => {
38 + // Custom logic here
39 + const { param1, param2 } = params.arguments;
40 +
41 + // Return a successful response
42 + return {
43 + data: {
44 + result: `Processed ${param1} with value ${param2}`
45 + },
46 + successful: true,
47 + error: null
48 + };
49 + }
50 +});
51 +```
52 +
53 +## Custom Tool Options
54 +
55 +When creating a custom tool, you need to specify the following options:
56 +
57 +| Property | Type | Required | Description |
58 +|----------|------|----------|-------------|
59 +| `name` | string | Yes | The name of the custom tool |
60 +| `description` | string | Yes | A description of what the tool does |
61 +| `slug` | string | Yes | A unique identifier for the tool (usually uppercase with underscores) |
62 +| `inputParameters` | JSONSchema | Yes | The JSON Schema defining the input parameters |
63 +| `outputParameters` | JSONSchema | No | The JSON Schema defining the output parameters |
64 +| `handler` | function | Yes | The function that implements the tool's logic |
65 +
66 +## Handler Function
67 +
68 +The handler function is where you implement the custom tool's logic. It receives the following parameters:
69 +
70 +1. `params`: The parameters passed to the tool, including:
71 + - `arguments`: The input arguments as defined in `inputParameters`
72 + - `userId`: The ID of the user executing the tool
73 + - `connectedAccountId`: (optional) The ID of the connected account to use
74 + - Additional properties as defined in `ToolExecuteParams`
75 +
76 +2. `context`: Execution metadata, including:
77 + - `userId`: The ID of the user executing the tool
78 + - `connectedAccountId`: (optional) The ID of the connected account being used
79 +
80 +The handler must return a `ToolExecuteResponse` object with the following structure:
81 +
82 +```typescript
83 +{
84 + data: Record<string, unknown>, // The output data matching the outputParameters schema
85 + error: string | null, // Error message (if any)
86 + successful: boolean, // Whether the execution was successful
87 + logId?: string, // Optional log ID for debugging
88 + sessionInfo?: unknown // Optional session information
89 +}
90 +```
91 +
92 +## JSON Schema for Parameters
93 +
94 +Both `inputParameters` and `outputParameters` should be defined using JSON Schema:
95 +
96 +```typescript
97 +const inputParametersSchema = {
98 + type: 'object',
99 + properties: {
100 + query: {
101 + type: 'string',
102 + description: 'The search query'
103 + },
104 + limit: {
105 + type: 'integer',
106 + description: 'Maximum number of results',
107 + default: 10
108 + }
109 + },
110 + required: ['query']
111 +};
112 +
113 +const outputParametersSchema = {
114 + type: 'object',
115 + properties: {
116 + results: {
117 + type: 'array',
118 + items: {
119 + type: 'object',
120 + properties: {
121 + title: { type: 'string' },
122 + url: { type: 'string' }
123 + }
124 + },
125 + description: 'Search results'
126 + },
127 + totalCount: {
128 + type: 'integer',
129 + description: 'Total number of results found'
130 + }
131 + }
132 +};
133 +```
134 +
135 +## Error Handling in Custom Tools
136 +
137 +Your handler function should handle errors gracefully:
138 +
139 +```typescript
140 +handler: async (params, context) => {
141 + try {
142 + // Custom logic here
143 + const { query, limit = 10 } = params.arguments;
144 +
145 + // Simulate an API call
146 + const results = await searchApi(query, limit);
147 +
148 + return {
149 + data: {
150 + results,
151 + totalCount: results.length
152 + },
153 + successful: true,
154 + error: null
155 + };
156 + } catch (error) {
157 + // Handle errors
158 + return {
159 + data: {},
160 + successful: false,
161 + error: error.message || 'An error occurred during tool execution'
162 + };
163 + }
164 +}
165 +```
166 +
167 +## Using Connected Accounts in Custom Tools
168 +
169 +You can use connected accounts in your custom tools to access authenticated services:
170 +
171 +```typescript
172 +handler: async (params, context) => {
173 + const { userId, connectedAccountId } = context;
174 +
175 + if (!connectedAccountId) {
176 + return {
177 + data: {},
178 + successful: false,
179 + error: 'No connected account provided'
180 + };
181 + }
182 +
183 + try {
184 + // Get the connected account details
185 + const connectedAccount = await composio.connectedAccounts.get(connectedAccountId);
186 +
187 + // Use the authentication tokens
188 + const accessToken = connectedAccount.meta.access_token;
189 +
190 + // Make authenticated API calls
191 + const apiResult = await callExternalApi(accessToken, params.arguments);
192 +
193 + return {
194 + data: apiResult,
195 + successful: true,
196 + error: null
197 + };
198 + } catch (error) {
199 + return {
200 + data: {},
201 + successful: false,
202 + error: error.message
203 + };
204 + }
205 +}
206 +```
207 +
208 +## Accessing Custom Tools
209 +
210 +Once created, custom tools can be accessed just like built-in tools:
211 +
212 +```typescript
213 +// Get the custom tool
214 +const tool = await composio.tools.get('default', 'MY_CUSTOM_TOOL');
215 +
216 +// Execute the custom tool
217 +const result = await composio.tools.execute('MY_CUSTOM_TOOL', {
218 + userId: 'default',
219 + arguments: {
220 + param1: 'value1',
221 + param2: 42
222 + }
223 +});
224 +
225 +console.log(result.data); // { result: "Processed value1 with value 42" }
226 +```
227 +
228 +## Types
229 +
230 +### CustomToolOptions
231 +
232 +```typescript
233 +interface CustomToolOptions {
234 + name: string;
235 + description: string;
236 + slug: string;
237 + inputParameters: JSONSchema;
238 + outputParameters?: JSONSchema;
239 + handler: (
240 + params: ToolExecuteParams,
241 + context: ExecuteMetadata
242 + ) => Promise<ToolExecuteResponse>;
243 +}
244 +```
245 +
246 +### ExecuteMetadata
247 +
248 +```typescript
249 +interface ExecuteMetadata {
250 + userId: string;
251 + connectedAccountId?: string;
252 +}
253 +```
254 +
255 +### ToolExecuteParams
256 +
257 +```typescript
258 +interface ToolExecuteParams {
259 + allowTracing?: boolean;
260 + connectedAccountId?: string;
261 + customAuthParams?: CustomAuthParams;
262 + arguments: Record<string, unknown>;
263 + userId: string;
264 + version?: string;
265 + text?: string;
266 +}
267 +```
268 +
269 +### ToolExecuteResponse
270 +
271 +```typescript
272 +interface ToolExecuteResponse {
273 + data: Record<string, unknown>;
274 + error: string | null;
275 + successful: boolean;
276 + logId?: string;
277 + sessionInfo?: unknown;
278 +}
279 +```
\ No newline at end of file
docs/api/providers.md new
+293
@@ -0,0 +1,293 @@
1 +# Providers API
2 +
3 +Providers are adapters that allow Composio tools to be used with different AI platforms. The SDK comes with a default OpenAI provider and supports creating custom providers.
4 +
5 +## Base Provider Classes
6 +
7 +Composio provides abstract base classes for creating providers:
8 +
9 +### BaseComposioProvider
10 +
11 +The base type for all providers:
12 +
13 +```typescript
14 +type BaseComposioProvider<TToolCollection, TTool> =
15 + | BaseNonAgenticProvider<TToolCollection, TTool>
16 + | BaseAgenticProvider<TToolCollection, TTool>;
17 +```
18 +
19 +### BaseNonAgenticProvider
20 +
21 +Base class for non-agentic providers (those that don't have their own agency/autonomy):
22 +
23 +```typescript
24 +abstract class BaseNonAgenticProvider<TToolCollection, TTool> extends BaseProvider {
25 + readonly _isAgentic = false;
26 +
27 + // Wrap a tool in the provider specific format
28 + abstract wrapTool(tool: Tool): TTool;
29 +
30 + // Wrap a list of tools in the provider specific format
31 + abstract wrapTools(tools: Tool[]): TToolCollection;
32 +}
33 +```
34 +
35 +### BaseAgenticProvider
36 +
37 +Base class for agentic providers (those with their own agency/autonomy):
38 +
39 +```typescript
40 +abstract class BaseAgenticProvider<TToolCollection, TTool> extends BaseProvider {
41 + readonly _isAgentic = true;
42 +
43 + // Wrap a tool in the provider specific format
44 + abstract wrapTool(tool: Tool, executeTool: ExecuteToolFn): TTool;
45 +
46 + // Wrap a list of tools in the provider specific format
47 + abstract wrapTools(tools: Tool[], executeTool: ExecuteToolFn): TToolCollection;
48 +}
49 +```
50 +
51 +## OpenAI Provider
52 +
53 +The default provider for Composio SDK is the OpenAI Provider, which formats tools for use with OpenAI's API.
54 +
55 +```typescript
56 +import { Composio, OpenAIProvider } from '@composio/sdk';
57 +
58 +const composio = new Composio({
59 + apiKey: 'your-api-key',
60 + provider: new OpenAIProvider(),
61 +});
62 +```
63 +
64 +### Methods
65 +
66 +#### wrapTool(tool)
67 +
68 +Transforms a Composio tool into an OpenAI function tool format.
69 +
70 +```typescript
71 +const openaiTool = openaiProvider.wrapTool(composioTool);
72 +```
73 +
74 +**Parameters:**
75 +- `tool` (Tool): The Composio tool to transform
76 +
77 +**Returns:** OpenAI.ChatCompletionTool - The tool in OpenAI format
78 +
79 +#### wrapTools(tools)
80 +
81 +Transforms a list of Composio tools into an array of OpenAI function tools.
82 +
83 +```typescript
84 +const openaiTools = openaiProvider.wrapTools(composioTools);
85 +```
86 +
87 +**Parameters:**
88 +- `tools` (Tool[]): The list of Composio tools to transform
89 +
90 +**Returns:** Array<OpenAI.ChatCompletionTool> - The tools in OpenAI format
91 +
92 +#### executeToolCall(userId, tool, options?, modifiers?)
93 +
94 +Executes a tool call from an OpenAI assistant.
95 +
96 +```typescript
97 +const result = await openaiProvider.executeToolCall(
98 + 'user123',
99 + toolCall,
100 + { connectedAccountId: 'conn_abc123' },
101 + {
102 + beforeToolExecute: (toolSlug, toolkitSlug, params) => params,
103 + afterToolExecute: (toolSlug, toolkitSlug, result) => result
104 + }
105 +);
106 +```
107 +
108 +**Parameters:**
109 +- `userId` (string): The user ID
110 +- `tool` (OpenAI.ChatCompletionMessageToolCall): The tool call from OpenAI
111 +- `options` (ExecuteToolFnOptions): Optional parameters for tool execution
112 +- `modifiers` (ExecuteToolModifiers): Optional modifiers for request/response transformation
113 +
114 +**Returns:** Promise<string> - The result of the tool call as JSON string
115 +
116 +#### handleToolCall(userId, chatCompletion, options?, modifiers?)
117 +
118 +Handles tool calls from an OpenAI chat completion.
119 +
120 +```typescript
121 +const outputs = await openaiProvider.handleToolCall(
122 + 'user123',
123 + chatCompletion
124 +);
125 +```
126 +
127 +**Parameters:**
128 +- `userId` (string): The user ID
129 +- `chatCompletion` (OpenAI.ChatCompletion): The chat completion containing tool calls
130 +- `options` (ExecuteToolFnOptions): Optional parameters for tool execution
131 +- `modifiers` (ExecuteToolModifiers): Optional modifiers for request/response transformation
132 +
133 +**Returns:** Promise<string[]> - The results of the tool calls
134 +
135 +#### handleAssistantMessage(userId, run, options?, modifiers?)
136 +
137 +Handles tool calls from an OpenAI assistant run.
138 +
139 +```typescript
140 +const toolOutputs = await openaiProvider.handleAssistantMessage(
141 + 'user123',
142 + run
143 +);
144 +```
145 +
146 +**Parameters:**
147 +- `userId` (string): The user ID
148 +- `run` (OpenAI.Beta.Threads.Run): The run object containing tool calls
149 +- `options` (ExecuteToolFnOptions): Optional parameters for tool execution
150 +- `modifiers` (ExecuteToolModifiers): Optional modifiers for request/response transformation
151 +
152 +**Returns:** Promise<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput[]> - The tool outputs
153 +
154 +#### waitAndHandleAssistantStreamToolCalls(userId, client, runStream, thread, options?, modifiers?)
155 +
156 +Waits for and handles tool calls from an OpenAI assistant stream.
157 +
158 +```typescript
159 +for await (const event of openaiProvider.waitAndHandleAssistantStreamToolCalls(
160 + 'user123',
161 + openaiClient,
162 + runStream,
163 + thread
164 +)) {
165 + console.log(event);
166 +}
167 +```
168 +
169 +**Parameters:**
170 +- `userId` (string): The user ID
171 +- `client` (OpenAI): The OpenAI client
172 +- `runStream` (Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>): The run stream
173 +- `thread` (OpenAI.Beta.Threads.Thread): The thread object
174 +- `options` (ExecuteToolFnOptions): Optional parameters for tool execution
175 +- `modifiers` (ExecuteToolModifiers): Optional modifiers for request/response transformation
176 +
177 +**Returns:** AsyncGenerator<OpenAI.Beta.Assistants.AssistantStreamEvent, void, unknown> - Generator of stream events
178 +
179 +#### waitAndHandleAssistantToolCalls(userId, client, run, thread, options?, modifiers?)
180 +
181 +Waits for and handles tool calls from an OpenAI assistant.
182 +
183 +```typescript
184 +const finalRun = await openaiProvider.waitAndHandleAssistantToolCalls(
185 + 'user123',
186 + openaiClient,
187 + run,
188 + thread
189 +);
190 +```
191 +
192 +**Parameters:**
193 +- `userId` (string): The user ID
194 +- `client` (OpenAI): The OpenAI client
195 +- `run` (OpenAI.Beta.Threads.Run): The run object containing tool calls
196 +- `thread` (OpenAI.Beta.Threads.Thread): The thread object
197 +- `options` (ExecuteToolFnOptions): Optional parameters for tool execution
198 +- `modifiers` (ExecuteToolModifiers): Optional modifiers for request/response transformation
199 +
200 +**Returns:** Promise<OpenAI.Beta.Threads.Run> - The final run object
201 +
202 +## Creating Custom Providers
203 +
204 +You can create custom providers by extending either `BaseNonAgenticProvider` or `BaseAgenticProvider`:
205 +
206 +```typescript
207 +import { BaseNonAgenticProvider, Tool } from '@composio/sdk';
208 +
209 +type AnthropicTool = {
210 + name: string;
211 + description: string;
212 + parameters: Record<string, unknown>;
213 +};
214 +
215 +type AnthropicToolCollection = AnthropicTool[];
216 +
217 +export class AnthropicProvider extends BaseNonAgenticProvider<AnthropicToolCollection, AnthropicTool> {
218 + readonly name = 'anthropic';
219 +
220 + override wrapTool(tool: Tool): AnthropicTool {
221 + return {
222 + name: tool.slug,
223 + description: tool.description || '',
224 + parameters: tool.inputParameters || {},
225 + };
226 + }
227 +
228 + override wrapTools(tools: Tool[]): AnthropicToolCollection {
229 + return tools.map(tool => this.wrapTool(tool));
230 + }
231 +
232 + // Additional methods for handling Anthropic-specific functionality
233 +}
234 +```
235 +
236 +## Types
237 +
238 +### ExecuteToolFn
239 +
240 +```typescript
241 +type ExecuteToolFn = (
242 + toolSlug: string,
243 + input: Record<string, unknown>
244 +) => Promise<ToolExecuteResponse>;
245 +```
246 +
247 +### ExecuteToolFnOptions
248 +
249 +```typescript
250 +interface ExecuteToolFnOptions {
251 + connectedAccountId?: string;
252 + customAuthParams?: CustomAuthParams;
253 +}
254 +```
255 +
256 +### ExecuteToolModifiers
257 +
258 +```typescript
259 +interface ExecuteToolModifiers {
260 + beforeToolExecute?: BeforeToolExecuteModifier;
261 + afterToolExecute?: AfterToolExecuteModifier;
262 +}
263 +```
264 +
265 +### TransformToolSchemaModifier
266 +
267 +```typescript
268 +type TransformToolSchemaModifier = (
269 + toolSlug: string,
270 + toolkitSlug: string,
271 + tool: Tool
272 +) => Tool;
273 +```
274 +
275 +### BeforeToolExecuteModifier
276 +
277 +```typescript
278 +type BeforeToolExecuteModifier = (
279 + toolSlug: string,
280 + toolkitSlug: string,
281 + params: ToolExecuteParams
282 +) => ToolExecuteParams;
283 +```
284 +
285 +### AfterToolExecuteModifier
286 +
287 +```typescript
288 +type AfterToolExecuteModifier = (
289 + toolSlug: string,
290 + toolkitSlug: string,
291 + result: ToolExecuteResponse
292 +) => ToolExecuteResponse;
293 +```
\ No newline at end of file
docs/api/toolkits.md new
+169
@@ -0,0 +1,169 @@
1 +# Toolkits API
2 +
3 +The `Toolkits` class provides methods to list, retrieve, and manage toolkits. Toolkits are collections of related tools provided by a single service (like GitHub, Gmail, etc.).
4 +
5 +## Methods
6 +
7 +### get(slug)
8 +
9 +Retrieves a specific toolkit by its slug identifier.
10 +
11 +```typescript
12 +// Get a specific toolkit
13 +const githubToolkit = await composio.toolkits.get('github');
14 +console.log(githubToolkit.name); // GitHub
15 +console.log(githubToolkit.authConfigDetails); // Authentication configuration details
16 +```
17 +
18 +**Parameters:**
19 +
20 +- `slug` (string): The unique slug identifier of the toolkit to retrieve
21 +
22 +**Returns:** Promise<ToolkitRetrieveResponse> - The toolkit object with detailed information
23 +
24 +**Throws:** ComposioToolNotFoundError if no toolkit with the given slug exists
25 +
26 +### get(query)
27 +
28 +Retrieves a list of toolkits based on the provided query parameters.
29 +
30 +```typescript
31 +// Get all toolkits
32 +const allToolkits = await composio.toolkits.get({});
33 +
34 +// Get toolkits by category
35 +const devToolkits = await composio.toolkits.get({
36 + category: 'developer-tools'
37 +});
38 +
39 +// Get local toolkits
40 +const localToolkits = await composio.toolkits.get({
41 + isLocal: true
42 +});
43 +```
44 +
45 +**Parameters:**
46 +
47 +- `query` (ToolkitListParams): The query parameters to filter toolkits
48 +
49 +**Returns:** Promise<ToolKitListResponse> - A paginated list of toolkits matching the query criteria
50 +
51 +### listCategories()
52 +
53 +Retrieves all toolkit categories available in the Composio SDK.
54 +
55 +```typescript
56 +// Get all toolkit categories
57 +const categories = await composio.toolkits.listCategories();
58 +console.log(categories.items); // Array of category objects
59 +```
60 +
61 +**Returns:** Promise<ToolkitRetrieveCategoriesResponse> - The list of toolkit categories
62 +
63 +### authorize(userId, toolkitSlug)
64 +
65 +Authorizes a user to use a toolkit. This method will create an auth config if one doesn't exist and initiate a connection request.
66 +
67 +```typescript
68 +// Authorize a user to use GitHub
69 +const connectionRequest = await composio.toolkits.authorize('user123', 'github');
70 +
71 +// Use the connection request to complete the authorization process
72 +console.log(connectionRequest.redirectUrl); // URL to redirect the user for authorization
73 +```
74 +
75 +**Parameters:**
76 +
77 +- `userId` (string): The user ID of the user to authorize
78 +- `toolkitSlug` (string): The slug of the toolkit to authorize
79 +
80 +**Returns:** Promise<ConnectionRequest> - The connection request object
81 +
82 +## Types
83 +
84 +### ToolkitListParams
85 +
86 +```typescript
87 +interface ToolkitListParams {
88 + category?: string; // Filter by category
89 + isLocal?: boolean; // Filter for local toolkits
90 + managedBy?: string; // Filter by manager
91 + sortBy?: string; // Sort results by this field
92 +}
93 +```
94 +
95 +### ToolKitListResponse
96 +
97 +```typescript
98 +interface ToolKitListResponse {
99 + items: ToolKitItem[]; // List of toolkits
100 + nextCursor?: string | null; // Pagination cursor
101 + totalPages: number; // Total number of pages
102 +}
103 +```
104 +
105 +### ToolKitItem
106 +
107 +```typescript
108 +interface ToolKitItem {
109 + name: string; // Name of the toolkit
110 + slug: string; // Unique slug identifier
111 + meta: { // Metadata about the toolkit
112 + createdAt: string; // When the toolkit was created
113 + updatedAt: string; // When the toolkit was last updated
114 + toolsCount: number; // Number of tools in the toolkit
115 + triggersCount: number; // Number of triggers in the toolkit
116 + };
117 + isLocalToolkit: boolean; // Whether this is a local toolkit
118 + authSchemes: string[]; // Available authentication schemes
119 + composioManagedAuthSchemes: string[]; // Managed auth schemes
120 + noAuth: boolean; // Whether authentication is required
121 +}
122 +```
123 +
124 +### ToolkitRetrieveResponse
125 +
126 +```typescript
127 +interface ToolkitRetrieveResponse {
128 + name: string; // Name of the toolkit
129 + slug: string; // Unique slug identifier
130 + meta: { // Metadata about the toolkit
131 + createdAt: string; // When the toolkit was created
132 + updatedAt: string; // When the toolkit was last updated
133 + toolsCount: number; // Number of tools in the toolkit
134 + triggersCount: number; // Number of triggers in the toolkit
135 + };
136 + isLocalToolkit: boolean; // Whether this is a local toolkit
137 + composioManagedAuthSchemes: string[]; // Managed auth schemes
138 + authConfigDetails: { // Authentication configuration details
139 + name: string; // Name of the auth configuration
140 + mode: string; // Auth mode (e.g., "OAUTH2")
141 + fields: { // Required fields
142 + authConfigCreation: Record<string, unknown>; // Fields for creating auth config
143 + connectedAccountInitiation: Record<string, unknown>; // Fields for initiating connection
144 + };
145 + proxy?: { // Proxy configuration (if any)
146 + baseUrl: string; // Base URL for proxied requests
147 + };
148 + }[];
149 +}
150 +```
151 +
152 +### ToolkitRetrieveCategoriesResponse
153 +
154 +```typescript
155 +interface ToolkitRetrieveCategoriesResponse {
156 + items: ToolkitCategory[]; // List of categories
157 + nextCursor?: string | null; // Pagination cursor
158 + totalPages: number; // Total number of pages
159 +}
160 +```
161 +
162 +### ToolkitCategory
163 +
164 +```typescript
165 +interface ToolkitCategory {
166 + id: string; // Category ID
167 + name: string; // Category name
168 +}
169 +```
\ No newline at end of file
docs/api/tools.md new
+218
@@ -0,0 +1,218 @@
1 +# Tools API
2 +
3 +The `Tools` class provides methods to list, retrieve, and execute tools from various toolkits. It is one of the core components of the Composio SDK.
4 +
5 +## Methods
6 +
7 +### get(userId, filters, options?)
8 +
9 +Retrieves tools based on the provided filters.
10 +
11 +```typescript
12 +// Get tools from a specific toolkit
13 +const githubTools = await composio.tools.get('default', {
14 + toolkits: ['github'],
15 + limit: 10
16 +});
17 +
18 +// Get tools with search
19 +const searchTools = await composio.tools.get('default', {
20 + search: 'user',
21 + important: true
22 +});
23 +
24 +// Get a specific tool by slug
25 +const tool = await composio.tools.get('default', 'GITHUB_GET_REPO');
26 +
27 +// Get a tool with schema modifications
28 +const tool = await composio.tools.get('default', 'GITHUB_GET_REPOS', {
29 + modifyToolSchema: (toolSlug, toolkitSlug, schema) => {
30 + // Customize the tool schema
31 + return {...schema, description: 'Custom description'};
32 + }
33 +});
34 +```
35 +
36 +**Parameters:**
37 +
38 +- `userId` (string): The user ID to get the tools for
39 +- `filters` (ToolListParams | string): Either a slug string or filters object
40 +- `options` (ProviderOptions): Optional provider options including modifiers
41 +
42 +**Returns:** The wrapped tools collection, formatted according to the provider
43 +
44 +### execute(slug, body, modifiers?)
45 +
46 +Executes a given tool with the provided parameters.
47 +
48 +```typescript
49 +// Execute a Composio API tool
50 +const result = await composio.tools.execute('HACKERNEWS_GET_USER', {
51 + userId: 'default',
52 + arguments: { userId: 'pg' }
53 +});
54 +
55 +// Execute with modifiers
56 +const result = await composio.tools.execute('GITHUB_GET_ISSUES', {
57 + userId: 'default',
58 + arguments: { owner: 'composio', repo: 'sdk' }
59 +}, {
60 + beforeToolExecute: (toolSlug, toolkitSlug, params) => {
61 + // Modify params before execution
62 + return params;
63 + },
64 + afterToolExecute: (toolSlug, toolkitSlug, result) => {
65 + // Transform result after execution
66 + return result;
67 + }
68 +});
69 +```
70 +
71 +**Parameters:**
72 +
73 +- `slug` (string): The slug/ID of the tool to be executed
74 +- `body` (ToolExecuteParams): The parameters to be passed to the tool
75 +- `modifiers` (ExecuteToolModifiers): Optional modifiers to transform the request or response
76 +
77 +**Returns:** Promise<ToolExecuteResponse> - The response from the tool execution
78 +
79 +**Throws:**
80 +- `ComposioCustomToolsNotInitializedError`: If the CustomTools instance is not initialized
81 +- `ComposioToolNotFoundError`: If the tool with the given slug is not found
82 +- `ComposioToolExecutionError`: If there is an error during tool execution
83 +
84 +### createCustomTool(body)
85 +
86 +Creates a custom tool that can be used within the Composio SDK.
87 +
88 +```typescript
89 +const customTool = await composio.tools.createCustomTool({
90 + name: 'My Custom Tool',
91 + description: 'A custom tool that does something specific',
92 + slug: 'MY_CUSTOM_TOOL',
93 + inputParameters: {
94 + param1: {
95 + type: 'string',
96 + description: 'First parameter',
97 + required: true
98 + }
99 + },
100 + outputParameters: {
101 + result: {
102 + type: 'string',
103 + description: 'The result of the operation'
104 + }
105 + },
106 + handler: async (params, context) => {
107 + // Custom logic here
108 + return { data: { result: 'Success!' } };
109 + }
110 +});
111 +```
112 +
113 +**Parameters:**
114 +
115 +- `body` (CustomToolOptions): The configuration for the custom tool
116 +
117 +**Returns:** Promise<Tool> - The created custom tool
118 +
119 +### getRawComposioTools(userId, query?, modifier?)
120 +
121 +Lists all tools available in the Composio SDK including custom tools.
122 +
123 +```typescript
124 +// Get all tools
125 +const tools = await composio.tools.getRawComposioTools('default');
126 +
127 +// Get tools with filters
128 +const githubTools = await composio.tools.getRawComposioTools('default', {
129 + toolkits: ['github'],
130 + important: true
131 +});
132 +
133 +// Get tools with schema transformation
134 +const tools = await composio.tools.getRawComposioTools('default', {},
135 + (toolSlug, toolkitSlug, tool) => {
136 + // Add custom properties to tool schema
137 + return {...tool, customProperty: 'value'};
138 + }
139 +);
140 +```
141 +
142 +**Parameters:**
143 +
144 +- `userId` (string): The user ID for whom to fetch the tools
145 +- `query` (ToolListParams): Optional query parameters to filter the tools
146 +- `modifier` (TransformToolSchemaModifier): Optional function to transform tool schemas
147 +
148 +**Returns:** Promise<ToolList> - List of tools matching the query criteria
149 +
150 +### getRawComposioToolBySlug(userId, slug, modifier?)
151 +
152 +Retrieves a tool by its Slug.
153 +
154 +```typescript
155 +const tool = await composio.tools.getRawComposioToolBySlug('default', 'github');
156 +```
157 +
158 +**Parameters:**
159 +
160 +- `userId` (string): The user ID for whom to fetch the tool
161 +- `slug` (string): The ID of the tool to be retrieved
162 +- `modifier` (TransformToolSchemaModifier): Optional function to transform tool schema
163 +
164 +**Returns:** Promise<Tool> - The tool
165 +
166 +## Types
167 +
168 +### ToolListParams
169 +
170 +```typescript
171 +interface ToolListParams {
172 + tools?: string[]; // List of tool slugs to filter by
173 + cursor?: string; // Pagination cursor
174 + important?: string; // Filter for important tools
175 + limit?: string; // Limit the number of results
176 + search?: string; // Search term
177 + toolkits?: string[]; // List of toolkit slugs to filter by
178 +}
179 +```
180 +
181 +### ToolExecuteParams
182 +
183 +```typescript
184 +interface ToolExecuteParams {
185 + allowTracing?: boolean; // Enable/disable tracing
186 + connectedAccountId?: string; // Connected account ID
187 + customAuthParams?: CustomAuthParams; // Custom auth parameters
188 + arguments?: Record<string, unknown>; // Tool arguments
189 + userId: string; // User ID
190 + version?: string; // Tool version
191 + text?: string; // Text input
192 +}
193 +```
194 +
195 +### ToolExecuteResponse
196 +
197 +```typescript
198 +interface ToolExecuteResponse {
199 + data: Record<string, unknown>; // Tool execution data
200 + error: string | null; // Error message (if any)
201 + successful: boolean; // Whether the execution was successful
202 + logId?: string; // Log ID for debugging
203 + sessionInfo?: unknown; // Session information
204 +}
205 +```
206 +
207 +### CustomToolOptions
208 +
209 +```typescript
210 +interface CustomToolOptions {
211 + name: string; // Name of the custom tool
212 + description: string; // Description of the custom tool
213 + slug: string; // Unique slug for the custom tool
214 + inputParameters: Record<string, unknown>; // Input parameters schema
215 + outputParameters?: Record<string, unknown>; // Output parameters schema
216 + handler: (params: ToolExecuteParams, context: ExecuteMetadata) => Promise<ToolExecuteResponse>; // Handler function
217 +}
218 +```
\ No newline at end of file
docs/core-concepts.md new
+122
@@ -0,0 +1,122 @@
1 +# Core Concepts
2 +
3 +Composio SDK is built around a set of key concepts that work together to provide a seamless integration experience for third-party services and tools.
4 +
5 +## Tools
6 +
7 +Tools are the fundamental units of functionality in Composio. Each tool represents a specific action that can be performed, such as "Get GitHub Repository" or "Send Email". Tools have:
8 +
9 +- **Slug**: A unique identifier (e.g., `GITHUB_GET_REPO`)
10 +- **Name**: A human-readable name (e.g., "Get GitHub Repository")
11 +- **Description**: A description of what the tool does
12 +- **Input Parameters**: The arguments required to execute the tool
13 +- **Output Parameters**: The data returned by the tool
14 +
15 +Tools are organized into toolkits and can be executed through the Composio SDK.
16 +
17 +```typescript
18 +// Example: Execute a GitHub tool
19 +const result = await composio.tools.execute('GITHUB_GET_REPO', {
20 + userId: 'default',
21 + arguments: {
22 + owner: 'composio',
23 + repo: 'sdk',
24 + },
25 +});
26 +```
27 +
28 +## Toolkits
29 +
30 +Toolkits are collections of related tools grouped by service or functionality. For example, the "GitHub" toolkit includes tools for interacting with repositories, issues, pull requests, and more.
31 +
32 +Toolkits typically require authentication to be accessed, which is managed through connected accounts.
33 +
34 +```typescript
35 +// Example: Get all tools from the GitHub toolkit
36 +const tools = await composio.tools.get('default', {
37 + toolkits: ['github'],
38 +});
39 +```
40 +
41 +## Connected Accounts
42 +
43 +Connected Accounts represent a user's connection to an external service (toolkit). They store authentication tokens and other information needed to access the service.
44 +
45 +The SDK provides methods to create, manage, and use connected accounts:
46 +
47 +```typescript
48 +// Example: Initiate a connection to GitHub
49 +const connectionRequest = await composio.toolkits.authorize('user123', 'github');
50 +
51 +// Example: Wait for the connection to be established
52 +const connectedAccount = await composio.connectedAccounts.waitForConnection(connectionRequest.id);
53 +```
54 +
55 +## Auth Configs
56 +
57 +Auth Configs define how authentication works for a particular toolkit. They specify the auth scheme (OAuth2, API Key, etc.) and other authentication-related details.
58 +
59 +Auth Configs are usually created automatically when authorizing a toolkit but can also be created manually.
60 +
61 +```typescript
62 +// Example: Create an auth config for GitHub
63 +const authConfig = await composio.authConfigs.create('github', {
64 + type: 'use_composio_managed_auth',
65 + name: 'GitHub Auth Config',
66 +});
67 +```
68 +
69 +## Providers
70 +
71 +Providers are adapters that allow tools to be used with different AI platforms or frameworks. The default provider is OpenAIProvider, which formats tools for use with OpenAI's API.
72 +
73 +Providers handle the transformation of tools into the format required by the AI platform and manage the execution flow.
74 +
75 +```typescript
76 +// Example: Initialize Composio with OpenAI provider
77 +const composio = new Composio({
78 + apiKey: 'your-api-key',
79 + provider: new OpenAIProvider(),
80 +});
81 +```
82 +
83 +## Custom Tools
84 +
85 +Custom Tools allow you to extend Composio's functionality by creating your own tools. You define the input and output parameters and provide a handler function that implements the tool's behavior.
86 +
87 +```typescript
88 +// Example: Create a custom tool
89 +const customTool = await composio.tools.createCustomTool({
90 + name: 'My Custom Tool',
91 + description: 'A custom tool that does something specific',
92 + slug: 'MY_CUSTOM_TOOL',
93 + inputParameters: {
94 + param1: {
95 + type: 'string',
96 + description: 'First parameter',
97 + required: true
98 + }
99 + },
100 + outputParameters: {
101 + result: {
102 + type: 'string',
103 + description: 'The result of the operation'
104 + }
105 + },
106 + handler: async (params, context) => {
107 + // Custom logic here
108 + return { data: { result: 'Success!' } };
109 + }
110 +});
111 +```
112 +
113 +## Triggers
114 +
115 +Triggers allow your application to respond to events from external services. They define when and how your application should take action based on external events.
116 +
117 +```typescript
118 +// Example: Get available triggers
119 +const triggers = await composio.triggers.get({
120 + toolkits: ['github'],
121 +});
122 +```
\ No newline at end of file
docs/getting-started.md new
+272
@@ -0,0 +1,272 @@
1 +# Getting Started with Composio SDK
2 +
3 +This guide will help you get started with the Composio SDK. You'll learn how to install it, initialize it, and use it to execute tools, manage connected accounts, and integrate with AI providers.
4 +
5 +## Installation
6 +
7 +Install the Composio SDK using npm, yarn, or pnpm:
8 +
9 +```bash
10 +# Using npm
11 +npm install @composio/sdk
12 +
13 +# Using yarn
14 +yarn add @composio/sdk
15 +
16 +# Using pnpm
17 +pnpm add @composio/sdk
18 +```
19 +
20 +## Initialization
21 +
22 +To use the SDK, you need to initialize it with your API key:
23 +
24 +```typescript
25 +import { Composio } from '@composio/sdk';
26 +
27 +// Initialize the SDK
28 +const composio = new Composio({
29 + apiKey: 'your-api-key',
30 +});
31 +```
32 +
33 +You can also customize the initialization with additional options:
34 +
35 +```typescript
36 +import { Composio, OpenAIProvider } from '@composio/sdk';
37 +
38 +// Initialize with custom provider and options
39 +const composio = new Composio({
40 + apiKey: 'your-api-key',
41 + baseURL: 'https://api.composio.dev', // Optional: Custom API endpoint
42 + allowTracking: true, // Optional: Enable/disable telemetry
43 + provider: new OpenAIProvider(), // Optional: Custom provider
44 +});
45 +```
46 +
47 +## Basic Usage
48 +
49 +### Listing Available Toolkits
50 +
51 +Toolkits are collections of related tools (like GitHub, Gmail, etc.). You can list all available toolkits:
52 +
53 +```typescript
54 +// Get all toolkits
55 +const allToolkits = await composio.toolkits.get({});
56 +console.log(allToolkits.items);
57 +
58 +// Get toolkits by category
59 +const devToolkits = await composio.toolkits.get({
60 + category: 'developer-tools'
61 +});
62 +```
63 +
64 +### Getting Tools from a Toolkit
65 +
66 +You can get tools from a specific toolkit:
67 +
68 +```typescript
69 +// Get all tools from the GitHub toolkit
70 +const githubTools = await composio.tools.get('default', {
71 + toolkits: ['github'],
72 +});
73 +
74 +// Get a specific tool by slug
75 +const getRepoTool = await composio.tools.get('default', 'GITHUB_GET_REPO');
76 +```
77 +
78 +### Executing a Tool
79 +
80 +To execute a tool, you need to provide the tool's slug and the parameters:
81 +
82 +```typescript
83 +// Execute a GitHub tool
84 +const result = await composio.tools.execute('GITHUB_GET_REPO', {
85 + userId: 'default',
86 + arguments: {
87 + owner: 'composio',
88 + repo: 'sdk',
89 + },
90 +});
91 +
92 +// Check if the execution was successful
93 +if (result.successful) {
94 + console.log('Repository details:', result.data);
95 +} else {
96 + console.error('Error:', result.error);
97 +}
98 +```
99 +
100 +## Working with Connected Accounts
101 +
102 +Many tools require authentication with external services. Composio manages this through connected accounts.
103 +
104 +### Setting Up a Connection
105 +
106 +To create a connected account, you need to:
107 +
108 +1. Authorize the toolkit
109 +2. Wait for the user to complete the authentication flow
110 +
111 +```typescript
112 +// Step 1: Authorize the toolkit
113 +const connectionRequest = await composio.toolkits.authorize('user123', 'github');
114 +
115 +// This gives you a redirect URL
116 +console.log('Redirect the user to:', connectionRequest.redirectUrl);
117 +
118 +// Step 2: Wait for the connection to be established
119 +// This should be called after the user completes the auth flow
120 +const connectedAccount = await composio.connectedAccounts.waitForConnection(connectionRequest.id);
121 +console.log('Connected account:', connectedAccount);
122 +```
123 +
124 +### Using a Connected Account with Tools
125 +
126 +Once you have a connected account, you can use it when executing tools:
127 +
128 +```typescript
129 +// Execute a tool with a connected account
130 +const result = await composio.tools.execute('GITHUB_GET_REPOS', {
131 + userId: 'user123',
132 + connectedAccountId: connectedAccount.id,
133 + arguments: {},
134 +});
135 +```
136 +
137 +## Integration with OpenAI
138 +
139 +Composio integrates seamlessly with OpenAI. Here's an example of using Composio tools with OpenAI:
140 +
141 +```typescript
142 +import { Composio } from '@composio/sdk';
143 +import OpenAI from 'openai';
144 +
145 +// Initialize Composio and OpenAI
146 +const composio = new Composio({
147 + apiKey: 'your-composio-api-key',
148 +});
149 +
150 +const openai = new OpenAI({
151 + apiKey: 'your-openai-api-key',
152 +});
153 +
154 +// Get tools from the GitHub toolkit
155 +const tools = await composio.tools.get('default', {
156 + toolkits: ['github'],
157 +});
158 +
159 +// Create a chat completion with OpenAI using the tools
160 +const completion = await openai.chat.completions.create({
161 + model: 'gpt-4-turbo',
162 + messages: [
163 + { role: 'system', content: 'You are a helpful assistant with access to GitHub tools.' },
164 + { role: 'user', content: 'List the repositories in the Composio organization' }
165 + ],
166 + tools, // Pass the tools to OpenAI
167 +});
168 +
169 +// If the assistant wants to use a tool
170 +if (completion.choices[0].message.tool_calls) {
171 + // Execute each tool call
172 + for (const toolCall of completion.choices[0].message.tool_calls) {
173 + // Parse the arguments
174 + const args = JSON.parse(toolCall.function.arguments);
175 +
176 + // Execute the tool
177 + const result = await composio.tools.execute(toolCall.function.name, {
178 + userId: 'default',
179 + arguments: args,
180 + });
181 +
182 + // Use the result in your application
183 + console.log(`Tool ${toolCall.function.name} result:`, result.data);
184 + }
185 +}
186 +```
187 +
188 +For a more complete integration, check out the [OpenAI Provider example](../examples/openai).
189 +
190 +## Creating Custom Tools
191 +
192 +You can extend Composio by creating your own custom tools:
193 +
194 +```typescript
195 +// Create a custom tool
196 +const customTool = await composio.tools.createCustomTool({
197 + name: 'Weather Forecast',
198 + description: 'Get the weather forecast for a location',
199 + slug: 'WEATHER_FORECAST',
200 + inputParameters: {
201 + type: 'object',
202 + properties: {
203 + location: {
204 + type: 'string',
205 + description: 'The location to get the forecast for'
206 + },
207 + days: {
208 + type: 'integer',
209 + description: 'Number of days for the forecast',
210 + default: 3
211 + }
212 + },
213 + required: ['location']
214 + },
215 + outputParameters: {
216 + type: 'object',
217 + properties: {
218 + forecast: {
219 + type: 'array',
220 + items: {
221 + type: 'object',
222 + properties: {
223 + date: { type: 'string' },
224 + temperature: { type: 'number' },
225 + conditions: { type: 'string' }
226 + }
227 + }
228 + }
229 + }
230 + },
231 + handler: async (params, context) => {
232 + try {
233 + const { location, days = 3 } = params.arguments;
234 +
235 + // Here you would call your weather API
236 + const forecast = await getWeatherForecast(location, days);
237 +
238 + return {
239 + data: { forecast },
240 + successful: true,
241 + error: null
242 + };
243 + } catch (error) {
244 + return {
245 + data: {},
246 + successful: false,
247 + error: error.message
248 + };
249 + }
250 + }
251 +});
252 +
253 +// Now you can use your custom tool
254 +const result = await composio.tools.execute('WEATHER_FORECAST', {
255 + userId: 'default',
256 + arguments: {
257 + location: 'San Francisco, CA',
258 + days: 5
259 + }
260 +});
261 +
262 +console.log(result.data.forecast);
263 +```
264 +
265 +## Next Steps
266 +
267 +Now that you understand the basics, you can:
268 +
269 +- Explore [more examples](../examples) to see how to use Composio in different scenarios
270 +- Learn about [custom providers](./api/providers.md) to integrate with other AI frameworks
271 +- Understand [error handling](./advanced/error-handling.md) to make your application more robust
272 +- Implement [middleware and modifiers](./advanced/middleware.md) to customize tool execution
\ No newline at end of file
docs/overview.md new
+112
@@ -0,0 +1,112 @@
1 +# Composio SDK v3 Documentation
2 +
3 +Composio SDK is a powerful toolkit that enables you to integrate third-party tools and services into your applications. This SDK helps you connect to various services (toolkits), execute tools, and manage user connections seamlessly.
4 +
5 +## Table of Contents
6 +
7 +- [Overview](#overview)
8 +- [Installation](#installation)
9 +- [Core Concepts](#core-concepts)
10 +- [Getting Started](#getting-started)
11 +- [API Reference](#api-reference)
12 +- [Providers](#providers)
13 +- [Examples](#examples)
14 +- [Advanced Topics](#advanced-topics)
15 +
16 +## Overview
17 +
18 +Composio SDK allows you to:
19 +
20 +- Execute tools from various services (like GitHub, Gmail, Slack, etc.)
21 +- Manage user connections to external services
22 +- Create custom tools
23 +- Implement triggers and event handlers
24 +- Integrate with AI providers like OpenAI
25 +
26 +The SDK is designed to be flexible and extensible, allowing you to integrate it into various types of applications.
27 +
28 +## Installation
29 +
30 +```bash
31 +npm install @composio/core
32 +```
33 +
34 +## Core Concepts
35 +
36 +The Composio SDK is built around several key concepts:
37 +
38 +- **Tools**: Individual actions that can be performed (e.g., "Get GitHub Repository", "Send Email")
39 +- **Toolkits**: Collections of related tools (e.g., GitHub, Gmail)
40 +- **Connected Accounts**: User connections to external services
41 +- **Auth Configs**: Authentication configurations for external services
42 +- **Providers**: Adapters for AI services that can use tools (e.g., OpenAI)
43 +- **Custom Tools**: Tools you can create and define yourself
44 +
45 +Check out the [Core Concepts](./core-concepts.md) documentation for more detailed information.
46 +
47 +## Getting Started
48 +
49 +Here's a quick example of how to use the Composio SDK:
50 +
51 +```typescript
52 +import { Composio } from '@composio/sdk';
53 +
54 +// Initialize the SDK
55 +const composio = new Composio({
56 + apiKey: 'your-api-key',
57 +});
58 +
59 +// Get tools from a specific toolkit
60 +const tools = await composio.tools.get('default', {
61 + toolkits: ['github'],
62 +});
63 +
64 +// Execute a tool
65 +const result = await composio.tools.execute('GITHUB_GET_REPO', {
66 + userId: 'default',
67 + arguments: {
68 + owner: 'composio',
69 + repo: 'sdk',
70 + },
71 +});
72 +
73 +console.log(result.data);
74 +```
75 +
76 +For more detailed examples and tutorials, check out the [Getting Started](./getting-started.md) guide.
77 +
78 +## API Reference
79 +
80 +The complete API reference documentation is available here:
81 +
82 +- [Composio Class](./api/composio.md)
83 +- [Tools](./api/tools.md)
84 +- [Toolkits](./api/toolkits.md)
85 +- [Connected Accounts](./api/connected-accounts.md)
86 +- [Auth Configs](./api/auth-configs.md)
87 +- [Providers](./api/providers.md)
88 +- [Custom Tools](./api/custom-tools.md)
89 +
90 +## Providers
91 +
92 +Composio SDK comes with built-in support for different providers:
93 +
94 +- [OpenAI Provider](./providers/openai.md)
95 +- [Custom Providers](./providers/custom.md)
96 +
97 +## Examples
98 +
99 +Check out our [examples directory](../examples) for complete code samples:
100 +
101 +- [Connected Accounts](../examples/connected-accounts)
102 +- [OpenAI Integration](../examples/openai)
103 +- [LangChain Integration](../examples/langchain)
104 +- [Toolkits](../examples/toolkits)
105 +- [Modifiers](../examples/modifiers)
106 +
107 +## Advanced Topics
108 +
109 +- [Error Handling](./advanced/error-handling.md)
110 +- [Telemetry](./advanced/telemetry.md)
111 +- [Custom Providers](./advanced/custom-providers.md)
112 +- [Middleware and Modifiers](./advanced/middleware.md)
docs/providers/custom.md new
+366
@@ -0,0 +1,366 @@
1 +# Creating Custom Providers
2 +
3 +Composio SDK allows you to create custom providers to integrate with different AI platforms and frameworks. This guide explains how to create custom providers for both agentic and non-agentic platforms.
4 +
5 +## Provider Types
6 +
7 +Composio supports two types of providers:
8 +
9 +1. **Non-Agentic Providers**: For platforms where the provider simply formats tools but doesn't have its own agency (e.g., OpenAI).
10 +2. **Agentic Providers**: For platforms where the provider has its own agency and can execute tools autonomously (e.g., an agent framework).
11 +
12 +## Creating a Non-Agentic Provider
13 +
14 +Non-agentic providers extend the `BaseNonAgenticProvider` class:
15 +
16 +```typescript
17 +import { BaseNonAgenticProvider, Tool } from '@composio/sdk';
18 +
19 +// Define the tool type for your provider
20 +type AnthropicTool = {
21 + name: string;
22 + description: string;
23 + parameters: Record<string, unknown>;
24 +};
25 +
26 +// Define the collection type for your provider
27 +type AnthropicToolCollection = AnthropicTool[];
28 +
29 +// Create the provider class
30 +export class AnthropicProvider extends BaseNonAgenticProvider<AnthropicToolCollection, AnthropicTool> {
31 + // Define the provider name (used for telemetry)
32 + readonly name = 'anthropic';
33 +
34 + // Implement the wrapTool method
35 + override wrapTool(tool: Tool): AnthropicTool {
36 + return {
37 + name: tool.slug,
38 + description: tool.description || '',
39 + parameters: tool.inputParameters || {},
40 + };
41 + }
42 +
43 + // Implement the wrapTools method
44 + override wrapTools(tools: Tool[]): AnthropicToolCollection {
45 + return tools.map(tool => this.wrapTool(tool));
46 + }
47 +
48 + // Add provider-specific methods
49 + async handleToolUsage(userId: string, toolName: string, params: Record<string, unknown>) {
50 + const result = await this.executeTool(toolName, {
51 + userId,
52 + arguments: params,
53 + });
54 +
55 + return JSON.stringify(result);
56 + }
57 +}
58 +```
59 +
60 +## Creating an Agentic Provider
61 +
62 +Agentic providers extend the `BaseAgenticProvider` class:
63 +
64 +```typescript
65 +import { BaseAgenticProvider, Tool, ExecuteToolFn } from '@composio/sdk';
66 +
67 +// Define the tool type for your provider
68 +type LangchainTool = {
69 + name: string;
70 + description: string;
71 + func: Function;
72 +};
73 +
74 +// Define the collection type for your provider
75 +type LangchainToolset = {
76 + tools: LangchainTool[];
77 + executor: (tool: LangchainTool, input: Record<string, unknown>) => Promise<unknown>;
78 +};
79 +
80 +// Create the provider class
81 +export class LangchainProvider extends BaseAgenticProvider<LangchainToolset, LangchainTool> {
82 + // Define the provider name (used for telemetry)
83 + readonly name = 'langchain';
84 +
85 + // Implement the wrapTool method (note the executeToolFn parameter)
86 + override wrapTool(tool: Tool, executeToolFn: ExecuteToolFn): LangchainTool {
87 + return {
88 + name: tool.slug,
89 + description: tool.description || '',
90 + func: async (input: Record<string, unknown>) => {
91 + const result = await executeToolFn(tool.slug, input);
92 + return result.data;
93 + }
94 + };
95 + }
96 +
97 + // Implement the wrapTools method (note the executeToolFn parameter)
98 + override wrapTools(tools: Tool[], executeToolFn: ExecuteToolFn): LangchainToolset {
99 + const langchainTools = tools.map(tool => this.wrapTool(tool, executeToolFn));
100 +
101 + return {
102 + tools: langchainTools,
103 + executor: async (tool, input) => {
104 + return await tool.func(input);
105 + }
106 + };
107 + }
108 +
109 + // Add provider-specific methods
110 + async createAgent(tools: LangchainToolset, model: any) {
111 + // Create a Langchain agent with the tools
112 + // This is just an example, the actual implementation would depend on the Langchain API
113 + return {
114 + run: async (prompt: string) => {
115 + // Run the agent with the prompt
116 + // The agent would use the tools.executor to execute tools
117 + }
118 + };
119 + }
120 +}
121 +```
122 +
123 +## Using a Custom Provider
124 +
125 +Once you've created a custom provider, you can use it with the Composio SDK:
126 +
127 +```typescript
128 +import { Composio } from '@composio/sdk';
129 +import { AnthropicProvider } from './providers/anthropic-provider';
130 +
131 +// Create an instance of your custom provider
132 +const anthropicProvider = new AnthropicProvider();
133 +
134 +// Initialize Composio with your custom provider
135 +const composio = new Composio({
136 + apiKey: 'your-composio-api-key',
137 + provider: anthropicProvider,
138 +});
139 +
140 +// Get tools using your custom provider
141 +const tools = await composio.tools.get('default', {
142 + toolkits: ['github'],
143 +});
144 +
145 +// Now you can use these tools with Anthropic's API
146 +// The tools will be formatted according to your provider's implementation
147 +```
148 +
149 +## Provider Methods
150 +
151 +### Common Methods
152 +
153 +Both types of providers have these methods available:
154 +
155 +#### executeTool(toolSlug, body, modifiers?)
156 +
157 +Executes a tool using the global execute function. This is useful for implementing provider-specific helper methods that need to execute tools.
158 +
159 +```typescript
160 +async executeTool(
161 + toolSlug: string,
162 + body: ToolExecuteParams,
163 + modifiers?: ExecuteToolModifiers
164 +): Promise<ToolExecuteResponse>;
165 +```
166 +
167 +Example:
168 +
169 +```typescript
170 +class MyProvider extends BaseNonAgenticProvider<MyToolCollection, MyTool> {
171 + // Other methods...
172 +
173 + async executeWithContext(userId: string, toolSlug: string, args: Record<string, unknown>, context: string) {
174 + // Add context to the arguments
175 + const argsWithContext = { ...args, context };
176 +
177 + // Execute the tool
178 + return this.executeTool(toolSlug, {
179 + userId,
180 + arguments: argsWithContext,
181 + });
182 + }
183 +}
184 +```
185 +
186 +### Non-Agentic Provider Methods
187 +
188 +Non-agentic providers must implement these methods:
189 +
190 +#### wrapTool(tool)
191 +
192 +Transforms a Composio tool into the provider-specific format.
193 +
194 +```typescript
195 +wrapTool(tool: Tool): TTool;
196 +```
197 +
198 +#### wrapTools(tools)
199 +
200 +Transforms a list of Composio tools into the provider-specific collection format.
201 +
202 +```typescript
203 +wrapTools(tools: Tool[]): TToolCollection;
204 +```
205 +
206 +### Agentic Provider Methods
207 +
208 +Agentic providers must implement these methods:
209 +
210 +#### wrapTool(tool, executeToolFn)
211 +
212 +Transforms a Composio tool into the provider-specific format, with access to an execute function.
213 +
214 +```typescript
215 +wrapTool(tool: Tool, executeToolFn: ExecuteToolFn): TTool;
216 +```
217 +
218 +#### wrapTools(tools, executeToolFn)
219 +
220 +Transforms a list of Composio tools into the provider-specific collection format, with access to an execute function.
221 +
222 +```typescript
223 +wrapTools(tools: Tool[], executeToolFn: ExecuteToolFn): TToolCollection;
224 +```
225 +
226 +## Examples
227 +
228 +### Claude Provider Example
229 +
230 +```typescript
231 +import { BaseNonAgenticProvider, Tool } from '@composio/sdk';
232 +
233 +type ClaudeTool = {
234 + name: string;
235 + description: string;
236 + input_schema: {
237 + type: string;
238 + properties: Record<string, unknown>;
239 + required?: string[];
240 + };
241 +};
242 +
243 +type ClaudeToolCollection = ClaudeTool[];
244 +
245 +export class ClaudeProvider extends BaseNonAgenticProvider<ClaudeToolCollection, ClaudeTool> {
246 + readonly name = 'claude';
247 +
248 + override wrapTool(tool: Tool): ClaudeTool {
249 + // Convert the input parameters to Claude's format
250 + const inputSchema = {
251 + type: 'object',
252 + properties: tool.inputParameters?.properties || {},
253 + required: tool.inputParameters?.required || [],
254 + };
255 +
256 + return {
257 + name: tool.slug,
258 + description: tool.description || '',
259 + input_schema: inputSchema,
260 + };
261 + }
262 +
263 + override wrapTools(tools: Tool[]): ClaudeToolCollection {
264 + return tools.map(tool => this.wrapTool(tool));
265 + }
266 +
267 + // Helper method for Claude tool execution
268 + async executeClaudeTool(userId: string, toolName: string, input: Record<string, unknown>) {
269 + const result = await this.executeTool(toolName, {
270 + userId,
271 + arguments: input,
272 + });
273 +
274 + return result.data;
275 + }
276 +}
277 +```
278 +
279 +### LangChain Provider Example
280 +
281 +```typescript
282 +import { BaseAgenticProvider, Tool, ExecuteToolFn } from '@composio/sdk';
283 +
284 +// These types would match the actual LangChain API
285 +type LangChainTool = {
286 + name: string;
287 + description: string;
288 + schema: any;
289 + call: (input: Record<string, unknown>) => Promise<any>;
290 +};
291 +
292 +type LangChainToolset = LangChainTool[];
293 +
294 +export class LangChainProvider extends BaseAgenticProvider<LangChainToolset, LangChainTool> {
295 + readonly name = 'langchain';
296 +
297 + override wrapTool(tool: Tool, executeToolFn: ExecuteToolFn): LangChainTool {
298 + return {
299 + name: tool.slug,
300 + description: tool.description || '',
301 + schema: tool.inputParameters || {},
302 + call: async (input: Record<string, unknown>) => {
303 + const result = await executeToolFn(tool.slug, input);
304 + if (!result.successful) {
305 + throw new Error(result.error || 'Tool execution failed');
306 + }
307 + return result.data;
308 + }
309 + };
310 + }
311 +
312 + override wrapTools(tools: Tool[], executeToolFn: ExecuteToolFn): LangChainToolset {
313 + return tools.map(tool => this.wrapTool(tool, executeToolFn));
314 + }
315 +
316 + // LangChain-specific helper methods
317 + createAgent(tools: LangChainToolset, model: any) {
318 + // Implement LangChain agent creation
319 + // This is just a placeholder - the actual implementation would use the LangChain API
320 + }
321 +}
322 +```
323 +
324 +## Advanced: Provider Context
325 +
326 +You can store provider-specific context or state in your provider class:
327 +
328 +```typescript
329 +class ProviderWithContext extends BaseNonAgenticProvider<MyToolCollection, MyTool> {
330 + readonly name = 'provider-with-context';
331 +
332 + // Provider-specific context
333 + private cache = new Map<string, any>();
334 + private config: any;
335 +
336 + constructor(config: any) {
337 + super();
338 + this.config = config;
339 + }
340 +
341 + override wrapTool(tool: Tool): MyTool {
342 + // Use the config when wrapping tools
343 + const customizedTool = {
344 + name: tool.slug,
345 + description: this.config.addDescriptionPrefix
346 + ? `[${this.config.descriptionPrefix}] ${tool.description}`
347 + : tool.description,
348 + // Other properties...
349 + };
350 +
351 + // Cache the tool for later use
352 + this.cache.set(tool.slug, customizedTool);
353 +
354 + return customizedTool;
355 + }
356 +
357 + override wrapTools(tools: Tool[]): MyToolCollection {
358 + return tools.map(tool => this.wrapTool(tool));
359 + }
360 +
361 + // Custom method that uses the cache
362 + getTool(slug: string): MyTool | undefined {
363 + return this.cache.get(slug);
364 + }
365 +}
366 +```
\ No newline at end of file
docs/providers/openai.md new
+364
@@ -0,0 +1,364 @@
1 +# OpenAI Provider
2 +
3 +The OpenAI Provider is the default provider for the Composio SDK. It transforms Composio tools into a format compatible with OpenAI's function calling capabilities.
4 +
5 +## Overview
6 +
7 +The OpenAI Provider allows you to:
8 +
9 +1. Format Composio tools as OpenAI function tools
10 +2. Handle tool calls from OpenAI chat completions
11 +3. Handle tool calls from OpenAI assistants
12 +4. Process streaming responses from OpenAI with tool calls
13 +
14 +## Basic Usage
15 +
16 +The OpenAI Provider is used by default when you initialize the Composio SDK:
17 +
18 +```typescript
19 +import { Composio } from '@composio/sdk';
20 +
21 +// OpenAI Provider is used by default
22 +const composio = new Composio({
23 + apiKey: 'your-composio-api-key',
24 +});
25 +```
26 +
27 +You can also explicitly specify the OpenAI Provider:
28 +
29 +```typescript
30 +import { Composio, OpenAIProvider } from '@composio/sdk';
31 +
32 +// Explicitly specify the OpenAI Provider
33 +const composio = new Composio({
34 + apiKey: 'your-composio-api-key',
35 + provider: new OpenAIProvider(),
36 +});
37 +```
38 +
39 +## Getting Tools for OpenAI
40 +
41 +The OpenAI Provider transforms Composio tools into OpenAI function tools:
42 +
43 +```typescript
44 +import { Composio } from '@composio/sdk';
45 +import OpenAI from 'openai';
46 +
47 +const composio = new Composio({
48 + apiKey: 'your-composio-api-key',
49 +});
50 +
51 +const openai = new OpenAI({
52 + apiKey: 'your-openai-api-key',
53 +});
54 +
55 +// Get GitHub tools from Composio
56 +const tools = await composio.tools.get('default', {
57 + toolkits: ['github'],
58 +});
59 +
60 +// The tools are already formatted for OpenAI
61 +console.log(tools[0]); // { type: 'function', function: { name: 'GITHUB_GET_REPO', ... } }
62 +
63 +// Use the tools with OpenAI
64 +const completion = await openai.chat.completions.create({
65 + model: 'gpt-4',
66 + messages: [
67 + { role: 'system', content: 'You are a helpful assistant with GitHub tools.' },
68 + { role: 'user', content: 'Find information about the Composio SDK repository' }
69 + ],
70 + tools, // Pass the tools to OpenAI
71 +});
72 +```
73 +
74 +## Handling Tool Calls from OpenAI Chat Completions
75 +
76 +When OpenAI's model decides to call a tool, you can use the OpenAI Provider to handle it:
77 +
78 +```typescript
79 +import { Composio, OpenAIProvider } from '@composio/sdk';
80 +import OpenAI from 'openai';
81 +
82 +const composio = new Composio({
83 + apiKey: 'your-composio-api-key',
84 +});
85 +
86 +const openai = new OpenAI({
87 + apiKey: 'your-openai-api-key',
88 +});
89 +
90 +// Get the OpenAI Provider
91 +const openaiProvider = composio.provider as OpenAIProvider;
92 +
93 +// Get GitHub tools
94 +const tools = await composio.tools.get('default', {
95 + toolkits: ['github'],
96 +});
97 +
98 +// Create a chat completion
99 +const completion = await openai.chat.completions.create({
100 + model: 'gpt-4',
101 + messages: [
102 + { role: 'system', content: 'You are a helpful assistant with GitHub tools.' },
103 + { role: 'user', content: 'Find information about the Composio SDK repository' }
104 + ],
105 + tools,
106 +});
107 +
108 +// Check if there are tool calls
109 +if (completion.choices[0].message.tool_calls) {
110 + // Handle the tool calls
111 + const toolOutputs = await openaiProvider.handleToolCall(
112 + 'default', // userId
113 + completion,
114 + { connectedAccountId: 'connected_account_123' } // Optional
115 + );
116 +
117 + // Continue the conversation with the tool outputs
118 + const followupCompletion = await openai.chat.completions.create({
119 + model: 'gpt-4',
120 + messages: [
121 + { role: 'system', content: 'You are a helpful assistant with GitHub tools.' },
122 + { role: 'user', content: 'Find information about the Composio SDK repository' },
123 + completion.choices[0].message,
124 + { role: 'tool', content: toolOutputs[0], tool_call_id: completion.choices[0].message.tool_calls[0].id }
125 + ],
126 + tools,
127 + });
128 +
129 + console.log(followupCompletion.choices[0].message.content);
130 +}
131 +```
132 +
133 +## Working with OpenAI Assistants
134 +
135 +The OpenAI Provider includes helper methods for working with OpenAI Assistants:
136 +
137 +```typescript
138 +import { Composio, OpenAIProvider } from '@composio/sdk';
139 +import OpenAI from 'openai';
140 +
141 +const composio = new Composio({
142 + apiKey: 'your-composio-api-key',
143 +});
144 +
145 +const openai = new OpenAI({
146 + apiKey: 'your-openai-api-key',
147 +});
148 +
149 +// Get the OpenAI Provider
150 +const openaiProvider = composio.provider as OpenAIProvider;
151 +
152 +// Get GitHub tools
153 +const tools = await composio.tools.get('default', {
154 + toolkits: ['github'],
155 +});
156 +
157 +// Create an assistant with Composio tools
158 +const assistant = await openai.beta.assistants.create({
159 + name: 'GitHub Assistant',
160 + instructions: 'You are a helpful assistant with GitHub tools.',
161 + model: 'gpt-4',
162 + tools,
163 +});
164 +
165 +// Create a thread
166 +const thread = await openai.beta.threads.create();
167 +
168 +// Add a message to the thread
169 +await openai.beta.threads.messages.create(thread.id, {
170 + role: 'user',
171 + content: 'Find information about the Composio SDK repository',
172 +});
173 +
174 +// Run the assistant
175 +const run = await openai.beta.threads.runs.create(thread.id, {
176 + assistant_id: assistant.id,
177 +});
178 +
179 +// Wait for the run to complete and handle any tool calls
180 +const finalRun = await openaiProvider.waitAndHandleAssistantToolCalls(
181 + 'default', // userId
182 + openai,
183 + run,
184 + thread,
185 + { connectedAccountId: 'connected_account_123' } // Optional
186 +);
187 +
188 +// Get the assistant's response
189 +const messages = await openai.beta.threads.messages.list(thread.id);
190 +console.log(messages.data[0].content);
191 +```
192 +
193 +## Handling Streaming Responses with Tool Calls
194 +
195 +The OpenAI Provider can also handle streaming responses with tool calls:
196 +
197 +```typescript
198 +import { Composio, OpenAIProvider } from '@composio/sdk';
199 +import OpenAI from 'openai';
200 +
201 +const composio = new Composio({
202 + apiKey: 'your-composio-api-key',
203 +});
204 +
205 +const openai = new OpenAI({
206 + apiKey: 'your-openai-api-key',
207 +});
208 +
209 +// Get the OpenAI Provider
210 +const openaiProvider = composio.provider as OpenAIProvider;
211 +
212 +// Get GitHub tools
213 +const tools = await composio.tools.get('default', {
214 + toolkits: ['github'],
215 +});
216 +
217 +// Create an assistant with Composio tools
218 +const assistant = await openai.beta.assistants.create({
219 + name: 'GitHub Assistant',
220 + instructions: 'You are a helpful assistant with GitHub tools.',
221 + model: 'gpt-4',
222 + tools,
223 +});
224 +
225 +// Create a thread
226 +const thread = await openai.beta.threads.create();
227 +
228 +// Add a message to the thread
229 +await openai.beta.threads.messages.create(thread.id, {
230 + role: 'user',
231 + content: 'Find information about the Composio SDK repository',
232 +});
233 +
234 +// Run the assistant with streaming
235 +const runStream = await openai.beta.threads.runs.createAndStream(thread.id, {
236 + assistant_id: assistant.id,
237 +});
238 +
239 +// Process the stream and handle tool calls
240 +for await (const event of openaiProvider.waitAndHandleAssistantStreamToolCalls(
241 + 'default', // userId
242 + openai,
243 + runStream,
244 + thread,
245 + { connectedAccountId: 'connected_account_123' } // Optional
246 +)) {
247 + // Process different event types
248 + if (event.event === 'thread.message.created') {
249 + console.log('New message created');
250 + } else if (event.event === 'thread.message.delta') {
251 + console.log('Message update:', event.data.delta.content);
252 + } else if (event.event === 'thread.run.requires_action') {
253 + console.log('Run requires action (tools being executed)');
254 + } else if (event.event === 'thread.run.completed') {
255 + console.log('Run completed');
256 + }
257 +}
258 +```
259 +
260 +## Modifiers with OpenAI Provider
261 +
262 +You can use modifiers with the OpenAI Provider to transform tools and tool execution:
263 +
264 +```typescript
265 +import { Composio, OpenAIProvider } from '@composio/sdk';
266 +
267 +const composio = new Composio({
268 + apiKey: 'your-composio-api-key',
269 +});
270 +
271 +// Get GitHub tools with modifiers
272 +const tools = await composio.tools.get('default', {
273 + toolkits: ['github'],
274 +}, {
275 + // Modify tool schema
276 + modifyToolSchema: (toolSlug, toolkitSlug, tool) => {
277 + // Make tool descriptions more concise for OpenAI
278 + if (tool.description && tool.description.length > 100) {
279 + tool.description = tool.description.substring(0, 100) + '...';
280 + }
281 + return tool;
282 + },
283 +
284 + // Modify parameters before execution
285 + beforeToolExecute: (toolSlug, toolkitSlug, params) => {
286 + console.log(`Executing ${toolSlug} tool`);
287 + return params;
288 + },
289 +
290 + // Transform results after execution
291 + afterToolExecute: (toolSlug, toolkitSlug, result) => {
292 + // Format the result data for better presentation
293 + if (result.successful && toolSlug === 'GITHUB_GET_REPO') {
294 + result.data = {
295 + name: result.data.name,
296 + description: result.data.description,
297 + stars: result.data.stargazers_count,
298 + forks: result.data.forks_count,
299 + url: result.data.html_url,
300 + };
301 + }
302 + return result;
303 + }
304 +});
305 +```
306 +
307 +## Type Definitions
308 +
309 +The OpenAI Provider exports these types:
310 +
311 +```typescript
312 +// OpenAI tool type (matches OpenAI's API)
313 +type OpenAiTool = OpenAI.ChatCompletionTool;
314 +
315 +// Collection of OpenAI tools
316 +type OpenAiToolCollection = Array<OpenAiTool>;
317 +
318 +// The provider class
319 +class OpenAIProvider extends BaseNonAgenticProvider<OpenAiToolCollection, OpenAiTool> {
320 + readonly name = 'openai';
321 +
322 + wrapTool(tool: Tool): OpenAiTool;
323 + wrapTools(tools: Tool[]): OpenAiToolCollection;
324 +
325 + executeToolCall(
326 + userId: string,
327 + tool: OpenAI.ChatCompletionMessageToolCall,
328 + options?: ExecuteToolFnOptions,
329 + modifiers?: ExecuteToolModifiers
330 + ): Promise<string>;
331 +
332 + handleToolCall(
333 + userId: string,
334 + chatCompletion: OpenAI.ChatCompletion,
335 + options?: ExecuteToolFnOptions,
336 + modifiers?: ExecuteToolModifiers
337 + ): Promise<string[]>;
338 +
339 + handleAssistantMessage(
340 + userId: string,
341 + run: OpenAI.Beta.Threads.Run,
342 + options?: ExecuteToolFnOptions,
343 + modifiers?: ExecuteToolModifiers
344 + ): Promise<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput[]>;
345 +
346 + waitAndHandleAssistantStreamToolCalls(
347 + userId: string,
348 + client: OpenAI,
349 + runStream: Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>,
350 + thread: OpenAI.Beta.Threads.Thread,
351 + options?: ExecuteToolFnOptions,
352 + modifiers?: ExecuteToolModifiers
353 + ): AsyncGenerator<OpenAI.Beta.Assistants.AssistantStreamEvent, void, unknown>;
354 +
355 + waitAndHandleAssistantToolCalls(
356 + userId: string,
357 + client: OpenAI,
358 + run: OpenAI.Beta.Threads.Run,
359 + thread: OpenAI.Beta.Threads.Thread,
360 + options?: ExecuteToolFnOptions,
361 + modifiers?: ExecuteToolModifiers
362 + ): Promise<OpenAI.Beta.Threads.Run>;
363 +}
364 +```
\ No newline at end of file
packages/core/.env.example new
+3
@@ -0,0 +1,3 @@
1 +COMPOSIO_LOG_LEVEL=
2 +COMPOSIO_API_KEY=
3 +COMPOSIO_API_BASE_URL=
\ No newline at end of file