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

next
md 333 lines 9.8 KB
Rendered Raw
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 The TypeScript SDK requires **Node.js 22.22.3 or newer** and is **ESM-only**. Use `import` syntax rather than CommonJS `require()`, and set `"type": "module"` in your project's `package.json`.
8
9 For the current session-based examples and framework setup, see the [SDK quickstart](https://docs.composio.dev/docs/quickstart).
10
11 Install the Composio SDK using npm, yarn, or pnpm:
12
13 ```bash
14 # Using npm
15 npm install @composio/core
16
17 # Using yarn
18 yarn add @composio/core
19
20 # Using pnpm
21 pnpm add @composio/core
22 ```
23
24 ## Initialization
25
26 To use the SDK, you need to initialize it with your API key:
27
28 ```typescript
29 import { Composio } from '@composio/core';
30
31 // Initialize the SDK
32 const composio = new Composio({
33 apiKey: 'your-api-key',
34 });
35 ```
36
37 You can also customize the initialization with additional options:
38
39 ```typescript
40 import { Composio } from '@composio/core';
41 import { OpenAIProvider } from '@composio/openai';
42
43 // Initialize with custom provider and options
44 const composio = new Composio({
45 apiKey: 'your-api-key',
46 baseURL: 'https://api.composio.dev', // Optional: Custom API endpoint
47 allowTracking: true, // Optional: Enable/disable telemetry
48 provider: new OpenAIProvider(), // Optional: Custom provider
49 toolkitVersions: { github: '12082025_00', slack: 'latest' }, // Optional: Toolkit versions
50 });
51 ```
52
53 ### Toolkit Versions
54
55 Toolkit versions allow you to pin specific versions of tools and triggers, ensuring consistency across your application. By default, Composio uses the `'latest'` version for all toolkits, but you can specify exact versions for production stability.
56
57 #### Version Format
58
59 Toolkit versions follow the format `DDMMYYYY_NN`, where:
60 - `DD` = Day (01-31)
61 - `MM` = Month (01-12)
62 - `YYYY` = Year
63 - `NN` = Version number for that day (00, 01, 02, etc.)
64
65 Example: `12082025_00` represents version 00 released on August 12, 2025.
66
67 #### Configuration Options
68
69 **Option 1: Specific Versions per Toolkit (Recommended for Production)**
70
71 ```typescript
72 const composio = new Composio({
73 toolkitVersions: {
74 github: '12082025_00',
75 slack: '10082025_01',
76 gmail: 'latest', // You can mix specific versions with 'latest'
77 }
78 });
79 ```
80
81 **Option 2: Using Environment Variables**
82
83 You can set toolkit versions using environment variables:
84
85 ```bash
86 # Set specific versions for individual toolkits
87 export COMPOSIO_TOOLKIT_VERSION_GITHUB=12082025_00
88 export COMPOSIO_TOOLKIT_VERSION_SLACK=10082025_01
89 export COMPOSIO_TOOLKIT_VERSION_GMAIL=latest
90 ```
91
92 Then initialize Composio without specifying `toolkitVersions`:
93
94 ```typescript
95 const composio = new Composio({
96 apiKey: 'your-api-key'
97 // Will automatically use environment variables
98 });
99 ```
100
101 **Option 3: Latest version for all toolkits**
102 If omitted, SDK will use `latest` version for all the toolkits
103
104 ```typescript
105 const composio = new Composio({
106 apiKey: 'your-api-key',
107 // since omitted, this will use `latest` for all toolkits
108 })
109 ```
110
111 #### Version Behavior
112
113 - **Tools & Triggers:** The toolkit version configuration applies to both tools and triggers
114 - **Override Support:** Tools can override the global version for specific operations:
115 - When executing tools: Pass a `version` parameter in the execute call to override the configured version
116 - **Defaults:** If no version is specified, the SDK defaults to `'latest'`
117 - **Triggers:** Trigger types always use the global toolkit version configured at initialization. To use a specific version for triggers, set it in the `toolkitVersions` configuration when creating the Composio instance.
118
119 #### Best Practices
120
121 1. **Use `'latest'` for Development:** Get the newest features and improvements automatically
122 2. **Pin Versions in Production:** Use specific version numbers to prevent unexpected changes
123 3. **Test Before Upgrading:** When moving to a new version, test thoroughly before deploying
124 4. **Version Per Toolkit:** Different toolkits can use different versions based on your needs
125
126 #### Example: Production Configuration
127
128 ```typescript
129 import { Composio } from '@composio/core';
130
131 // Production setup with pinned versions
132 const composio = new Composio({
133 apiKey: process.env.COMPOSIO_API_KEY,
134 toolkitVersions: {
135 // Pin critical toolkits to stable versions
136 github: '12082025_00',
137 slack: '10082025_01',
138 gmail: '15082025_00',
139 // Use latest for non-critical toolkits
140 hackernews: 'latest'
141 }
142 });
143 ```
144
145 ## Basic Usage
146
147 ### Listing Available Toolkits
148
149 Toolkits are collections of related tools (like GitHub, Gmail, etc.). You can list all available toolkits:
150
151 ```typescript
152 // Get all toolkits
153 const allToolkits = await composio.toolkits.get({});
154 console.log(allToolkits.items);
155
156 // Get toolkits by category
157 const devToolkits = await composio.toolkits.get({
158 category: 'developer-tools',
159 });
160 ```
161
162 ### Getting Tools from a Toolkit
163
164 You can get tools from a specific toolkit:
165
166 ```typescript
167 // Get all tools from the GitHub toolkit
168 const githubTools = await composio.tools.get('default', {
169 toolkits: ['github'],
170 });
171
172 // Get a specific tool by slug
173 const getRepoTool = await composio.tools.get('default', 'GITHUB_GET_REPO');
174 ```
175
176 ### Executing a Tool
177
178 To execute a tool, you need to provide the tool's slug and the parameters:
179
180 ```typescript
181 // Execute a GitHub tool
182 const result = await composio.tools.execute('GITHUB_GET_REPO', {
183 userId: 'default',
184 arguments: {
185 owner: 'composio',
186 repo: 'sdk',
187 },
188 });
189
190 // Check if the execution was successful
191 if (result.successful) {
192 console.log('Repository details:', result.data);
193 } else {
194 console.error('Error:', result.error);
195 }
196 ```
197
198 ## Working with Connected Accounts
199
200 Many tools require authentication with external services. Composio manages this through connected accounts.
201
202 ### Setting Up a Connection
203
204 To create a connected account, you need to:
205
206 1. Authorize the toolkit
207 2. Wait for the user to complete the authentication flow
208
209 ```typescript
210 // Step 1: Authorize the toolkit
211 const connectionRequest = await composio.toolkits.authorize('user123', 'github');
212
213 // This gives you a redirect URL
214 console.log('Redirect the user to:', connectionRequest.redirectUrl);
215
216 // Step 2: Wait for the connection to be established
217 // This should be called after the user completes the auth flow
218 const connectedAccount = await composio.connectedAccounts.waitForConnection(connectionRequest.id);
219 console.log('Connected account:', connectedAccount);
220 ```
221
222 ### Using a Connected Account with Tools
223
224 Once you have a connected account, you can use it when executing tools:
225
226 ```typescript
227 // Execute a tool with a connected account
228 const result = await composio.tools.execute('GITHUB_GET_REPOS', {
229 userId: 'user123',
230 connectedAccountId: connectedAccount.id,
231 arguments: {},
232 });
233 ```
234
235 ## Integration with OpenAI
236
237 Composio integrates seamlessly with OpenAI. Here's an example of using Composio tools with OpenAI:
238
239 ```typescript
240 import { Composio } from '@composio/core';
241 import OpenAI from 'openai';
242
243 // Initialize Composio and OpenAI
244 const composio = new Composio({
245 apiKey: 'your-composio-api-key',
246 });
247
248 const openai = new OpenAI({
249 apiKey: 'your-openai-api-key',
250 });
251
252 // Get tools from the GitHub toolkit
253 const tools = await composio.tools.get('default', {
254 toolkits: ['github'],
255 });
256
257 // Create a chat completion with OpenAI using the tools
258 const completion = await openai.chat.completions.create({
259 model: 'gpt-5',
260 messages: [
261 { role: 'system', content: 'You are a helpful assistant with access to GitHub tools.' },
262 { role: 'user', content: 'List the repositories in the Composio organization' },
263 ],
264 tools, // Pass the tools to OpenAI
265 });
266
267 // If the assistant wants to use a tool
268 if (completion.choices[0].message.tool_calls) {
269 // Execute each tool call
270 for (const toolCall of completion.choices[0].message.tool_calls) {
271 // Parse the arguments
272 const args = JSON.parse(toolCall.function.arguments);
273
274 // Execute the tool
275 const result = await composio.tools.execute(toolCall.function.name, {
276 userId: 'default',
277 arguments: args,
278 });
279
280 // Use the result in your application
281 console.log(`Tool ${toolCall.function.name} result:`, result.data);
282 }
283 }
284 ```
285
286 For a more complete integration, check out the [OpenAI Provider example](../examples/openai).
287
288 ## Creating Custom Tools
289
290 You can extend Tool Router sessions with your own local custom tools:
291
292 ```typescript
293 import { Composio, experimental_createTool } from '@composio/core';
294 import { z } from 'zod';
295
296 const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
297
298 const customTool = experimental_createTool('WEATHER_FORECAST', {
299 name: 'Weather Forecast',
300 description: 'Get the weather forecast for a location',
301 inputParams: z.object({
302 location: z.string().describe('The location to get the forecast for'),
303 days: z.number().optional().default(3).describe('Number of days for the forecast'),
304 }),
305 execute: async (input) => {
306 const { location, days = 3 } = input;
307 const forecast = await getWeatherForecast(location, days);
308 return { forecast };
309 },
310 });
311
312 const session = await composio.create('default', {
313 experimental: { localTools: [customTool] },
314 });
315
316 const result = await session.execute('WEATHER_FORECAST', {
317 location: 'San Francisco, CA',
318 days: 5,
319 });
320
321 console.log(result.data?.forecast);
322 ```
323
324 For more advanced session management features, check out the [Session Management Guide](./advanced/session-management.md).
325
326 ## Next Steps
327
328 Now that you understand the basics, you can:
329
330 - Explore [more examples](../examples) to see how to use Composio in different scenarios
331 - Learn about [custom providers](./api/providers.md) to integrate with other AI frameworks
332 - Understand [error handling](./advanced/error-handling.md) to make your application more robust
333 - Implement [modifiers](./advanced/modifiers.md) to customize tool execution